diff --git a/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs b/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs index 1356bb6288..f2f8147cc9 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix}; +use ruff_diagnostics::Fix; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; @@ -38,92 +38,64 @@ pub(crate) fn bindings(checker: &Checker) { .dummy_variable_rgx .is_match(binding.name(checker.source())) { - let mut diagnostic = Diagnostic::new( - pyflakes::rules::UnusedVariable { - name: binding.name(checker.source()).to_string(), - }, - binding.range(), - ); - diagnostic.try_set_fix(|| { - pyflakes::fixes::remove_exception_handler_assignment(binding, checker.locator) + checker + .report_diagnostic( + pyflakes::rules::UnusedVariable { + name: binding.name(checker.source()).to_string(), + }, + binding.range(), + ) + .try_set_fix(|| { + pyflakes::fixes::remove_exception_handler_assignment( + binding, + checker.locator, + ) .map(Fix::safe_edit) - }); - checker.report_diagnostic(diagnostic); + }); } } if checker.enabled(Rule::InvalidAllFormat) { - if let Some(diagnostic) = pylint::rules::invalid_all_format(binding) { - checker.report_diagnostic(diagnostic); - } + pylint::rules::invalid_all_format(checker, binding); } if checker.enabled(Rule::InvalidAllObject) { - if let Some(diagnostic) = pylint::rules::invalid_all_object(binding) { - checker.report_diagnostic(diagnostic); - } + pylint::rules::invalid_all_object(checker, binding); } if checker.enabled(Rule::NonAsciiName) { - if let Some(diagnostic) = pylint::rules::non_ascii_name(binding, checker.locator) { - checker.report_diagnostic(diagnostic); - } + pylint::rules::non_ascii_name(checker, binding); } if checker.enabled(Rule::UnconventionalImportAlias) { - if let Some(diagnostic) = flake8_import_conventions::rules::unconventional_import_alias( + flake8_import_conventions::rules::unconventional_import_alias( checker, binding, &checker.settings.flake8_import_conventions.aliases, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::UnaliasedCollectionsAbcSetImport) { - if let Some(diagnostic) = - flake8_pyi::rules::unaliased_collections_abc_set_import(checker, binding) - { - checker.report_diagnostic(diagnostic); - } + flake8_pyi::rules::unaliased_collections_abc_set_import(checker, binding); } if !checker.source_type.is_stub() && checker.enabled(Rule::UnquotedTypeAlias) { flake8_type_checking::rules::unquoted_type_alias(checker, binding); } if checker.enabled(Rule::UnsortedDunderSlots) { - if let Some(diagnostic) = ruff::rules::sort_dunder_slots(checker, binding) { - checker.report_diagnostic(diagnostic); - } + ruff::rules::sort_dunder_slots(checker, binding); } if checker.enabled(Rule::UsedDummyVariable) { - if let Some(diagnostic) = ruff::rules::used_dummy_variable(checker, binding, binding_id) - { - checker.report_diagnostic(diagnostic); - } + ruff::rules::used_dummy_variable(checker, binding, binding_id); } if checker.enabled(Rule::AssignmentInAssert) { - if let Some(diagnostic) = ruff::rules::assignment_in_assert(checker, binding) { - checker.report_diagnostic(diagnostic); - } + ruff::rules::assignment_in_assert(checker, binding); } if checker.enabled(Rule::PytestUnittestRaisesAssertion) { - if let Some(diagnostic) = - flake8_pytest_style::rules::unittest_raises_assertion_binding(checker, binding) - { - checker.report_diagnostic(diagnostic); - } + flake8_pytest_style::rules::unittest_raises_assertion_binding(checker, binding); } if checker.enabled(Rule::ForLoopWrites) { - if let Some(diagnostic) = refurb::rules::for_loop_writes_binding(checker, binding) { - checker.report_diagnostic(diagnostic); - } + refurb::rules::for_loop_writes_binding(checker, binding); } if checker.enabled(Rule::CustomTypeVarForSelf) { - if let Some(diagnostic) = - flake8_pyi::rules::custom_type_var_instead_of_self(checker, binding) - { - checker.report_diagnostic(diagnostic); - } + flake8_pyi::rules::custom_type_var_instead_of_self(checker, binding); } if checker.enabled(Rule::PrivateTypeParameter) { - if let Some(diagnostic) = pyupgrade::rules::private_type_parameter(checker, binding) { - checker.report_diagnostic(diagnostic); - } + pyupgrade::rules::private_type_parameter(checker, binding); } } } 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 36a8af20fa..72ef6bde28 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix}; +use ruff_diagnostics::Fix; use ruff_python_semantic::analyze::visibility; use ruff_python_semantic::{Binding, BindingKind, Imported, ResolvedReference, ScopeKind}; use ruff_text_size::Ranged; @@ -112,12 +112,12 @@ pub(crate) fn deferred_scopes(checker: &Checker) { .map(|id| checker.semantic.reference(*id)) .all(ResolvedReference::is_load) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pylint::rules::GlobalVariableNotAssigned { name: (*name).to_string(), }, binding.range(), - )); + ); } } } @@ -146,12 +146,12 @@ pub(crate) fn deferred_scopes(checker: &Checker) { if scope.kind.is_generator() { continue; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pylint::rules::RedefinedArgumentFromLocal { name: name.to_string(), }, binding.range(), - )); + ); } } } @@ -186,13 +186,13 @@ pub(crate) fn deferred_scopes(checker: &Checker) { continue; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::ImportShadowedByLoopVar { name: name.to_string(), row: checker.compute_source_row(shadowed.start()), }, binding.range(), - )); + ); } } } @@ -331,7 +331,7 @@ pub(crate) fn deferred_scopes(checker: &Checker) { // Create diagnostics for each statement. for (source, entries) in &redefinitions { for (shadowed, binding) in entries { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( pyflakes::rules::RedefinedWhileUnused { name: binding.name(checker.source()).to_string(), row: checker.compute_source_row(shadowed.start()), @@ -346,8 +346,6 @@ pub(crate) fn deferred_scopes(checker: &Checker) { if let Some(fix) = source.as_ref().and_then(|source| fixes.get(source)) { diagnostic.set_fix(fix.clone()); } - - checker.report_diagnostic(diagnostic); } } } 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 9a68550216..7ef76d9382 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs @@ -17,14 +17,7 @@ pub(crate) fn except_handler(except_handler: &ExceptHandler, checker: &Checker) range: _, }) => { if checker.enabled(Rule::BareExcept) { - if let Some(diagnostic) = pycodestyle::rules::bare_except( - type_.as_deref(), - body, - except_handler, - checker.locator, - ) { - checker.report_diagnostic(diagnostic); - } + pycodestyle::rules::bare_except(checker, type_.as_deref(), body, except_handler); } if checker.enabled(Rule::RaiseWithoutFromInsideExcept) { flake8_bugbear::rules::raise_without_from_inside_except( diff --git a/crates/ruff_linter/src/checkers/ast/analyze/expression.rs b/crates/ruff_linter/src/checkers/ast/analyze/expression.rs index de027ff99e..e6de351398 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/expression.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/expression.rs @@ -1,8 +1,6 @@ use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Operator}; use ruff_python_literal::cformat::{CFormatError, CFormatErrorType}; -use ruff_diagnostics::Diagnostic; - use ruff_python_ast::types::Node; use ruff_python_semantic::ScopeKind; use ruff_python_semantic::analyze::typing; @@ -195,14 +193,13 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { let check_too_many_expressions = checker.enabled(Rule::ExpressionsInStarAssignment); let check_two_starred_expressions = checker.enabled(Rule::MultipleStarredExpressions); - if let Some(diagnostic) = pyflakes::rules::starred_expressions( + pyflakes::rules::starred_expressions( + checker, elts, check_too_many_expressions, check_two_starred_expressions, expr.range(), - ) { - checker.report_diagnostic(diagnostic); - } + ); } } Expr::Name(ast::ExprName { id, ctx, range }) => { @@ -527,12 +524,12 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { match pyflakes::format::FormatSummary::try_from(string_value.to_str()) { Err(e) => { if checker.enabled(Rule::StringDotFormatInvalidFormat) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::StringDotFormatInvalidFormat { message: pyflakes::format::error_to_string(&e), }, location, - )); + ); } } Ok(summary) => { @@ -936,9 +933,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { pylint::rules::repeated_keyword_argument(checker, call); } if checker.enabled(Rule::PytestPatchWithLambda) { - if let Some(diagnostic) = flake8_pytest_style::rules::patch_with_lambda(call) { - checker.report_diagnostic(diagnostic); - } + flake8_pytest_style::rules::patch_with_lambda(checker, call); } if checker.any_enabled(&[ Rule::PytestParametrizeNamesWrongType, @@ -1286,22 +1281,22 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { .. }) => { if checker.enabled(Rule::PercentFormatUnsupportedFormatCharacter) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::PercentFormatUnsupportedFormatCharacter { char: c, }, location, - )); + ); } } Err(e) => { if checker.enabled(Rule::PercentFormatInvalidFormat) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::PercentFormatInvalidFormat { message: e.to_string(), }, location, - )); + ); } } Ok(summary) => { @@ -1365,10 +1360,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { op: Operator::Add, .. }) => { if checker.enabled(Rule::ExplicitStringConcatenation) { - if let Some(diagnostic) = flake8_implicit_str_concat::rules::explicit(expr, checker) - { - checker.report_diagnostic(diagnostic); - } + flake8_implicit_str_concat::rules::explicit(checker, expr); } if checker.enabled(Rule::CollectionLiteralConcatenation) { ruff::rules::collection_literal_concatenation(checker, expr); diff --git a/crates/ruff_linter/src/checkers/ast/analyze/statement.rs b/crates/ruff_linter/src/checkers/ast/analyze/statement.rs index 059c831a17..69f7dfd8d8 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/statement.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/statement.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_python_ast::helpers; use ruff_python_ast::types::Node; use ruff_python_ast::{self as ast, Expr, Stmt}; @@ -39,12 +38,12 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { if !checker.semantic.scope_id.is_global() { for name in names { if checker.semantic.nonlocal(name).is_none() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pylint::rules::NonlocalWithoutBinding { name: name.to_string(), }, name.range(), - )); + ); } } } @@ -55,22 +54,20 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } Stmt::Break(_) => { if checker.enabled(Rule::BreakOutsideLoop) { - if let Some(diagnostic) = pyflakes::rules::break_outside_loop( + pyflakes::rules::break_outside_loop( + checker, stmt, &mut checker.semantic.current_statements().skip(1), - ) { - checker.report_diagnostic(diagnostic); - } + ); } } Stmt::Continue(_) => { if checker.enabled(Rule::ContinueOutsideLoop) { - if let Some(diagnostic) = pyflakes::rules::continue_outside_loop( + pyflakes::rules::continue_outside_loop( + checker, stmt, &mut checker.semantic.current_statements().skip(1), - ) { - checker.report_diagnostic(diagnostic); - } + ); } } Stmt::FunctionDef( @@ -98,9 +95,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { fastapi::rules::fastapi_unused_path_parameter(checker, function_def); } if checker.enabled(Rule::AmbiguousFunctionName) { - if let Some(diagnostic) = pycodestyle::rules::ambiguous_function_name(name) { - checker.report_diagnostic(diagnostic); - } + pycodestyle::rules::ambiguous_function_name(checker, name); } if checker.enabled(Rule::InvalidBoolReturnType) { pylint::rules::invalid_bool_return(checker, function_def); @@ -121,15 +116,14 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { pylint::rules::invalid_str_return(checker, function_def); } if checker.enabled(Rule::InvalidFunctionName) { - if let Some(diagnostic) = pep8_naming::rules::invalid_function_name( + pep8_naming::rules::invalid_function_name( + checker, stmt, name, decorator_list, &checker.settings.pep8_naming.ignore_names, &checker.semantic, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.source_type.is_stub() { if checker.enabled(Rule::PassStatementStubBody) { @@ -179,14 +173,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { flake8_pyi::rules::pep_484_positional_parameter(checker, function_def); } if checker.enabled(Rule::DunderFunctionName) { - if let Some(diagnostic) = pep8_naming::rules::dunder_function_name( + pep8_naming::rules::dunder_function_name( + checker, checker.semantic.current_scope(), stmt, name, &checker.settings.pep8_naming.ignore_names, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::GlobalStatement) { pylint::rules::global_statement(checker, name); @@ -231,14 +224,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } if checker.enabled(Rule::ComplexStructure) { - if let Some(diagnostic) = mccabe::rules::function_is_too_complex( + mccabe::rules::function_is_too_complex( + checker, stmt, name, body, checker.settings.mccabe.max_complexity, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::HardcodedPasswordDefault) { flake8_bandit::rules::hardcoded_password_default(checker, parameters); @@ -258,31 +250,28 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { pylint::rules::too_many_positional_arguments(checker, function_def); } if checker.enabled(Rule::TooManyReturnStatements) { - if let Some(diagnostic) = pylint::rules::too_many_return_statements( + pylint::rules::too_many_return_statements( + checker, stmt, body, checker.settings.pylint.max_returns, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::TooManyBranches) { - if let Some(diagnostic) = pylint::rules::too_many_branches( + pylint::rules::too_many_branches( + checker, stmt, body, checker.settings.pylint.max_branches, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::TooManyStatements) { - if let Some(diagnostic) = pylint::rules::too_many_statements( + pylint::rules::too_many_statements( + checker, stmt, body, checker.settings.pylint.max_statements, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.any_enabled(&[ Rule::PytestFixtureIncorrectParenthesesStyle, @@ -451,28 +440,24 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { pyupgrade::rules::unnecessary_class_parentheses(checker, class_def); } if checker.enabled(Rule::AmbiguousClassName) { - if let Some(diagnostic) = pycodestyle::rules::ambiguous_class_name(name) { - checker.report_diagnostic(diagnostic); - } + pycodestyle::rules::ambiguous_class_name(checker, name); } if checker.enabled(Rule::InvalidClassName) { - if let Some(diagnostic) = pep8_naming::rules::invalid_class_name( + pep8_naming::rules::invalid_class_name( + checker, stmt, name, &checker.settings.pep8_naming.ignore_names, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::ErrorSuffixOnExceptionName) { - if let Some(diagnostic) = pep8_naming::rules::error_suffix_on_exception_name( + pep8_naming::rules::error_suffix_on_exception_name( + checker, stmt, arguments.as_deref(), name, &checker.settings.pep8_naming.ignore_names, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if !checker.source_type.is_stub() { if checker.any_enabled(&[ @@ -611,11 +596,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } if checker.enabled(Rule::Debugger) { - if let Some(diagnostic) = - flake8_debugger::rules::debugger_import(stmt, None, &alias.name) - { - checker.report_diagnostic(diagnostic); - } + flake8_debugger::rules::debugger_import(checker, stmt, None, &alias.name); } if checker.enabled(Rule::BannedApi) { flake8_tidy_imports::rules::banned_api( @@ -638,94 +619,74 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { pylint::rules::manual_from_import(checker, stmt, alias, names); } if checker.enabled(Rule::ImportSelf) { - if let Some(diagnostic) = - pylint::rules::import_self(alias, checker.module.qualified_name()) - { - checker.report_diagnostic(diagnostic); - } + 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 let Some(diagnostic) = - pep8_naming::rules::constant_imported_as_non_constant( - name, - asname, - alias, - stmt, - &checker.settings.pep8_naming.ignore_names, - ) - { - checker.report_diagnostic(diagnostic); - } - } - if checker.enabled(Rule::LowercaseImportedAsNonLowercase) { - if let Some(diagnostic) = - pep8_naming::rules::lowercase_imported_as_non_lowercase( - name, - asname, - alias, - stmt, - &checker.settings.pep8_naming.ignore_names, - ) - { - checker.report_diagnostic(diagnostic); - } - } - if checker.enabled(Rule::CamelcaseImportedAsLowercase) { - if let Some(diagnostic) = - pep8_naming::rules::camelcase_imported_as_lowercase( - name, - asname, - alias, - stmt, - &checker.settings.pep8_naming.ignore_names, - ) - { - checker.report_diagnostic(diagnostic); - } - } - if checker.enabled(Rule::CamelcaseImportedAsConstant) { - if let Some(diagnostic) = pep8_naming::rules::camelcase_imported_as_constant( + pep8_naming::rules::constant_imported_as_non_constant( + checker, name, asname, alias, stmt, &checker.settings.pep8_naming.ignore_names, - ) { - checker.report_diagnostic(diagnostic); - } + ); + } + if checker.enabled(Rule::LowercaseImportedAsNonLowercase) { + pep8_naming::rules::lowercase_imported_as_non_lowercase( + checker, + name, + asname, + alias, + stmt, + &checker.settings.pep8_naming.ignore_names, + ); + } + if checker.enabled(Rule::CamelcaseImportedAsLowercase) { + pep8_naming::rules::camelcase_imported_as_lowercase( + checker, + name, + asname, + alias, + stmt, + &checker.settings.pep8_naming.ignore_names, + ); + } + if checker.enabled(Rule::CamelcaseImportedAsConstant) { + pep8_naming::rules::camelcase_imported_as_constant( + checker, + name, + asname, + alias, + stmt, + &checker.settings.pep8_naming.ignore_names, + ); } if checker.enabled(Rule::CamelcaseImportedAsAcronym) { - if let Some(diagnostic) = pep8_naming::rules::camelcase_imported_as_acronym( + pep8_naming::rules::camelcase_imported_as_acronym( name, asname, alias, stmt, checker, - ) { - checker.report_diagnostic(diagnostic); - } + ); } } if checker.enabled(Rule::BannedImportAlias) { if let Some(asname) = &alias.asname { - if let Some(diagnostic) = - flake8_import_conventions::rules::banned_import_alias( - stmt, - &alias.name, - asname, - &checker.settings.flake8_import_conventions.banned_aliases, - ) - { - checker.report_diagnostic(diagnostic); - } + flake8_import_conventions::rules::banned_import_alias( + checker, + stmt, + &alias.name, + asname, + &checker.settings.flake8_import_conventions.banned_aliases, + ); } } if checker.enabled(Rule::PytestIncorrectPytestImport) { - if let Some(diagnostic) = flake8_pytest_style::rules::import( + flake8_pytest_style::rules::import( + checker, stmt, &alias.name, alias.asname.as_deref(), - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::BuiltinImportShadowing) { flake8_builtins::rules::builtin_import_shadowing(checker, alias); @@ -837,11 +798,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } if checker.enabled(Rule::PytestIncorrectPytestImport) { - if let Some(diagnostic) = - flake8_pytest_style::rules::import_from(stmt, module, level) - { - checker.report_diagnostic(diagnostic); - } + flake8_pytest_style::rules::import_from(checker, stmt, module, level); } if checker.source_type.is_stub() { if checker.enabled(Rule::FutureAnnotationsInStub) { @@ -856,119 +813,98 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } else if &alias.name == "*" { if checker.enabled(Rule::UndefinedLocalWithNestedImportStarUsage) { if !matches!(checker.semantic.current_scope().kind, ScopeKind::Module) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::UndefinedLocalWithNestedImportStarUsage { name: helpers::format_import_from(level, module).to_string(), }, stmt.range(), - )); + ); } } if checker.enabled(Rule::UndefinedLocalWithImportStar) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::UndefinedLocalWithImportStar { name: helpers::format_import_from(level, module).to_string(), }, stmt.range(), - )); + ); } } if checker.enabled(Rule::RelativeImports) { - if let Some(diagnostic) = flake8_tidy_imports::rules::banned_relative_import( + flake8_tidy_imports::rules::banned_relative_import( checker, stmt, level, module, checker.module.qualified_name(), checker.settings.flake8_tidy_imports.ban_relative_imports, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::Debugger) { - if let Some(diagnostic) = - flake8_debugger::rules::debugger_import(stmt, module, &alias.name) - { - checker.report_diagnostic(diagnostic); - } + flake8_debugger::rules::debugger_import(checker, stmt, module, &alias.name); } if checker.enabled(Rule::BannedImportAlias) { if let Some(asname) = &alias.asname { let qualified_name = helpers::format_import_from_member(level, module, &alias.name); - if let Some(diagnostic) = - flake8_import_conventions::rules::banned_import_alias( - stmt, - &qualified_name, - asname, - &checker.settings.flake8_import_conventions.banned_aliases, - ) - { - checker.report_diagnostic(diagnostic); - } + flake8_import_conventions::rules::banned_import_alias( + checker, + stmt, + &qualified_name, + asname, + &checker.settings.flake8_import_conventions.banned_aliases, + ); } } if let Some(asname) = &alias.asname { if checker.enabled(Rule::ConstantImportedAsNonConstant) { - if let Some(diagnostic) = - pep8_naming::rules::constant_imported_as_non_constant( - &alias.name, - asname, - alias, - stmt, - &checker.settings.pep8_naming.ignore_names, - ) - { - checker.report_diagnostic(diagnostic); - } - } - if checker.enabled(Rule::LowercaseImportedAsNonLowercase) { - if let Some(diagnostic) = - pep8_naming::rules::lowercase_imported_as_non_lowercase( - &alias.name, - asname, - alias, - stmt, - &checker.settings.pep8_naming.ignore_names, - ) - { - checker.report_diagnostic(diagnostic); - } - } - if checker.enabled(Rule::CamelcaseImportedAsLowercase) { - if let Some(diagnostic) = - pep8_naming::rules::camelcase_imported_as_lowercase( - &alias.name, - asname, - alias, - stmt, - &checker.settings.pep8_naming.ignore_names, - ) - { - checker.report_diagnostic(diagnostic); - } - } - if checker.enabled(Rule::CamelcaseImportedAsConstant) { - if let Some(diagnostic) = pep8_naming::rules::camelcase_imported_as_constant( + pep8_naming::rules::constant_imported_as_non_constant( + checker, &alias.name, asname, alias, stmt, &checker.settings.pep8_naming.ignore_names, - ) { - checker.report_diagnostic(diagnostic); - } + ); + } + if checker.enabled(Rule::LowercaseImportedAsNonLowercase) { + pep8_naming::rules::lowercase_imported_as_non_lowercase( + checker, + &alias.name, + asname, + alias, + stmt, + &checker.settings.pep8_naming.ignore_names, + ); + } + if checker.enabled(Rule::CamelcaseImportedAsLowercase) { + pep8_naming::rules::camelcase_imported_as_lowercase( + checker, + &alias.name, + asname, + alias, + stmt, + &checker.settings.pep8_naming.ignore_names, + ); + } + if checker.enabled(Rule::CamelcaseImportedAsConstant) { + pep8_naming::rules::camelcase_imported_as_constant( + checker, + &alias.name, + asname, + alias, + stmt, + &checker.settings.pep8_naming.ignore_names, + ); } if checker.enabled(Rule::CamelcaseImportedAsAcronym) { - if let Some(diagnostic) = pep8_naming::rules::camelcase_imported_as_acronym( + pep8_naming::rules::camelcase_imported_as_acronym( &alias.name, asname, alias, stmt, checker, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if !checker.source_type.is_stub() { if checker.enabled(Rule::UselessImportAlias) { @@ -981,23 +917,21 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } if checker.enabled(Rule::ImportSelf) { - if let Some(diagnostic) = pylint::rules::import_from_self( + pylint::rules::import_from_self( + checker, level, module, names, checker.module.qualified_name(), - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::BannedImportFrom) { - if let Some(diagnostic) = flake8_import_conventions::rules::banned_import_from( + flake8_import_conventions::rules::banned_import_from( + checker, stmt, &helpers::format_import_from(level, module), &checker.settings.flake8_import_conventions.banned_from, - ) { - checker.report_diagnostic(diagnostic); - } + ); } if checker.enabled(Rule::ByteStringUsage) { flake8_pyi::rules::bytestring_import(checker, import_from); @@ -1212,7 +1146,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ) => { if !checker.semantic.in_type_checking_block() { if checker.enabled(Rule::Assert) { - checker.report_diagnostic(flake8_bandit::rules::assert_used(stmt)); + flake8_bandit::rules::assert_used(checker, stmt); } } if checker.enabled(Rule::AssertTuple) { @@ -1409,11 +1343,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } if checker.enabled(Rule::DefaultExceptNotLast) { - if let Some(diagnostic) = - pyflakes::rules::default_except_not_last(handlers, checker.locator) - { - checker.report_diagnostic(diagnostic); - } + pyflakes::rules::default_except_not_last(checker, handlers, checker.locator); } if checker.any_enabled(&[ Rule::DuplicateHandlerException, @@ -1508,9 +1438,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } if checker.enabled(Rule::PandasDfVariableName) { - if let Some(diagnostic) = pandas_vet::rules::assignment_to_df(targets) { - checker.report_diagnostic(diagnostic); - } + pandas_vet::rules::assignment_to_df(checker, targets); } if checker .settings @@ -1704,11 +1632,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { pylint::rules::named_expr_without_context(checker, value); } if checker.enabled(Rule::AsyncioDanglingTask) { - if let Some(diagnostic) = - ruff::rules::asyncio_dangling_task(value, checker.semantic()) - { - checker.report_diagnostic(diagnostic); - } + ruff::rules::asyncio_dangling_task(checker, value, checker.semantic()); } if checker.enabled(Rule::RepeatedAppend) { refurb::rules::repeated_append(checker, stmt); 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 dbe2c540ef..3060e07f63 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_python_semantic::Exceptions; use ruff_python_stdlib::builtins::version_builtin_was_added; @@ -15,12 +14,12 @@ pub(crate) fn unresolved_references(checker: &Checker) { for reference in checker.semantic.unresolved_references() { if reference.is_wildcard_import() { if checker.enabled(Rule::UndefinedLocalWithImportStarUsage) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::UndefinedLocalWithImportStarUsage { name: reference.name(checker.source()).to_string(), }, reference.range(), - )); + ); } } else { if checker.enabled(Rule::UndefinedName) { @@ -42,13 +41,13 @@ pub(crate) fn unresolved_references(checker: &Checker) { let symbol_name = reference.name(checker.source()); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( pyflakes::rules::UndefinedName { name: symbol_name.to_string(), minor_version_builtin_added: version_builtin_was_added(symbol_name), }, reference.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/checkers/ast/mod.rs b/crates/ruff_linter/src/checkers/ast/mod.rs index 694ff08a87..92783663c0 100644 --- a/crates/ruff_linter/src/checkers/ast/mod.rs +++ b/crates/ruff_linter/src/checkers/ast/mod.rs @@ -31,7 +31,7 @@ use ruff_python_parser::semantic_errors::{ }; use rustc_hash::{FxHashMap, FxHashSet}; -use ruff_diagnostics::{Diagnostic, Edit, IsolationLevel}; +use ruff_diagnostics::{Diagnostic, Edit, IsolationLevel, Violation}; use ruff_notebook::{CellOffsets, NotebookIndex}; use ruff_python_ast::helpers::{collect_import_from_member, is_docstring_stmt, to_module_path}; use ruff_python_ast::identifier::Identifier; @@ -66,7 +66,7 @@ use crate::importer::{ImportRequest, Importer, ResolutionError}; use crate::noqa::NoqaMapping; use crate::package::PackageRoot; use crate::preview::{is_semantic_errors_enabled, is_undefined_export_in_dunder_init_enabled}; -use crate::registry::Rule; +use crate::registry::{AsRule, Rule}; use crate::rules::pyflakes::rules::{ LateFutureImport, ReturnOutsideFunction, YieldOutsideFunction, }; @@ -379,10 +379,40 @@ impl<'a> Checker<'a> { self.indexer.comment_ranges() } - /// Push a new [`Diagnostic`] to the collection in the [`Checker`] - pub(crate) fn report_diagnostic(&self, diagnostic: Diagnostic) { - let mut diagnostics = self.diagnostics.borrow_mut(); - diagnostics.push(diagnostic); + /// Return a [`DiagnosticGuard`] for reporting a diagnostic. + /// + /// The guard derefs to a [`Diagnostic`], so it can be used to further modify the diagnostic + /// before it is added to the collection in the checker on `Drop`. + pub(crate) fn report_diagnostic<'chk, T: Violation>( + &'chk self, + kind: T, + range: TextRange, + ) -> DiagnosticGuard<'chk, 'a> { + DiagnosticGuard { + checker: self, + diagnostic: Some(Diagnostic::new(kind, range)), + } + } + + /// Return a [`DiagnosticGuard`] for reporting a diagnostic if the corresponding rule is + /// enabled. + /// + /// Prefer [`Checker::report_diagnostic`] in general because the conversion from a `Diagnostic` + /// to a `Rule` is somewhat expensive. + pub(crate) fn report_diagnostic_if_enabled<'chk, T: Violation>( + &'chk self, + kind: T, + range: TextRange, + ) -> Option> { + let diagnostic = Diagnostic::new(kind, range); + if self.enabled(diagnostic.rule()) { + Some(DiagnosticGuard { + checker: self, + diagnostic: Some(diagnostic), + }) + } else { + None + } } /// Adds a [`TextRange`] to the set of ranges of variable names @@ -508,9 +538,9 @@ impl<'a> Checker<'a> { } /// Push `diagnostic` if the checker is not in a `@no_type_check` context. - pub(crate) fn report_type_diagnostic(&self, diagnostic: Diagnostic) { + pub(crate) fn report_type_diagnostic(&self, kind: T, range: TextRange) { if !self.semantic.in_no_type_check() { - self.report_diagnostic(diagnostic); + self.report_diagnostic(kind, range); } } @@ -595,7 +625,7 @@ impl SemanticSyntaxContext for Checker<'_> { match error.kind { SemanticSyntaxErrorKind::LateFutureImport => { if self.settings.rules.enabled(Rule::LateFutureImport) { - self.report_diagnostic(Diagnostic::new(LateFutureImport, error.range)); + self.report_diagnostic(LateFutureImport, error.range); } } SemanticSyntaxErrorKind::LoadBeforeGlobalDeclaration { name, start } => { @@ -604,31 +634,28 @@ impl SemanticSyntaxContext for Checker<'_> { .rules .enabled(Rule::LoadBeforeGlobalDeclaration) { - self.report_diagnostic(Diagnostic::new( + self.report_diagnostic( LoadBeforeGlobalDeclaration { name, row: self.compute_source_row(start), }, error.range, - )); + ); } } SemanticSyntaxErrorKind::YieldOutsideFunction(kind) => { if self.settings.rules.enabled(Rule::YieldOutsideFunction) { - self.report_diagnostic(Diagnostic::new( - YieldOutsideFunction::new(kind), - error.range, - )); + self.report_diagnostic(YieldOutsideFunction::new(kind), error.range); } } SemanticSyntaxErrorKind::ReturnOutsideFunction => { if self.settings.rules.enabled(Rule::ReturnOutsideFunction) { - self.report_diagnostic(Diagnostic::new(ReturnOutsideFunction, error.range)); + self.report_diagnostic(ReturnOutsideFunction, error.range); } } SemanticSyntaxErrorKind::AwaitOutsideAsyncFunction(_) => { if self.settings.rules.enabled(Rule::AwaitOutsideAsync) { - self.report_diagnostic(Diagnostic::new(AwaitOutsideAsync, error.range)); + self.report_diagnostic(AwaitOutsideAsync, error.range); } } SemanticSyntaxErrorKind::ReboundComprehensionVariable @@ -2717,12 +2744,12 @@ impl<'a> Checker<'a> { self.semantic.restore(snapshot); if self.enabled(Rule::ForwardAnnotationSyntaxError) { - self.report_type_diagnostic(Diagnostic::new( + self.report_type_diagnostic( pyflakes::rules::ForwardAnnotationSyntaxError { parse_error: parse_error.error.to_string(), }, string_expr.range(), - )); + ); } } } @@ -3020,3 +3047,59 @@ pub(crate) fn check_ast( (diagnostics.into_inner(), semantic_errors.into_inner()) } + +/// An abstraction for mutating a diagnostic. +/// +/// Callers can build this guard by starting with `Checker::report_diagnostic`. +/// +/// The primary function of this guard is to add the underlying diagnostic to the `Checker`'s list +/// of diagnostics on `Drop`, while dereferencing to the underlying diagnostic for mutations like +/// adding fixes or parent ranges. +pub(crate) struct DiagnosticGuard<'a, 'b> { + /// The parent checker that will receive the diagnostic on `Drop`. + checker: &'a Checker<'b>, + /// The diagnostic that we want to report. + /// + /// This is always `Some` until the `Drop` (or `defuse`) call. + diagnostic: Option, +} + +impl DiagnosticGuard<'_, '_> { + /// Consume the underlying `Diagnostic` without emitting it. + /// + /// In general you should avoid constructing diagnostics that may not be emitted, but this + /// method can be used where this is unavoidable. + pub(crate) fn defuse(mut self) { + self.diagnostic = None; + } +} + +impl std::ops::Deref for DiagnosticGuard<'_, '_> { + type Target = Diagnostic; + + fn deref(&self) -> &Diagnostic { + // OK because `self.diagnostic` is only `None` within `Drop`. + self.diagnostic.as_ref().unwrap() + } +} + +/// Return a mutable borrow of the diagnostic in this guard. +impl std::ops::DerefMut for DiagnosticGuard<'_, '_> { + fn deref_mut(&mut self) -> &mut Diagnostic { + // OK because `self.diagnostic` is only `None` within `Drop`. + self.diagnostic.as_mut().unwrap() + } +} + +impl Drop for DiagnosticGuard<'_, '_> { + fn drop(&mut self) { + if std::thread::panicking() { + // Don't submit diagnostics when panicking because they might be incomplete. + return; + } + + if let Some(diagnostic) = self.diagnostic.take() { + self.checker.diagnostics.borrow_mut().push(diagnostic); + } + } +} diff --git a/crates/ruff_linter/src/rules/airflow/rules/dag_schedule_argument.rs b/crates/ruff_linter/src/rules/airflow/rules/dag_schedule_argument.rs index 5263ed963b..3413544ded 100644 --- a/crates/ruff_linter/src/rules/airflow/rules/dag_schedule_argument.rs +++ b/crates/ruff_linter/src/rules/airflow/rules/dag_schedule_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_ast::{self as ast}; @@ -86,6 +86,5 @@ pub(crate) fn dag_no_schedule_argument(checker: &Checker, expr: &Expr) { } // Produce a diagnostic when the `schedule` keyword argument is not found. - let diagnostic = Diagnostic::new(AirflowDagNoScheduleArgument, expr.range()); - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(AirflowDagNoScheduleArgument, expr.range()); } diff --git a/crates/ruff_linter/src/rules/airflow/rules/moved_to_provider_in_3.rs b/crates/ruff_linter/src/rules/airflow/rules/moved_to_provider_in_3.rs index 1a9c7433d6..8184167431 100644 --- a/crates/ruff_linter/src/rules/airflow/rules/moved_to_provider_in_3.rs +++ b/crates/ruff_linter/src/rules/airflow/rules/moved_to_provider_in_3.rs @@ -1,7 +1,8 @@ use crate::importer::ImportRequest; use crate::rules::airflow::helpers::{ProviderReplacement, is_guarded_by_try_except}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; +use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{Expr, ExprAttribute}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -28,12 +29,12 @@ use crate::checkers::ast::Checker; /// from airflow.providers.fab.auth_manager.fab_auth_manage import FabAuthManager /// ``` #[derive(ViolationMetadata)] -pub(crate) struct Airflow3MovedToProvider { - deprecated: String, +pub(crate) struct Airflow3MovedToProvider<'a> { + deprecated: QualifiedName<'a>, replacement: ProviderReplacement, } -impl Violation for Airflow3MovedToProvider { +impl Violation for Airflow3MovedToProvider<'_> { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] @@ -1197,34 +1198,42 @@ fn check_names_moved_to_provider(checker: &Checker, expr: &Expr, ranged: TextRan _ => return, }; - let mut diagnostic = Diagnostic::new( - Airflow3MovedToProvider { - deprecated: qualified_name.to_string(), - replacement: replacement.clone(), - }, - ranged.range(), - ); - - let semantic = checker.semantic(); - if let Some((module, name)) = match &replacement { - ProviderReplacement::AutoImport { module, name, .. } => Some((module, *name)), + let (module, name) = match &replacement { + ProviderReplacement::AutoImport { module, name, .. } => (module, *name), ProviderReplacement::SourceModuleMovedToProvider { module, name, .. } => { - Some((module, name.as_str())) + (module, name.as_str()) } - ProviderReplacement::None => None, - } { - if is_guarded_by_try_except(expr, module, name, semantic) { + ProviderReplacement::None => { + checker.report_diagnostic( + Airflow3MovedToProvider { + deprecated: qualified_name, + replacement, + }, + ranged, + ); return; } - diagnostic.try_set_fix(|| { + }; + + if is_guarded_by_try_except(expr, module, name, checker.semantic()) { + return; + } + + checker + .report_diagnostic( + Airflow3MovedToProvider { + deprecated: qualified_name, + replacement: replacement.clone(), + }, + ranged, + ) + .try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import_from(module, name), expr.start(), checker.semantic(), )?; - let replacement_edit = Edit::range_replacement(binding, ranged.range()); + let replacement_edit = Edit::range_replacement(binding, ranged); Ok(Fix::safe_edits(import_edit, [replacement_edit])) }); - } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/airflow/rules/removal_in_3.rs b/crates/ruff_linter/src/rules/airflow/rules/removal_in_3.rs index 7a77228221..3c551f4a1d 100644 --- a/crates/ruff_linter/src/rules/airflow/rules/removal_in_3.rs +++ b/crates/ruff_linter/src/rules/airflow/rules/removal_in_3.rs @@ -3,7 +3,7 @@ use crate::importer::ImportRequest; use crate::rules::airflow::helpers::{ Replacement, is_airflow_builtin_or_provider, is_guarded_by_try_except, }; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::{ @@ -166,13 +166,13 @@ fn check_function_parameters(checker: &Checker, function_def: &StmtFunctionDef) for param in function_def.parameters.iter_non_variadic_params() { let param_name = param.name(); if REMOVED_CONTEXT_KEYS.contains(¶m_name.as_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( Airflow3Removal { deprecated: param_name.to_string(), replacement: Replacement::None, }, param_name.range(), - )); + ); } } } @@ -200,7 +200,7 @@ fn check_call_arguments(checker: &Checker, qualified_name: &QualifiedName, argum segments => { if is_airflow_auth_manager(segments) { if !arguments.is_empty() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( Airflow3Removal { deprecated: String::from("appbuilder"), replacement: Replacement::Message( @@ -208,7 +208,7 @@ fn check_call_arguments(checker: &Checker, qualified_name: &QualifiedName, argum ), }, arguments.range(), - )); + ); } } else if is_airflow_task_handler(segments) { diagnostic_for_argument(checker, arguments, "filename_template", None); @@ -305,7 +305,7 @@ fn check_class_attribute(checker: &Checker, attribute_expr: &ExprAttribute) { } else { None }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( Airflow3Removal { deprecated: attr.to_string(), replacement, @@ -315,7 +315,6 @@ fn check_class_attribute(checker: &Checker, attribute_expr: &ExprAttribute) { if let Some(fix) = fix { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } /// Checks whether an Airflow 3.0–removed context key is used in a function decorated with `@task`. @@ -382,13 +381,13 @@ fn check_context_key_usage_in_call(checker: &Checker, call_expr: &ExprCall) { continue; }; if value == removed_key { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( Airflow3Removal { deprecated: removed_key.to_string(), replacement: Replacement::None, }, *range, - )); + ); } } } @@ -423,13 +422,13 @@ fn check_context_key_usage_in_subscript(checker: &Checker, subscript: &ExprSubsc } if REMOVED_CONTEXT_KEYS.contains(&key.to_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( Airflow3Removal { deprecated: key.to_string(), replacement: Replacement::None, }, slice.range(), - )); + ); } } @@ -537,7 +536,7 @@ fn check_method(checker: &Checker, call_expr: &ExprCall) { None }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( Airflow3Removal { deprecated: attr.to_string(), replacement, @@ -547,7 +546,6 @@ fn check_method(checker: &Checker, call_expr: &ExprCall) { if let Some(fix) = fix { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } /// Check whether a removed Airflow name is used. @@ -966,26 +964,36 @@ fn check_name(checker: &Checker, expr: &Expr, range: TextRange) { _ => return, }; - let mut diagnostic = Diagnostic::new( - Airflow3Removal { - deprecated: qualified_name.to_string(), - replacement: replacement.clone(), - }, - range, - ); - let semantic = checker.semantic(); - if let Some((module, name)) = match &replacement { - Replacement::AutoImport { module, name } => Some((module, *name)), - Replacement::SourceModuleMoved { module, name } => Some((module, name.as_str())), - _ => None, - } { - if is_guarded_by_try_except(expr, module, name, semantic) { + let (module, name) = match &replacement { + Replacement::AutoImport { module, name } => (module, *name), + Replacement::SourceModuleMoved { module, name } => (module, name.as_str()), + _ => { + checker.report_diagnostic( + Airflow3Removal { + deprecated: qualified_name.to_string(), + replacement: replacement.clone(), + }, + range, + ); return; } + }; - let import_target = name.split('.').next().unwrap_or(name); + if is_guarded_by_try_except(expr, module, name, checker.semantic()) { + return; + } - diagnostic.try_set_fix(|| { + let import_target = name.split('.').next().unwrap_or(name); + + checker + .report_diagnostic( + Airflow3Removal { + deprecated: qualified_name.to_string(), + replacement: replacement.clone(), + }, + range, + ) + .try_set_fix(|| { let (import_edit, _) = checker.importer().get_or_import_symbol( &ImportRequest::import_from(module, import_target), expr.start(), @@ -994,9 +1002,6 @@ fn check_name(checker: &Checker, expr: &Expr, range: TextRange) { let replacement_edit = Edit::range_replacement(name.to_string(), range); Ok(Fix::safe_edits(import_edit, [replacement_edit])) }); - } - - checker.report_diagnostic(diagnostic); } /// Check whether a customized Airflow plugin contains removed extensions. @@ -1028,7 +1033,7 @@ fn check_airflow_plugin_extension( ) }) }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( Airflow3Removal { deprecated: name.to_string(), replacement: Replacement::Message( @@ -1036,7 +1041,7 @@ fn check_airflow_plugin_extension( ), }, expr.range(), - )); + ); } } } @@ -1052,7 +1057,11 @@ fn diagnostic_for_argument( let Some(keyword) = arguments.find_keyword(deprecated) else { return; }; - let mut diagnostic = Diagnostic::new( + let range = keyword + .arg + .as_ref() + .map_or_else(|| keyword.range(), Ranged::range); + let mut diagnostic = checker.report_diagnostic( Airflow3Removal { deprecated: deprecated.to_string(), replacement: match replacement { @@ -1060,20 +1069,15 @@ fn diagnostic_for_argument( None => Replacement::None, }, }, - keyword - .arg - .as_ref() - .map_or_else(|| keyword.range(), Ranged::range), + range, ); if let Some(replacement) = replacement { diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( replacement.to_string(), - diagnostic.range, + range, ))); } - - checker.report_diagnostic(diagnostic); } /// Check whether the symbol is coming from the `secrets` builtin or provider module which ends diff --git a/crates/ruff_linter/src/rules/airflow/rules/suggested_to_move_to_provider_in_3.rs b/crates/ruff_linter/src/rules/airflow/rules/suggested_to_move_to_provider_in_3.rs index b5db71486e..a6815fa5a9 100644 --- a/crates/ruff_linter/src/rules/airflow/rules/suggested_to_move_to_provider_in_3.rs +++ b/crates/ruff_linter/src/rules/airflow/rules/suggested_to_move_to_provider_in_3.rs @@ -1,8 +1,9 @@ use crate::importer::ImportRequest; use crate::rules::airflow::helpers::{ProviderReplacement, is_guarded_by_try_except}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; +use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{Expr, ExprAttribute}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -30,12 +31,12 @@ use crate::checkers::ast::Checker; /// from airflow.providers.standard.operators.python import PythonOperator /// ``` #[derive(ViolationMetadata)] -pub(crate) struct Airflow3SuggestedToMoveToProvider { - deprecated: String, +pub(crate) struct Airflow3SuggestedToMoveToProvider<'a> { + deprecated: QualifiedName<'a>, replacement: ProviderReplacement, } -impl Violation for Airflow3SuggestedToMoveToProvider { +impl Violation for Airflow3SuggestedToMoveToProvider<'_> { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { @@ -281,26 +282,36 @@ fn check_names_moved_to_provider(checker: &Checker, expr: &Expr, ranged: TextRan _ => return, }; - let mut diagnostic = Diagnostic::new( - Airflow3SuggestedToMoveToProvider { - deprecated: qualified_name.to_string(), - replacement: replacement.clone(), - }, - ranged.range(), - ); - - let semantic = checker.semantic(); - if let Some((module, name)) = match &replacement { - ProviderReplacement::AutoImport { module, name, .. } => Some((module, *name)), + let (module, name) = match &replacement { + ProviderReplacement::AutoImport { module, name, .. } => (module, *name), ProviderReplacement::SourceModuleMovedToProvider { module, name, .. } => { - Some((module, name.as_str())) + (module, name.as_str()) } - ProviderReplacement::None => None, - } { - if is_guarded_by_try_except(expr, module, name, semantic) { + ProviderReplacement::None => { + checker.report_diagnostic( + Airflow3SuggestedToMoveToProvider { + deprecated: qualified_name, + replacement: replacement.clone(), + }, + ranged.range(), + ); return; } - diagnostic.try_set_fix(|| { + }; + + if is_guarded_by_try_except(expr, module, name, checker.semantic()) { + return; + } + + checker + .report_diagnostic( + Airflow3SuggestedToMoveToProvider { + deprecated: qualified_name, + replacement: replacement.clone(), + }, + ranged.range(), + ) + .try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import_from(module, name), expr.start(), @@ -309,7 +320,4 @@ fn check_names_moved_to_provider(checker: &Checker, expr: &Expr, ranged: TextRan let replacement_edit = Edit::range_replacement(binding, ranged.range()); Ok(Fix::safe_edits(import_edit, [replacement_edit])) }); - } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/airflow/rules/suggested_to_update_3_0.rs b/crates/ruff_linter/src/rules/airflow/rules/suggested_to_update_3_0.rs index 0bc310f3fe..f3286a8350 100644 --- a/crates/ruff_linter/src/rules/airflow/rules/suggested_to_update_3_0.rs +++ b/crates/ruff_linter/src/rules/airflow/rules/suggested_to_update_3_0.rs @@ -3,7 +3,7 @@ use crate::importer::ImportRequest; use crate::rules::airflow::helpers::{ Replacement, is_airflow_builtin_or_provider, is_guarded_by_try_except, }; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Arguments, Expr, ExprAttribute, ExprCall, ExprName, name::QualifiedName}; use ruff_python_semantic::Modules; @@ -120,7 +120,11 @@ fn diagnostic_for_argument( let Some(keyword) = arguments.find_keyword(deprecated) else { return; }; - let mut diagnostic = Diagnostic::new( + let range = keyword + .arg + .as_ref() + .map_or_else(|| keyword.range(), Ranged::range); + let mut diagnostic = checker.report_diagnostic( Airflow3SuggestedUpdate { deprecated: deprecated.to_string(), replacement: match replacement { @@ -128,20 +132,15 @@ fn diagnostic_for_argument( None => Replacement::None, }, }, - keyword - .arg - .as_ref() - .map_or_else(|| keyword.range(), Ranged::range), + range, ); if let Some(replacement) = replacement { diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( replacement.to_string(), - diagnostic.range, + range, ))); } - - checker.report_diagnostic(diagnostic); } /// Check whether a removed Airflow argument is passed. /// @@ -284,24 +283,34 @@ fn check_name(checker: &Checker, expr: &Expr, range: TextRange) { _ => return, }; - let mut diagnostic = Diagnostic::new( - Airflow3SuggestedUpdate { - deprecated: qualified_name.to_string(), - replacement: replacement.clone(), - }, - range, - ); - - let semantic = checker.semantic(); - if let Some((module, name)) = match &replacement { - Replacement::AutoImport { module, name } => Some((module, *name)), - Replacement::SourceModuleMoved { module, name } => Some((module, name.as_str())), - _ => None, - } { - if is_guarded_by_try_except(expr, module, name, semantic) { + let (module, name) = match &replacement { + Replacement::AutoImport { module, name } => (module, *name), + Replacement::SourceModuleMoved { module, name } => (module, name.as_str()), + _ => { + checker.report_diagnostic( + Airflow3SuggestedUpdate { + deprecated: qualified_name.to_string(), + replacement: replacement.clone(), + }, + range, + ); return; } - diagnostic.try_set_fix(|| { + }; + + if is_guarded_by_try_except(expr, module, name, checker.semantic()) { + return; + } + + checker + .report_diagnostic( + Airflow3SuggestedUpdate { + deprecated: qualified_name.to_string(), + replacement: replacement.clone(), + }, + range, + ) + .try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import_from(module, name), expr.start(), @@ -310,7 +319,4 @@ fn check_name(checker: &Checker, expr: &Expr, range: TextRange) { let replacement_edit = Edit::range_replacement(binding, range); Ok(Fix::safe_edits(import_edit, [replacement_edit])) }); - } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/airflow/rules/task_variable_name.rs b/crates/ruff_linter/src/rules/airflow/rules/task_variable_name.rs index 72e62d15bc..5470014187 100644 --- a/crates/ruff_linter/src/rules/airflow/rules/task_variable_name.rs +++ b/crates/ruff_linter/src/rules/airflow/rules/task_variable_name.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::Expr; @@ -110,11 +110,10 @@ pub(crate) fn variable_name_task_id(checker: &Checker, targets: &[Expr], value: return; } - let diagnostic = Diagnostic::new( + checker.report_diagnostic( AirflowVariableNameTaskIdMismatch { task_id: task_id.to_string(), }, target.range(), ); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/fastapi/rules/fastapi_non_annotated_dependency.rs b/crates/ruff_linter/src/rules/fastapi/rules/fastapi_non_annotated_dependency.rs index 2ef280bd2e..b2221cfbd5 100644 --- a/crates/ruff_linter/src/rules/fastapi/rules/fastapi_non_annotated_dependency.rs +++ b/crates/ruff_linter/src/rules/fastapi/rules/fastapi_non_annotated_dependency.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::helpers::map_callable; @@ -237,7 +237,7 @@ fn create_diagnostic( return seen_default; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( FastApiNonAnnotatedDependency { py_version: checker.target_version(), }, @@ -308,7 +308,5 @@ fn create_diagnostic( } diagnostic.try_set_optional_fix(|| fix); - checker.report_diagnostic(diagnostic); - seen_default } diff --git a/crates/ruff_linter/src/rules/fastapi/rules/fastapi_redundant_response_model.rs b/crates/ruff_linter/src/rules/fastapi/rules/fastapi_redundant_response_model.rs index ab38db93ae..96a663eaea 100644 --- a/crates/ruff_linter/src/rules/fastapi/rules/fastapi_redundant_response_model.rs +++ b/crates/ruff_linter/src/rules/fastapi/rules/fastapi_redundant_response_model.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Decorator, Expr, ExprCall, Keyword, StmtFunctionDef}; use ruff_python_semantic::{Modules, SemanticModel}; @@ -85,7 +85,7 @@ pub(crate) fn fastapi_redundant_response_model(checker: &Checker, function_def: continue; }; let mut diagnostic = - Diagnostic::new(FastApiRedundantResponseModel, response_model_arg.range()); + checker.report_diagnostic(FastApiRedundantResponseModel, response_model_arg.range()); diagnostic.try_set_fix(|| { remove_argument( response_model_arg, @@ -95,7 +95,6 @@ pub(crate) fn fastapi_redundant_response_model(checker: &Checker, function_def: ) .map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/fastapi/rules/fastapi_unused_path_parameter.rs b/crates/ruff_linter/src/rules/fastapi/rules/fastapi_unused_path_parameter.rs index 286617ccdf..42220b3dc8 100644 --- a/crates/ruff_linter/src/rules/fastapi/rules/fastapi_unused_path_parameter.rs +++ b/crates/ruff_linter/src/rules/fastapi/rules/fastapi_unused_path_parameter.rs @@ -3,7 +3,7 @@ use std::ops::Range; use std::str::CharIndices; use ruff_diagnostics::Fix; -use ruff_diagnostics::{Diagnostic, FixAvailability, Violation}; +use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::{Arguments, Expr, ExprCall, ExprSubscript, Parameter, ParameterWithDefault}; @@ -186,7 +186,7 @@ pub(crate) fn fastapi_unused_path_parameter( .iter() .any(|param| param.name() == path_param); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( FastApiUnusedPathParameter { arg_name: path_param.to_string(), function_name: function_def.name.to_string(), @@ -204,7 +204,6 @@ pub(crate) fn fastapi_unused_path_parameter( checker.locator().contents(), ))); } - checker.report_diagnostic(diagnostic); } } 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 359be0dbcb..a83fe0c288 100644 --- a/crates/ruff_linter/src/rules/flake8_2020/rules/compare.rs +++ b/crates/ruff_linter/src/rules/flake8_2020/rules/compare.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr}; use ruff_text_size::Ranged; @@ -254,12 +254,12 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ) = (ops, comparators) { if *n == 3 && checker.enabled(Rule::SysVersionInfo0Eq3) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SysVersionInfo0Eq3 { eq: matches!(*operator, CmpOp::Eq), }, left.range(), - )); + ); } } } else if *i == 1 { @@ -274,10 +274,7 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ) = (ops, comparators) { if checker.enabled(Rule::SysVersionInfo1CmpInt) { - checker.report_diagnostic(Diagnostic::new( - SysVersionInfo1CmpInt, - left.range(), - )); + checker.report_diagnostic(SysVersionInfo1CmpInt, left.range()); } } } @@ -298,10 +295,7 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ) = (ops, comparators) { if checker.enabled(Rule::SysVersionInfoMinorCmpInt) { - checker.report_diagnostic(Diagnostic::new( - SysVersionInfoMinorCmpInt, - left.range(), - )); + checker.report_diagnostic(SysVersionInfoMinorCmpInt, left.range()); } } } @@ -317,10 +311,10 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators { if value.len() == 1 { if checker.enabled(Rule::SysVersionCmpStr10) { - checker.report_diagnostic(Diagnostic::new(SysVersionCmpStr10, left.range())); + checker.report_diagnostic(SysVersionCmpStr10, left.range()); } } else if checker.enabled(Rule::SysVersionCmpStr3) { - checker.report_diagnostic(Diagnostic::new(SysVersionCmpStr3, left.range())); + checker.report_diagnostic(SysVersionCmpStr3, left.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_2020/rules/name_or_attribute.rs b/crates/ruff_linter/src/rules/flake8_2020/rules/name_or_attribute.rs index bcf610d355..fdf240834a 100644 --- a/crates/ruff_linter/src/rules/flake8_2020/rules/name_or_attribute.rs +++ b/crates/ruff_linter/src/rules/flake8_2020/rules/name_or_attribute.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::Modules; @@ -56,6 +56,6 @@ pub(crate) fn name_or_attribute(checker: &Checker, expr: &Expr) { .resolve_qualified_name(expr) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["six", "PY3"])) { - checker.report_diagnostic(Diagnostic::new(SixPY3, expr.range())); + checker.report_diagnostic(SixPY3, expr.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 0ed2feb248..e9f90c85d4 100644 --- a/crates/ruff_linter/src/rules/flake8_2020/rules/subscript.rs +++ b/crates/ruff_linter/src/rules/flake8_2020/rules/subscript.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -183,9 +183,9 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, slice: &Expr) { }) = upper.as_ref() { if *i == 1 && checker.enabled(Rule::SysVersionSlice1) { - checker.report_diagnostic(Diagnostic::new(SysVersionSlice1, value.range())); + checker.report_diagnostic(SysVersionSlice1, value.range()); } else if *i == 3 && checker.enabled(Rule::SysVersionSlice3) { - checker.report_diagnostic(Diagnostic::new(SysVersionSlice3, value.range())); + checker.report_diagnostic(SysVersionSlice3, value.range()); } } } @@ -195,9 +195,9 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, slice: &Expr) { .. }) => { if *i == 2 && checker.enabled(Rule::SysVersion2) { - checker.report_diagnostic(Diagnostic::new(SysVersion2, value.range())); + checker.report_diagnostic(SysVersion2, value.range()); } else if *i == 0 && checker.enabled(Rule::SysVersion0) { - checker.report_diagnostic(Diagnostic::new(SysVersion0, value.range())); + 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 1f75ec28a1..333845c7e2 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/rules/definition.rs +++ b/crates/ruff_linter/src/rules/flake8_annotations/rules/definition.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -9,7 +9,7 @@ use ruff_python_semantic::analyze::visibility; use ruff_python_stdlib::typing::simple_magic_return_type; use ruff_text_size::Ranged; -use crate::checkers::ast::Checker; +use crate::checkers::ast::{Checker, DiagnosticGuard}; use crate::registry::Rule; use crate::rules::flake8_annotations::helpers::auto_return_type; use crate::rules::ruff::typing::type_hint_resolves_to_any; @@ -529,11 +529,11 @@ fn is_none_returning(body: &[Stmt]) -> bool { } /// ANN401 -fn check_dynamically_typed( - checker: &Checker, +fn check_dynamically_typed<'a, 'b, F>( + checker: &'a Checker<'b>, annotation: &Expr, func: F, - diagnostics: &mut Vec, + diagnostics: &mut Vec>, ) where F: FnOnce() -> String, { @@ -545,18 +545,14 @@ fn check_dynamically_typed( checker, checker.target_version(), ) { - diagnostics.push(Diagnostic::new( - AnyType { name: func() }, - annotation.range(), - )); + diagnostics + .push(checker.report_diagnostic(AnyType { name: func() }, annotation.range())); } } } else { if type_hint_resolves_to_any(annotation, checker, checker.target_version()) { - diagnostics.push(Diagnostic::new( - AnyType { name: func() }, - annotation.range(), - )); + diagnostics + .push(checker.report_diagnostic(AnyType { name: func() }, annotation.range())); } } } @@ -655,7 +651,7 @@ pub(crate) fn definition( .is_match(parameter.name())) { if checker.enabled(Rule::MissingTypeFunctionArgument) { - diagnostics.push(Diagnostic::new( + diagnostics.push(checker.report_diagnostic( MissingTypeFunctionArgument { name: parameter.name().to_string(), }, @@ -681,7 +677,7 @@ pub(crate) fn definition( && checker.settings.dummy_variable_rgx.is_match(&arg.name)) { if checker.enabled(Rule::MissingTypeArgs) { - diagnostics.push(Diagnostic::new( + diagnostics.push(checker.report_diagnostic( MissingTypeArgs { name: arg.name.to_string(), }, @@ -712,7 +708,7 @@ pub(crate) fn definition( && checker.settings.dummy_variable_rgx.is_match(&arg.name)) { if checker.enabled(Rule::MissingTypeKwargs) { - diagnostics.push(Diagnostic::new( + diagnostics.push(checker.report_diagnostic( MissingTypeKwargs { name: arg.name.to_string(), }, @@ -745,7 +741,7 @@ pub(crate) fn definition( }) .map(|(return_type, edits)| (checker.generator().expr(&return_type), edits)) }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingReturnTypeClassMethod { name: name.to_string(), annotation: return_type.clone().map(|(return_type, ..)| return_type), @@ -771,7 +767,7 @@ pub(crate) fn definition( }) .map(|(return_type, edits)| (checker.generator().expr(&return_type), edits)) }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingReturnTypeStaticMethod { name: name.to_string(), annotation: return_type.clone().map(|(return_type, ..)| return_type), @@ -791,7 +787,7 @@ pub(crate) fn definition( // least one argument is typed. if checker.enabled(Rule::MissingReturnTypeSpecialMethod) { if !(checker.settings.flake8_annotations.mypy_init_return && has_any_typed_arg) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingReturnTypeSpecialMethod { name: name.to_string(), annotation: Some("None".to_string()), @@ -808,7 +804,7 @@ pub(crate) fn definition( } else if is_method && visibility::is_magic(name) { if checker.enabled(Rule::MissingReturnTypeSpecialMethod) { let return_type = simple_magic_return_type(name); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingReturnTypeSpecialMethod { name: name.to_string(), annotation: return_type.map(ToString::to_string), @@ -839,7 +835,7 @@ pub(crate) fn definition( (checker.generator().expr(&return_type), edits) }) }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingReturnTypeUndocumentedPublicFunction { name: name.to_string(), annotation: return_type @@ -874,7 +870,7 @@ pub(crate) fn definition( (checker.generator().expr(&return_type), edits) }) }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingReturnTypePrivateFunction { name: name.to_string(), annotation: return_type @@ -901,7 +897,7 @@ pub(crate) fn definition( // If settings say so, don't report any of the // diagnostics gathered here if there were no type annotations at all. - if !checker.settings.flake8_annotations.ignore_fully_untyped + let diagnostics_enabled = !checker.settings.flake8_annotations.ignore_fully_untyped || has_any_typed_arg || has_typed_return || (is_method @@ -910,10 +906,11 @@ pub(crate) fn definition( .posonlyargs .first() .or_else(|| parameters.args.first()) - .is_some_and(|first_param| first_param.annotation().is_some())) - { + .is_some_and(|first_param| first_param.annotation().is_some())); + + if !diagnostics_enabled { for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); + diagnostic.defuse(); } } } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/async_busy_wait.rs b/crates/ruff_linter/src/rules/flake8_async/rules/async_busy_wait.rs index 60ab11c874..9d5980c548 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/async_busy_wait.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/async_busy_wait.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::Ranged; @@ -74,11 +74,11 @@ pub(crate) fn async_busy_wait(checker: &Checker, while_stmt: &ast::StmtWhile) { qualified_name.segments(), ["trio" | "anyio", "sleep" | "sleep_until"] | ["asyncio", "sleep"] ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( AsyncBusyWait { module: AsyncModule::try_from(&qualified_name).unwrap(), }, while_stmt.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/async_function_with_timeout.rs b/crates/ruff_linter/src/rules/flake8_async/rules/async_function_with_timeout.rs index 009aa42c77..3703ded95a 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/async_function_with_timeout.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/async_function_with_timeout.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; @@ -112,8 +112,5 @@ pub(crate) fn async_function_with_timeout(checker: &Checker, function_def: &ast: return; } - checker.report_diagnostic(Diagnostic::new( - AsyncFunctionWithTimeout { module }, - timeout.range(), - )); + checker.report_diagnostic(AsyncFunctionWithTimeout { module }, timeout.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/async_zero_sleep.rs b/crates/ruff_linter/src/rules/flake8_async/rules/async_zero_sleep.rs index 87a6ef841a..890cadd0e4 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/async_zero_sleep.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/async_zero_sleep.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall, Int, Number}; use ruff_python_semantic::Modules; @@ -109,7 +109,7 @@ pub(crate) fn async_zero_sleep(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new(AsyncZeroSleep { module }, call.range()); + let mut diagnostic = checker.report_diagnostic(AsyncZeroSleep { module }, call.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import_from(&module.to_string(), "lowlevel"), @@ -121,6 +121,5 @@ pub(crate) fn async_zero_sleep(checker: &Checker, call: &ExprCall) { let arg_edit = Edit::range_replacement("()".to_string(), call.arguments.range()); Ok(Fix::safe_edits(import_edit, [reference_edit, arg_edit])) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call.rs b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call.rs index 747913352c..ba99ea539d 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call.rs @@ -1,6 +1,6 @@ use ruff_python_ast::ExprCall; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_text_size::Ranged; @@ -70,10 +70,7 @@ pub(crate) fn blocking_http_call(checker: &Checker, call: &ExprCall) { .as_ref() .is_some_and(is_blocking_http_call) { - checker.report_diagnostic(Diagnostic::new( - BlockingHttpCallInAsyncFunction, - call.func.range(), - )); + checker.report_diagnostic(BlockingHttpCallInAsyncFunction, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_open_call.rs b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_open_call.rs index 621f87cec5..99c9d23bb6 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_open_call.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_open_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::{SemanticModel, analyze}; @@ -52,10 +52,7 @@ pub(crate) fn blocking_open_call(checker: &Checker, call: &ast::ExprCall) { if is_open_call(&call.func, checker.semantic()) || is_open_call_from_pathlib(call.func.as_ref(), checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( - BlockingOpenCallInAsyncFunction, - call.func.range(), - )); + checker.report_diagnostic(BlockingOpenCallInAsyncFunction, call.func.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_process_invocation.rs b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_process_invocation.rs index e9d6cb7ff2..fffd7d6913 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_process_invocation.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_process_invocation.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; @@ -6,7 +6,6 @@ use ruff_python_semantic::analyze::typing::find_assigned_value; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; -use crate::registry::AsRule; /// ## What it does /// Checks that async functions do not create subprocesses with blocking methods. @@ -125,17 +124,17 @@ pub(crate) fn blocking_process_invocation(checker: &Checker, call: &ast::ExprCal }; let range = call.func.range(); - let diagnostic = match qualified_name.segments() { + match qualified_name.segments() { ["subprocess", "Popen"] | ["os", "popen"] => { - Diagnostic::new(CreateSubprocessInAsyncFunction, range) + checker.report_diagnostic_if_enabled(CreateSubprocessInAsyncFunction, range) } ["os", "system" | "posix_spawn" | "posix_spawnp"] | [ "subprocess", "run" | "call" | "check_call" | "check_output" | "getoutput" | "getstatusoutput", - ] => Diagnostic::new(RunProcessInAsyncFunction, range), + ] => checker.report_diagnostic_if_enabled(RunProcessInAsyncFunction, range), ["os", "wait" | "wait3" | "wait4" | "waitid" | "waitpid"] => { - Diagnostic::new(WaitForProcessInAsyncFunction, range) + checker.report_diagnostic_if_enabled(WaitForProcessInAsyncFunction, range) } [ "os", @@ -143,17 +142,13 @@ pub(crate) fn blocking_process_invocation(checker: &Checker, call: &ast::ExprCal | "spawnvpe", ] => { if is_p_wait(call, checker.semantic()) { - Diagnostic::new(RunProcessInAsyncFunction, range) + checker.report_diagnostic_if_enabled(RunProcessInAsyncFunction, range) } else { - Diagnostic::new(CreateSubprocessInAsyncFunction, range) + checker.report_diagnostic_if_enabled(CreateSubprocessInAsyncFunction, range) } } _ => return, }; - - if checker.enabled(diagnostic.rule()) { - checker.report_diagnostic(diagnostic); - } } fn is_p_wait(call: &ast::ExprCall, semantic: &SemanticModel) -> bool { diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_sleep.rs b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_sleep.rs index c625318796..693ec58d3c 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/blocking_sleep.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/blocking_sleep.rs @@ -1,6 +1,6 @@ use ruff_python_ast::ExprCall; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_text_size::Ranged; @@ -51,10 +51,7 @@ pub(crate) fn blocking_sleep(checker: &Checker, call: &ExprCall) { .as_ref() .is_some_and(is_blocking_sleep) { - checker.report_diagnostic(Diagnostic::new( - BlockingSleepInAsyncFunction, - call.func.range(), - )); + checker.report_diagnostic(BlockingSleepInAsyncFunction, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/cancel_scope_no_checkpoint.rs b/crates/ruff_linter/src/rules/flake8_async/rules/cancel_scope_no_checkpoint.rs index 9ebf0ae2e2..80c65c2265 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/cancel_scope_no_checkpoint.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/cancel_scope_no_checkpoint.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::{AwaitVisitor, any_over_body}; use ruff_python_ast::visitor::Visitor; @@ -100,8 +100,5 @@ pub(crate) fn cancel_scope_no_checkpoint( return; } - checker.report_diagnostic(Diagnostic::new( - CancelScopeNoCheckpoint { method_name }, - with_stmt.range, - )); + checker.report_diagnostic(CancelScopeNoCheckpoint { method_name }, with_stmt.range); } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/long_sleep_not_forever.rs b/crates/ruff_linter/src/rules/flake8_async/rules/long_sleep_not_forever.rs index 3e31062672..e91ec3615e 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/long_sleep_not_forever.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/long_sleep_not_forever.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprCall, ExprNumberLiteral, Number}; use ruff_python_semantic::Modules; @@ -137,7 +137,7 @@ pub(crate) fn long_sleep_not_forever(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new(LongSleepNotForever { module }, call.range()); + let mut diagnostic = checker.report_diagnostic(LongSleepNotForever { module }, call.range()); let replacement_function = "sleep_forever"; diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( @@ -149,5 +149,4 @@ pub(crate) fn long_sleep_not_forever(checker: &Checker, call: &ExprCall) { let arg_edit = Edit::range_replacement("()".to_string(), call.arguments.range()); Ok(Fix::unsafe_edits(import_edit, [reference_edit, arg_edit])) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_async/rules/sync_call.rs b/crates/ruff_linter/src/rules/flake8_async/rules/sync_call.rs index fc93b806bc..ee0c301a4b 100644 --- a/crates/ruff_linter/src/rules/flake8_async/rules/sync_call.rs +++ b/crates/ruff_linter/src/rules/flake8_async/rules/sync_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprCall}; use ruff_python_semantic::Modules; @@ -80,7 +80,7 @@ pub(crate) fn sync_call(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new(TrioSyncCall { method_name }, call.range); + let mut diagnostic = checker.report_diagnostic(TrioSyncCall { method_name }, call.range); if checker.semantic().in_async_context() { diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( pad( @@ -91,5 +91,4 @@ pub(crate) fn sync_call(checker: &Checker, call: &ExprCall) { call.func.start(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/assert_used.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/assert_used.rs index 2001ef7727..6ea3b04fa9 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/assert_used.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/assert_used.rs @@ -1,10 +1,12 @@ use ruff_python_ast::Stmt; use ruff_text_size::{TextLen, TextRange}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for uses of the `assert` keyword. /// @@ -41,6 +43,6 @@ impl Violation for Assert { } /// S101 -pub(crate) fn assert_used(stmt: &Stmt) -> Diagnostic { - Diagnostic::new(Assert, TextRange::at(stmt.start(), "assert".text_len())) +pub(crate) fn assert_used(checker: &Checker, stmt: &Stmt) { + checker.report_diagnostic(Assert, TextRange::at(stmt.start(), "assert".text_len())); } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/bad_file_permissions.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/bad_file_permissions.rs index 0033504e2d..c99774341f 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/bad_file_permissions.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/bad_file_permissions.rs @@ -1,6 +1,6 @@ use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Expr, Operator}; @@ -78,22 +78,22 @@ pub(crate) fn bad_file_permissions(checker: &Checker, call: &ast::ExprCall) { // The mask is a valid integer value -- check for overly permissive permissions. Ok(Some(mask)) => { if (mask & WRITE_WORLD > 0) || (mask & EXECUTE_GROUP > 0) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadFilePermissions { reason: Reason::Permissive(mask), }, mode_arg.range(), - )); + ); } } // The mask is an invalid integer value (i.e., it's out of range). Err(_) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadFilePermissions { reason: Reason::Invalid, }, mode_arg.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/django_extra.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/django_extra.rs index 41686ce957..9051f9db47 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/django_extra.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/django_extra.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprAttribute}; use ruff_text_size::Ranged; @@ -54,7 +54,7 @@ pub(crate) fn django_extra(checker: &Checker, call: &ast::ExprCall) { } if is_call_insecure(call) { - checker.report_diagnostic(Diagnostic::new(DjangoExtra, call.arguments.range())); + checker.report_diagnostic(DjangoExtra, call.arguments.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/django_raw_sql.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/django_raw_sql.rs index c4ddc9decd..7876dca2c9 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/django_raw_sql.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/django_raw_sql.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; @@ -55,7 +55,7 @@ pub(crate) fn django_raw_sql(checker: &Checker, call: &ast::ExprCall) { .find_argument_value("sql", 0) .is_some_and(Expr::is_string_literal_expr) { - checker.report_diagnostic(Diagnostic::new(DjangoRawSql, call.func.range())); + checker.report_diagnostic(DjangoRawSql, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/exec_used.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/exec_used.rs index ee23e38be2..a495231702 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/exec_used.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/exec_used.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -34,6 +34,6 @@ impl Violation for ExecBuiltin { /// S102 pub(crate) fn exec_used(checker: &Checker, func: &Expr) { if checker.semantic().match_builtin_expr(func, "exec") { - checker.report_diagnostic(Diagnostic::new(ExecBuiltin, func.range())); + checker.report_diagnostic(ExecBuiltin, func.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/flask_debug_true.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/flask_debug_true.rs index 01a3f63ae2..6ab094b677 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/flask_debug_true.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/flask_debug_true.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; @@ -67,6 +67,6 @@ pub(crate) fn flask_debug_true(checker: &Checker, call: &ExprCall) { if typing::resolve_assignment(value, checker.semantic()) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["flask", "Flask"])) { - checker.report_diagnostic(Diagnostic::new(FlaskDebugTrue, debug_argument.range())); + checker.report_diagnostic(FlaskDebugTrue, debug_argument.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs index 2b8c743fea..6a44804748 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, StringLike}; use ruff_text_size::Ranged; @@ -41,8 +41,7 @@ pub(crate) fn hardcoded_bind_all_interfaces(checker: &Checker, string: StringLik match string { StringLike::String(ast::ExprStringLiteral { value, .. }) => { if value == "0.0.0.0" { - checker - .report_diagnostic(Diagnostic::new(HardcodedBindAllInterfaces, string.range())); + checker.report_diagnostic(HardcodedBindAllInterfaces, string.range()); } } StringLike::FString(ast::ExprFString { value, .. }) => { @@ -50,19 +49,14 @@ pub(crate) fn hardcoded_bind_all_interfaces(checker: &Checker, string: StringLik match part { ast::FStringPart::Literal(literal) => { if &**literal == "0.0.0.0" { - checker.report_diagnostic(Diagnostic::new( - HardcodedBindAllInterfaces, - literal.range(), - )); + checker.report_diagnostic(HardcodedBindAllInterfaces, literal.range()); } } ast::FStringPart::FString(f_string) => { for literal in f_string.elements.literals() { if &**literal == "0.0.0.0" { - checker.report_diagnostic(Diagnostic::new( - HardcodedBindAllInterfaces, - literal.range(), - )); + checker + .report_diagnostic(HardcodedBindAllInterfaces, literal.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_default.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_default.rs index 08070b9222..9cc404fba8 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_default.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_default.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, Parameter, Parameters}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -54,18 +54,20 @@ impl Violation for HardcodedPasswordDefault { } } -fn check_password_kwarg(parameter: &Parameter, default: &Expr) -> Option { - string_literal(default).filter(|string| !string.is_empty())?; +fn check_password_kwarg(checker: &Checker, parameter: &Parameter, default: &Expr) { + if string_literal(default).is_none_or(str::is_empty) { + return; + } let kwarg_name = ¶meter.name; if !matches_password_name(kwarg_name) { - return None; + return; } - Some(Diagnostic::new( + checker.report_diagnostic( HardcodedPasswordDefault { name: kwarg_name.to_string(), }, default.range(), - )) + ); } /// S107 @@ -74,8 +76,6 @@ pub(crate) fn hardcoded_password_default(checker: &Checker, parameters: &Paramet let Some(default) = parameter.default() else { continue; }; - if let Some(diagnostic) = check_password_kwarg(¶meter.parameter, default) { - checker.report_diagnostic(diagnostic); - } + check_password_kwarg(checker, ¶meter.parameter, default); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs index c242d36832..a6aacb3c5e 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Keyword; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -62,11 +62,11 @@ pub(crate) fn hardcoded_password_func_arg(checker: &Checker, keywords: &[Keyword if !matches_password_name(arg) { continue; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HardcodedPasswordFuncArg { name: arg.to_string(), }, keyword.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_string.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_string.rs index 6ea4ab32be..317dcad0c5 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_string.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_string.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -83,12 +83,12 @@ pub(crate) fn compare_to_hardcoded_password_string( let Some(name) = password_target(left) else { continue; }; - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HardcodedPasswordString { name: name.to_string(), }, comp.range(), - )); + ); } } @@ -100,12 +100,12 @@ pub(crate) fn assign_hardcoded_password_string(checker: &Checker, value: &Expr, { for target in targets { if let Some(name) = password_target(target) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HardcodedPasswordString { name: name.to_string(), }, value.range(), - )); + ); return; } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs index 70470fd977..8fa2cbf8dc 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs @@ -2,7 +2,7 @@ use std::sync::LazyLock; use regex::Regex; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::str::raw_contents; use ruff_python_ast::{self as ast, Expr, Operator}; @@ -113,7 +113,7 @@ pub(crate) fn hardcoded_sql_expression(checker: &Checker, expr: &Expr) { }; if SQL_REGEX.is_match(&content) { - checker.report_diagnostic(Diagnostic::new(HardcodedSQLExpression, expr.range())); + checker.report_diagnostic(HardcodedSQLExpression, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs index 35b35c850f..88086ca8bf 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr, StringLike}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -102,10 +102,10 @@ fn check(checker: &Checker, value: &str, range: TextRange) { } } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HardcodedTempFile { string: value.to_string(), }, range, - )); + ); } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs index 8fdfdd702f..035bb4c892 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_false; use ruff_python_ast::{self as ast, Arguments}; @@ -141,23 +141,23 @@ fn detect_insecure_hashlib_calls( hash_func_name.to_ascii_lowercase().as_str(), "md4" | "md5" | "sha" | "sha1" ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HashlibInsecureHashFunction { library: "hashlib".to_string(), string: hash_func_name.to_string(), }, name_arg.range(), - )); + ); } } HashlibCall::WeakHash(func_name) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HashlibInsecureHashFunction { library: "hashlib".to_string(), string: (*func_name).to_string(), }, call.func.range(), - )); + ); } } } @@ -186,13 +186,13 @@ fn detect_insecure_crypt_calls(checker: &Checker, call: &ast::ExprCall) { qualified_name.segments(), ["crypt", "METHOD_CRYPT" | "METHOD_MD5" | "METHOD_BLOWFISH"] ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( HashlibInsecureHashFunction { library: "crypt".to_string(), string: qualified_name.to_string(), }, method.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs index 100a15d40e..14f96de490 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -70,23 +70,20 @@ pub(crate) fn jinja2_autoescape_false(checker: &Checker, call: &ast::ExprCall) { Expr::Call(ast::ExprCall { func, .. }) => { if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() { if id != "select_autoescape" { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( Jinja2AutoescapeFalse { value: true }, keyword.range(), - )); + ); } } } - _ => checker.report_diagnostic(Diagnostic::new( - Jinja2AutoescapeFalse { value: true }, - keyword.range(), - )), + _ => { + checker + .report_diagnostic(Jinja2AutoescapeFalse { value: true }, keyword.range()); + } } } else { - checker.report_diagnostic(Diagnostic::new( - Jinja2AutoescapeFalse { value: false }, - call.func.range(), - )); + checker.report_diagnostic(Jinja2AutoescapeFalse { value: false }, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs index 95e9264195..48aab788dd 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::Modules; @@ -51,9 +51,6 @@ pub(crate) fn logging_config_insecure_listen(checker: &Checker, call: &ast::Expr return; } - checker.report_diagnostic(Diagnostic::new( - LoggingConfigInsecureListen, - call.func.range(), - )); + checker.report_diagnostic(LoggingConfigInsecureListen, call.func.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/mako_templates.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/mako_templates.rs index ecf38b92dd..8ca83f4abb 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/mako_templates.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/mako_templates.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; @@ -50,6 +50,6 @@ pub(crate) fn mako_templates(checker: &Checker, call: &ast::ExprCall) { matches!(qualified_name.segments(), ["mako", "template", "Template"]) }) { - checker.report_diagnostic(Diagnostic::new(MakoTemplates, call.func.range())); + checker.report_diagnostic(MakoTemplates, call.func.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/paramiko_calls.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/paramiko_calls.rs index bc76d74ebc..45f553d694 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/paramiko_calls.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/paramiko_calls.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -45,6 +45,6 @@ pub(crate) fn paramiko_call(checker: &Checker, func: &Expr) { matches!(qualified_name.segments(), ["paramiko", "exec_command"]) }) { - checker.report_diagnostic(Diagnostic::new(ParamikoCall, func.range())); + checker.report_diagnostic(ParamikoCall, func.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs index abb0f034b2..c6745ebb8b 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::helpers::is_const_false; @@ -65,12 +65,12 @@ pub(crate) fn request_with_no_cert_validation(checker: &Checker, call: &ast::Exp { if let Some(keyword) = call.arguments.find_keyword("verify") { if is_const_false(&keyword.value) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RequestWithNoCertValidation { string: target.to_string(), }, keyword.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/request_without_timeout.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/request_without_timeout.rs index 12a553d9b5..7a27c805a2 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/request_without_timeout.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/request_without_timeout.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; @@ -70,22 +70,22 @@ pub(crate) fn request_without_timeout(checker: &Checker, call: &ast::ExprCall) { { if let Some(keyword) = call.arguments.find_keyword("timeout") { if keyword.value.is_none_literal_expr() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RequestWithoutTimeout { implicit: false, module: module.to_string(), }, keyword.range(), - )); + ); } } else if module == "requests" { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RequestWithoutTimeout { implicit: true, module: module.to_string(), }, call.func.range(), - )); + ); } } } 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 89972bca1a..5b578a8e5c 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 @@ -1,7 +1,7 @@ //! Checks relating to shell injection. use crate::preview::is_shell_injection_only_trusted_input_enabled; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::Truthiness; use ruff_python_ast::{self as ast, Arguments, Expr}; @@ -314,13 +314,13 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { truthiness: truthiness @ (Truthiness::True | Truthiness::Truthy), }) => { if checker.enabled(Rule::SubprocessPopenWithShellEqualsTrue) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SubprocessPopenWithShellEqualsTrue { safety: Safety::from(arg), is_exact: matches!(truthiness, Truthiness::True), }, call.func.range(), - )); + ); } } // S603 @@ -329,10 +329,10 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { || !is_shell_injection_only_trusted_input_enabled(checker.settings) { if checker.enabled(Rule::SubprocessWithoutShellEqualsTrue) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SubprocessWithoutShellEqualsTrue, call.func.range(), - )); + ); } } } @@ -344,12 +344,12 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { { // S604 if checker.enabled(Rule::CallWithShellEqualsTrue) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( CallWithShellEqualsTrue { is_exact: matches!(truthiness, Truthiness::True), }, call.func.range(), - )); + ); } } @@ -357,12 +357,12 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { if checker.enabled(Rule::StartProcessWithAShell) { if matches!(call_kind, Some(CallKind::Shell)) { if let Some(arg) = call.arguments.args.first() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( StartProcessWithAShell { safety: Safety::from(arg), }, call.func.range(), - )); + ); } } } @@ -370,7 +370,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { // S606 if checker.enabled(Rule::StartProcessWithNoShell) { if matches!(call_kind, Some(CallKind::NoShell)) { - checker.report_diagnostic(Diagnostic::new(StartProcessWithNoShell, call.func.range())); + checker.report_diagnostic(StartProcessWithNoShell, call.func.range()); } } @@ -379,10 +379,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { if call_kind.is_some() { if let Some(arg) = call.arguments.args.first() { if is_partial_path(arg) { - checker.report_diagnostic(Diagnostic::new( - StartProcessWithPartialPath, - arg.range(), - )); + checker.report_diagnostic(StartProcessWithPartialPath, arg.range()); } } } @@ -403,10 +400,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { { if let Some(arg) = call.arguments.args.first() { if is_wildcard_command(arg) { - checker.report_diagnostic(Diagnostic::new( - UnixCommandWildcardInjection, - arg.range(), - )); + checker.report_diagnostic(UnixCommandWildcardInjection, arg.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_insecure_version.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_insecure_version.rs index 82365a74bf..28164d334c 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_insecure_version.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_insecure_version.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Int}; use ruff_text_size::Ranged; @@ -60,7 +60,7 @@ pub(crate) fn snmp_insecure_version(checker: &Checker, call: &ast::ExprCall) { .. }) ) { - checker.report_diagnostic(Diagnostic::new(SnmpInsecureVersion, keyword.range())); + checker.report_diagnostic(SnmpInsecureVersion, keyword.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs index f33fdbc8fc..e89b2f0d60 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; @@ -52,7 +52,7 @@ pub(crate) fn snmp_weak_cryptography(checker: &Checker, call: &ast::ExprCall) { ) }) { - checker.report_diagnostic(Diagnostic::new(SnmpWeakCryptography, call.func.range())); + checker.report_diagnostic(SnmpWeakCryptography, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssh_no_host_key_verification.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssh_no_host_key_verification.rs index 7956608f39..c109f7c09e 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssh_no_host_key_verification.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssh_no_host_key_verification.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; @@ -78,9 +78,6 @@ pub(crate) fn ssh_no_host_key_verification(checker: &Checker, call: &ExprCall) { ["paramiko", "client", "SSHClient"] | ["paramiko", "SSHClient"] ) }) { - checker.report_diagnostic(Diagnostic::new( - SSHNoHostKeyVerification, - policy_argument.range(), - )); + checker.report_diagnostic(SSHNoHostKeyVerification, policy_argument.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_insecure_version.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_insecure_version.rs index 70bddf995a..886733befd 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_insecure_version.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_insecure_version.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall}; use ruff_text_size::Ranged; @@ -68,22 +68,22 @@ pub(crate) fn ssl_insecure_version(checker: &Checker, call: &ExprCall) { match &keyword.value { Expr::Name(ast::ExprName { id, .. }) => { if is_insecure_protocol(id) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SslInsecureVersion { protocol: id.to_string(), }, keyword.range(), - )); + ); } } Expr::Attribute(ast::ExprAttribute { attr, .. }) => { if is_insecure_protocol(attr) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SslInsecureVersion { protocol: attr.to_string(), }, keyword.range(), - )); + ); } } _ => {} diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_bad_defaults.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_bad_defaults.rs index ab8367a7d2..82c6362b7b 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_bad_defaults.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_bad_defaults.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, StmtFunctionDef}; @@ -57,22 +57,22 @@ pub(crate) fn ssl_with_bad_defaults(checker: &Checker, function_def: &StmtFuncti match default { Expr::Name(ast::ExprName { id, range, .. }) => { if is_insecure_protocol(id.as_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SslWithBadDefaults { protocol: id.to_string(), }, *range, - )); + ); } } Expr::Attribute(ast::ExprAttribute { attr, range, .. }) => { if is_insecure_protocol(attr.as_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SslWithBadDefaults { protocol: attr.to_string(), }, *range, - )); + ); } } _ => {} diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_no_version.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_no_version.rs index 854c8f19cc..9bedb2eeb6 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_no_version.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_no_version.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprCall; use ruff_text_size::Ranged; @@ -43,7 +43,7 @@ pub(crate) fn ssl_with_no_version(checker: &Checker, call: &ExprCall) { .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["ssl", "wrap_socket"])) { if call.arguments.find_keyword("ssl_version").is_none() { - checker.report_diagnostic(Diagnostic::new(SslWithNoVersion, call.range())); + checker.report_diagnostic(SslWithNoVersion, call.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_function_call.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_function_call.rs index c7886e8bcf..6302b767c2 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_function_call.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_function_call.rs @@ -2,14 +2,13 @@ //! //! See: use itertools::Either; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, ExprCall, Operator}; use ruff_text_size::{Ranged, TextRange}; use crate::checkers::ast::Checker; use crate::preview::is_suspicious_function_reference_enabled; -use crate::registry::AsRule; /// ## What it does /// Checks for calls to `pickle` functions or modules that wrap them. @@ -1035,16 +1034,20 @@ fn suspicious_function( return; }; - let diagnostic = match qualified_name.segments() { + match qualified_name.segments() { // Pickle ["pickle" | "dill", "load" | "loads" | "Unpickler"] | ["shelve", "open" | "DbfilenameShelf"] | ["jsonpickle", "decode"] | ["jsonpickle", "unpickler", "decode"] - | ["pandas", "read_pickle"] => Diagnostic::new(SuspiciousPickleUsage, range), + | ["pandas", "read_pickle"] => { + checker.report_diagnostic_if_enabled(SuspiciousPickleUsage, range) + } // Marshal - ["marshal", "load" | "loads"] => Diagnostic::new(SuspiciousMarshalUsage, range), + ["marshal", "load" | "loads"] => { + checker.report_diagnostic_if_enabled(SuspiciousMarshalUsage, range) + } // InsecureHash [ @@ -1059,7 +1062,7 @@ fn suspicious_function( "primitives", "hashes", "SHA1" | "MD5", - ] => Diagnostic::new(SuspiciousInsecureHashUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousInsecureHashUsage, range), // InsecureCipher [ @@ -1075,7 +1078,7 @@ fn suspicious_function( "ciphers", "algorithms", "ARC4" | "Blowfish" | "IDEA", - ] => Diagnostic::new(SuspiciousInsecureCipherUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousInsecureCipherUsage, range), // InsecureCipherMode [ @@ -1085,13 +1088,17 @@ fn suspicious_function( "ciphers", "modes", "ECB", - ] => Diagnostic::new(SuspiciousInsecureCipherModeUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousInsecureCipherModeUsage, range), // Mktemp - ["tempfile", "mktemp"] => Diagnostic::new(SuspiciousMktempUsage, range), + ["tempfile", "mktemp"] => { + checker.report_diagnostic_if_enabled(SuspiciousMktempUsage, range) + } // Eval - ["" | "builtins", "eval"] => Diagnostic::new(SuspiciousEvalUsage, range), + ["" | "builtins", "eval"] => { + checker.report_diagnostic_if_enabled(SuspiciousEvalUsage, range) + } // MarkSafe ["django", "utils", "safestring" | "html", "mark_safe"] => { @@ -1102,7 +1109,7 @@ fn suspicious_function( } } } - Diagnostic::new(SuspiciousMarkSafeUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousMarkSafeUsage, range) } // URLOpen (`Request`) @@ -1124,7 +1131,7 @@ fn suspicious_function( } } } - Diagnostic::new(SuspiciousURLOpenUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousURLOpenUsage, range) } // URLOpen (`urlopen`, `urlretrieve`) @@ -1176,7 +1183,7 @@ fn suspicious_function( } } } - Diagnostic::new(SuspiciousURLOpenUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousURLOpenUsage, range) } // URLOpen (`URLopener`, `FancyURLopener`) @@ -1187,18 +1194,18 @@ fn suspicious_function( "urllib", "request", "URLopener" | "FancyURLopener", - ] => Diagnostic::new(SuspiciousURLOpenUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousURLOpenUsage, range), // NonCryptographicRandom [ "random", "Random" | "random" | "randrange" | "randint" | "choice" | "choices" | "uniform" | "triangular" | "randbytes", - ] => Diagnostic::new(SuspiciousNonCryptographicRandomUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousNonCryptographicRandomUsage, range), // UnverifiedContext ["ssl", "_create_unverified_context"] => { - Diagnostic::new(SuspiciousUnverifiedContextUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousUnverifiedContextUsage, range) } // XMLCElementTree @@ -1207,7 +1214,7 @@ fn suspicious_function( "etree", "cElementTree", "parse" | "iterparse" | "fromstring" | "XMLParser", - ] => Diagnostic::new(SuspiciousXMLCElementTreeUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousXMLCElementTreeUsage, range), // XMLElementTree [ @@ -1215,31 +1222,31 @@ fn suspicious_function( "etree", "ElementTree", "parse" | "iterparse" | "fromstring" | "XMLParser", - ] => Diagnostic::new(SuspiciousXMLElementTreeUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousXMLElementTreeUsage, range), // XMLExpatReader ["xml", "sax", "expatreader", "create_parser"] => { - Diagnostic::new(SuspiciousXMLExpatReaderUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousXMLExpatReaderUsage, range) } // XMLExpatBuilder ["xml", "dom", "expatbuilder", "parse" | "parseString"] => { - Diagnostic::new(SuspiciousXMLExpatBuilderUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousXMLExpatBuilderUsage, range) } // XMLSax ["xml", "sax", "parse" | "parseString" | "make_parser"] => { - Diagnostic::new(SuspiciousXMLSaxUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousXMLSaxUsage, range) } // XMLMiniDOM ["xml", "dom", "minidom", "parse" | "parseString"] => { - Diagnostic::new(SuspiciousXMLMiniDOMUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousXMLMiniDOMUsage, range) } // XMLPullDOM ["xml", "dom", "pulldom", "parse" | "parseString"] => { - Diagnostic::new(SuspiciousXMLPullDOMUsage, range) + checker.report_diagnostic_if_enabled(SuspiciousXMLPullDOMUsage, range) } // XMLETree @@ -1248,20 +1255,16 @@ fn suspicious_function( "etree", "parse" | "fromstring" | "RestrictedElement" | "GlobalParserTLS" | "getDefaultParser" | "check_docinfo", - ] => Diagnostic::new(SuspiciousXMLETreeUsage, range), + ] => checker.report_diagnostic_if_enabled(SuspiciousXMLETreeUsage, range), // Telnet - ["telnetlib", ..] => Diagnostic::new(SuspiciousTelnetUsage, range), + ["telnetlib", ..] => checker.report_diagnostic_if_enabled(SuspiciousTelnetUsage, range), // FTPLib - ["ftplib", ..] => Diagnostic::new(SuspiciousFTPLibUsage, range), + ["ftplib", ..] => checker.report_diagnostic_if_enabled(SuspiciousFTPLibUsage, range), _ => return, }; - - if checker.enabled(diagnostic.rule()) { - checker.report_diagnostic(diagnostic); - } } /// S308 diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_imports.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_imports.rs index 5b3522c56e..1951141db0 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_imports.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_imports.rs @@ -1,13 +1,12 @@ //! Check for imports of or from suspicious modules. //! //! See: -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Stmt}; -use ruff_text_size::{Ranged, TextRange}; +use ruff_text_size::Ranged; use crate::checkers::ast::Checker; -use crate::registry::AsRule; /// ## What it does /// Checks for imports of the `telnetlib` module. @@ -362,42 +361,47 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { for name in names { match name.name.as_str() { "telnetlib" => { - check_and_push_diagnostic(checker, SuspiciousTelnetlibImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousTelnetlibImport, name.range); } "ftplib" => { - check_and_push_diagnostic(checker, SuspiciousFtplibImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousFtplibImport, name.range); } "pickle" | "cPickle" | "dill" | "shelve" => { - check_and_push_diagnostic(checker, SuspiciousPickleImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousPickleImport, name.range); } "subprocess" => { - check_and_push_diagnostic(checker, SuspiciousSubprocessImport, name.range); + checker + .report_diagnostic_if_enabled(SuspiciousSubprocessImport, name.range); } "xml.etree.cElementTree" | "xml.etree.ElementTree" => { - check_and_push_diagnostic(checker, SuspiciousXmlEtreeImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousXmlEtreeImport, name.range); } "xml.sax" => { - check_and_push_diagnostic(checker, SuspiciousXmlSaxImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousXmlSaxImport, name.range); } "xml.dom.expatbuilder" => { - check_and_push_diagnostic(checker, SuspiciousXmlExpatImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousXmlExpatImport, name.range); } "xml.dom.minidom" => { - check_and_push_diagnostic(checker, SuspiciousXmlMinidomImport, name.range); + checker + .report_diagnostic_if_enabled(SuspiciousXmlMinidomImport, name.range); } "xml.dom.pulldom" => { - check_and_push_diagnostic(checker, SuspiciousXmlPulldomImport, name.range); + checker + .report_diagnostic_if_enabled(SuspiciousXmlPulldomImport, name.range); + } + "lxml" => { + checker.report_diagnostic_if_enabled(SuspiciousLxmlImport, name.range); } - "lxml" => check_and_push_diagnostic(checker, SuspiciousLxmlImport, name.range), "xmlrpc" => { - check_and_push_diagnostic(checker, SuspiciousXmlrpcImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousXmlrpcImport, name.range); } "Crypto.Cipher" | "Crypto.Hash" | "Crypto.IO" | "Crypto.Protocol" | "Crypto.PublicKey" | "Crypto.Random" | "Crypto.Signature" | "Crypto.Util" => { - check_and_push_diagnostic(checker, SuspiciousPycryptoImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousPycryptoImport, name.range); } "pyghmi" => { - check_and_push_diagnostic(checker, SuspiciousPyghmiImport, name.range); + checker.report_diagnostic_if_enabled(SuspiciousPyghmiImport, name.range); } _ => {} } @@ -406,27 +410,30 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { Stmt::ImportFrom(ast::StmtImportFrom { module, names, .. }) => { let Some(identifier) = module else { return }; match identifier.as_str() { - "telnetlib" => check_and_push_diagnostic( - checker, - SuspiciousTelnetlibImport, - identifier.range(), - ), + "telnetlib" => { + checker.report_diagnostic_if_enabled( + SuspiciousTelnetlibImport, + identifier.range(), + ); + } "ftplib" => { - check_and_push_diagnostic(checker, SuspiciousFtplibImport, identifier.range()); + checker + .report_diagnostic_if_enabled(SuspiciousFtplibImport, identifier.range()); } "pickle" | "cPickle" | "dill" | "shelve" => { - check_and_push_diagnostic(checker, SuspiciousPickleImport, identifier.range()); + checker + .report_diagnostic_if_enabled(SuspiciousPickleImport, identifier.range()); + } + "subprocess" => { + checker.report_diagnostic_if_enabled( + SuspiciousSubprocessImport, + identifier.range(), + ); } - "subprocess" => check_and_push_diagnostic( - checker, - SuspiciousSubprocessImport, - identifier.range(), - ), "xml.etree" => { for name in names { if matches!(name.name.as_str(), "cElementTree" | "ElementTree") { - check_and_push_diagnostic( - checker, + checker.report_diagnostic_if_enabled( SuspiciousXmlEtreeImport, identifier.range(), ); @@ -434,17 +441,13 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { } } "xml.etree.cElementTree" | "xml.etree.ElementTree" => { - check_and_push_diagnostic( - checker, - SuspiciousXmlEtreeImport, - identifier.range(), - ); + checker + .report_diagnostic_if_enabled(SuspiciousXmlEtreeImport, identifier.range()); } "xml" => { for name in names { if name.name.as_str() == "sax" { - check_and_push_diagnostic( - checker, + checker.report_diagnostic_if_enabled( SuspiciousXmlSaxImport, identifier.range(), ); @@ -452,58 +455,61 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { } } "xml.sax" => { - check_and_push_diagnostic(checker, SuspiciousXmlSaxImport, identifier.range()); + checker + .report_diagnostic_if_enabled(SuspiciousXmlSaxImport, identifier.range()); } "xml.dom" => { for name in names { match name.name.as_str() { - "expatbuilder" => check_and_push_diagnostic( - checker, - SuspiciousXmlExpatImport, - identifier.range(), - ), - "minidom" => check_and_push_diagnostic( - checker, - SuspiciousXmlMinidomImport, - identifier.range(), - ), - "pulldom" => check_and_push_diagnostic( - checker, - SuspiciousXmlPulldomImport, - identifier.range(), - ), - _ => (), + "expatbuilder" => { + checker.report_diagnostic_if_enabled( + SuspiciousXmlExpatImport, + identifier.range(), + ); + } + "minidom" => { + checker.report_diagnostic_if_enabled( + SuspiciousXmlMinidomImport, + identifier.range(), + ); + } + "pulldom" => { + checker.report_diagnostic_if_enabled( + SuspiciousXmlPulldomImport, + identifier.range(), + ); + } + _ => {} } } } "xml.dom.expatbuilder" => { - check_and_push_diagnostic( - checker, - SuspiciousXmlExpatImport, + checker + .report_diagnostic_if_enabled(SuspiciousXmlExpatImport, identifier.range()); + } + "xml.dom.minidom" => { + checker.report_diagnostic_if_enabled( + SuspiciousXmlMinidomImport, + identifier.range(), + ); + } + "xml.dom.pulldom" => { + checker.report_diagnostic_if_enabled( + SuspiciousXmlPulldomImport, identifier.range(), ); } - "xml.dom.minidom" => check_and_push_diagnostic( - checker, - SuspiciousXmlMinidomImport, - identifier.range(), - ), - "xml.dom.pulldom" => check_and_push_diagnostic( - checker, - SuspiciousXmlPulldomImport, - identifier.range(), - ), "lxml" => { - check_and_push_diagnostic(checker, SuspiciousLxmlImport, identifier.range()); + checker.report_diagnostic_if_enabled(SuspiciousLxmlImport, identifier.range()); } "xmlrpc" => { - check_and_push_diagnostic(checker, SuspiciousXmlrpcImport, identifier.range()); + checker + .report_diagnostic_if_enabled(SuspiciousXmlrpcImport, identifier.range()); } "wsgiref.handlers" => { for name in names { if name.name.as_str() == "CGIHandler" { - check_and_push_diagnostic( - checker, + checker.report_diagnostic_if_enabled( SuspiciousHttpoxyImport, identifier.range(), ); @@ -513,8 +519,7 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { "twisted.web.twcgi" => { for name in names { if name.name.as_str() == "CGIScript" { - check_and_push_diagnostic( - checker, + checker.report_diagnostic_if_enabled( SuspiciousHttpoxyImport, identifier.range(), ); @@ -534,8 +539,7 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { | "Signature" | "Util" ) { - check_and_push_diagnostic( - checker, + checker.report_diagnostic_if_enabled( SuspiciousPycryptoImport, identifier.range(), ); @@ -544,14 +548,12 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { } "Crypto.Cipher" | "Crypto.Hash" | "Crypto.IO" | "Crypto.Protocol" | "Crypto.PublicKey" | "Crypto.Random" | "Crypto.Signature" | "Crypto.Util" => { - check_and_push_diagnostic( - checker, - SuspiciousPycryptoImport, - identifier.range(), - ); + checker + .report_diagnostic_if_enabled(SuspiciousPycryptoImport, identifier.range()); } "pyghmi" => { - check_and_push_diagnostic(checker, SuspiciousPyghmiImport, identifier.range()); + checker + .report_diagnostic_if_enabled(SuspiciousPyghmiImport, identifier.range()); } _ => {} } @@ -559,10 +561,3 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { _ => panic!("Expected Stmt::Import | Stmt::ImportFrom"), } } - -fn check_and_push_diagnostic(checker: &Checker, diagnostic: T, range: TextRange) { - let diagnostic = Diagnostic::new(diagnostic, range); - if checker.enabled(diagnostic.rule()) { - checker.report_diagnostic(diagnostic); - } -} diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/tarfile_unsafe_members.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/tarfile_unsafe_members.rs index f4d9380971..f1f0587064 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/tarfile_unsafe_members.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/tarfile_unsafe_members.rs @@ -1,5 +1,4 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; @@ -70,5 +69,5 @@ pub(crate) fn tarfile_unsafe_members(checker: &Checker, call: &ast::ExprCall) { return; } - checker.report_diagnostic(Diagnostic::new(TarfileUnsafeMembers, call.func.range())); + checker.report_diagnostic(TarfileUnsafeMembers, call.func.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_continue.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_continue.rs index 193c797a09..ac7e7ebaf0 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_continue.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_continue.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{ExceptHandler, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -64,7 +64,7 @@ pub(crate) fn try_except_continue( ) { if matches!(body, [Stmt::Continue(_)]) { if check_typed_exception || is_untyped_exception(type_, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new(TryExceptContinue, except_handler.range())); + checker.report_diagnostic(TryExceptContinue, except_handler.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_pass.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_pass.rs index ff48968c98..3fdf1bf37c 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_pass.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_pass.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{ExceptHandler, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -60,7 +60,7 @@ pub(crate) fn try_except_pass( ) { if matches!(body, [Stmt::Pass(_)]) { if check_typed_exception || is_untyped_exception(type_, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new(TryExceptPass, except_handler.range())); + checker.report_diagnostic(TryExceptPass, except_handler.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_markup_use.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_markup_use.rs index 7c9cac7921..f82d6fbc09 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_markup_use.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_markup_use.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, ExprCall}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_semantic::{Modules, SemanticModel}; @@ -112,12 +112,12 @@ pub(crate) fn unsafe_markup_call(checker: &Checker, call: &ExprCall) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnsafeMarkupUse { name: qualified_name.to_string(), }, call.range(), - )); + ); } fn is_markup_call(qualified_name: &QualifiedName, settings: &LinterSettings) -> bool { diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs index 00a3df81a2..7c6510f585 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -82,16 +82,10 @@ pub(crate) fn unsafe_yaml_load(checker: &Checker, call: &ast::ExprCall) { Expr::Name(ast::ExprName { id, .. }) => Some(id.to_string()), _ => None, }; - checker.report_diagnostic(Diagnostic::new( - UnsafeYAMLLoad { loader }, - loader_arg.range(), - )); + checker.report_diagnostic(UnsafeYAMLLoad { loader }, loader_arg.range()); } } else { - checker.report_diagnostic(Diagnostic::new( - UnsafeYAMLLoad { loader: None }, - call.func.range(), - )); + checker.report_diagnostic(UnsafeYAMLLoad { loader: None }, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/weak_cryptographic_key.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/weak_cryptographic_key.rs index 47cc09a9dd..c89d8a7b3a 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/weak_cryptographic_key.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/weak_cryptographic_key.rs @@ -1,6 +1,6 @@ use std::fmt::{Display, Formatter}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprAttribute, ExprCall}; use ruff_text_size::{Ranged, TextRange}; @@ -55,10 +55,7 @@ pub(crate) fn weak_cryptographic_key(checker: &Checker, call: &ExprCall) { }; if cryptographic_key.is_vulnerable() { - checker.report_diagnostic(Diagnostic::new( - WeakCryptographicKey { cryptographic_key }, - range, - )); + checker.report_diagnostic(WeakCryptographicKey { cryptographic_key }, range); } } diff --git a/crates/ruff_linter/src/rules/flake8_blind_except/rules/blind_except.rs b/crates/ruff_linter/src/rules/flake8_blind_except/rules/blind_except.rs index 5680966fe9..c9119014f7 100644 --- a/crates/ruff_linter/src/rules/flake8_blind_except/rules/blind_except.rs +++ b/crates/ruff_linter/src/rules/flake8_blind_except/rules/blind_except.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; @@ -107,12 +107,12 @@ pub(crate) fn blind_except( return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BlindExcept { name: builtin_exception_type.to_string(), }, type_.range(), - )); + ); } /// A visitor to detect whether the exception with the given name was re-raised. diff --git a/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_default_value_positional_argument.rs b/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_default_value_positional_argument.rs index 5a27f40e57..f4f352a2ac 100644 --- a/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_default_value_positional_argument.rs +++ b/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_default_value_positional_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::name::UnqualifiedName; @@ -131,10 +131,7 @@ pub(crate) fn boolean_default_value_positional_argument( return; } - checker.report_diagnostic(Diagnostic::new( - BooleanDefaultValuePositionalArgument, - param.identifier(), - )); + checker.report_diagnostic(BooleanDefaultValuePositionalArgument, param.identifier()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_positional_value_in_call.rs b/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_positional_value_in_call.rs index 82dfca34bc..260d4e5663 100644 --- a/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_positional_value_in_call.rs +++ b/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_positional_value_in_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; @@ -61,6 +61,6 @@ pub(crate) fn boolean_positional_value_in_call(checker: &Checker, call: &ast::Ex .iter() .filter(|arg| arg.is_boolean_literal_expr()) { - checker.report_diagnostic(Diagnostic::new(BooleanPositionalValueInCall, arg.range())); + checker.report_diagnostic(BooleanPositionalValueInCall, arg.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_type_hint_positional_argument.rs b/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_type_hint_positional_argument.rs index 4be0578913..d06a8f7d42 100644 --- a/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_type_hint_positional_argument.rs +++ b/crates/ruff_linter/src/rules/flake8_boolean_trap/rules/boolean_type_hint_positional_argument.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; @@ -158,10 +157,7 @@ pub(crate) fn boolean_type_hint_positional_argument( return; } - checker.report_diagnostic(Diagnostic::new( - BooleanTypeHintPositionalArgument, - parameter.identifier(), - )); + checker.report_diagnostic(BooleanTypeHintPositionalArgument, parameter.identifier()); } } 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 e019e6a690..b1aa5bf9d1 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 @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Arguments, Expr, Keyword, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::SemanticModel; @@ -196,22 +196,22 @@ pub(crate) fn abstract_base_class( && is_empty_body(body) && !is_overload(decorator_list, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( EmptyMethodWithoutAbstractDecorator { name: format!("{name}.{method_name}"), }, stmt.range(), - )); + ); } } if checker.enabled(Rule::AbstractBaseClassWithoutAbstractMethod) { if !has_abstract_method { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( AbstractBaseClassWithoutAbstractMethod { name: name.to_string(), }, stmt.identifier(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_false.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_false.rs index 5be6814771..6ec957f8fe 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_false.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_false.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Stmt}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_false; @@ -79,10 +79,9 @@ pub(crate) fn assert_false(checker: &Checker, stmt: &Stmt, test: &Expr, msg: Opt return; } - let mut diagnostic = Diagnostic::new(AssertFalse, test.range()); + let mut diagnostic = checker.report_diagnostic(AssertFalse, test.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( checker.generator().stmt(&assertion_error(msg)), stmt.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_raises_exception.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_raises_exception.rs index e233a7c0db..0b9743aba5 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_raises_exception.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_raises_exception.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, WithItem}; use ruff_text_size::Ranged; @@ -99,9 +99,6 @@ pub(crate) fn assert_raises_exception(checker: &Checker, items: &[WithItem]) { continue; } - checker.report_diagnostic(Diagnostic::new( - AssertRaisesException { exception }, - item.range(), - )); + checker.report_diagnostic(AssertRaisesException { exception }, item.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs index 722f676137..d708793c1d 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -66,5 +66,5 @@ pub(crate) fn assignment_to_os_environ(checker: &Checker, targets: &[Expr]) { if id != "os" { return; } - checker.report_diagnostic(Diagnostic::new(AssignmentToOsEnviron, target.range())); + checker.report_diagnostic(AssignmentToOsEnviron, target.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/batched_without_explicit_strict.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/batched_without_explicit_strict.rs index fafc2fa966..8afefcd940 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/batched_without_explicit_strict.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/batched_without_explicit_strict.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::rules::flake8_bugbear::rules::is_infinite_iterable; -use ruff_diagnostics::{Diagnostic, FixAvailability, Violation}; +use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprCall; use ruff_python_ast::PythonVersion; @@ -86,6 +86,5 @@ pub(crate) fn batched_without_explicit_strict(checker: &Checker, call: &ExprCall return; } - let diagnostic = Diagnostic::new(BatchedWithoutExplicitStrict, call.range); - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(BatchedWithoutExplicitStrict, call.range); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/cached_instance_method.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/cached_instance_method.rs index 30175823c6..1c19a160ac 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/cached_instance_method.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/cached_instance_method.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::{self as ast, Expr}; @@ -102,7 +102,7 @@ pub(crate) fn cached_instance_method(checker: &Checker, function_def: &ast::Stmt return; } - checker.report_diagnostic(Diagnostic::new(CachedInstanceMethod, decorator.range())); + checker.report_diagnostic(CachedInstanceMethod, decorator.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/class_as_data_structure.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/class_as_data_structure.rs index 39ab5a9ae2..bf7994b990 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/class_as_data_structure.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/class_as_data_structure.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::analyze::visibility::{self, Visibility::Public}; @@ -105,7 +105,7 @@ pub(crate) fn class_as_data_structure(checker: &Checker, class_def: &ast::StmtCl } if has_dunder_init && public_methods == 1 { - checker.report_diagnostic(Diagnostic::new(ClassAsDataStructure, class_def.range())); + checker.report_diagnostic(ClassAsDataStructure, class_def.range()); } } 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 51d14bd114..dcda3372b5 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 @@ -2,7 +2,7 @@ use itertools::Itertools; use rustc_hash::{FxHashMap, FxHashSet}; use ruff_diagnostics::{AlwaysFixableViolation, Violation}; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext}; @@ -141,7 +141,7 @@ fn duplicate_handler_exceptions<'a>( if checker.enabled(Rule::DuplicateHandlerException) { // TODO(charlie): Handle "BaseException" and redundant exception aliases. if !duplicates.is_empty() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DuplicateHandlerException { names: duplicates .into_iter() @@ -167,7 +167,6 @@ fn duplicate_handler_exceptions<'a>( }, expr.range(), ))); - checker.report_diagnostic(diagnostic); } } @@ -217,13 +216,13 @@ pub(crate) fn duplicate_exceptions(checker: &Checker, handlers: &[ExceptHandler] .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( DuplicateTryBlockException { name: name.segments().join("."), is_star, }, expr.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_value.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_value.rs index 7a59df6266..346a1ae064 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_value.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_value.rs @@ -1,7 +1,7 @@ use anyhow::{Context, Result}; use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::Expr; @@ -60,7 +60,7 @@ pub(crate) fn duplicate_value(checker: &Checker, set: &ast::ExprSet) { for (index, value) in set.iter().enumerate() { if value.is_literal_expr() { if let Some(existing) = seen_values.insert(HashableExpr::from(value), value) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DuplicateValue { value: checker.generator().expr(value), existing: checker.generator().expr(existing), @@ -71,8 +71,6 @@ pub(crate) fn duplicate_value(checker: &Checker, set: &ast::ExprSet) { diagnostic.try_set_fix(|| { remove_member(set, index, checker.locator().contents()).map(Fix::safe_edit) }); - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs index cc512fee93..52375d2d74 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast}; use ruff_python_ast::{ExceptHandler, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -66,9 +66,6 @@ pub(crate) fn except_with_empty_tuple(checker: &Checker, except_handler: &Except .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); - checker.report_diagnostic(Diagnostic::new( - ExceptWithEmptyTuple { is_star }, - except_handler.range(), - )); + checker.report_diagnostic(ExceptWithEmptyTuple { is_star }, except_handler.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs index 25e4da777f..ca3b087446 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; use ruff_python_ast::{self as ast, ExceptHandler, Expr, Operator}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -69,10 +69,7 @@ pub(crate) fn except_with_non_exception_classes(checker: &Checker, except_handle .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); - checker.report_diagnostic(Diagnostic::new( - ExceptWithNonExceptionClasses { is_star }, - expr.range(), - )); + checker.report_diagnostic(ExceptWithNonExceptionClasses { is_star }, expr.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/f_string_docstring.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/f_string_docstring.rs index d5def15e96..d17b380c44 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/f_string_docstring.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/f_string_docstring.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; @@ -51,5 +51,5 @@ pub(crate) fn f_string_docstring(checker: &Checker, body: &[Stmt]) { if !value.is_f_string_expr() { return; } - checker.report_diagnostic(Diagnostic::new(FStringDocstring, stmt.identifier())); + checker.report_diagnostic(FStringDocstring, stmt.identifier()); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_call_in_argument_default.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_call_in_argument_default.rs index e6efec2bf7..05a24fe021 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_call_in_argument_default.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_call_in_argument_default.rs @@ -1,7 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Parameters}; use ruff_text_size::Ranged; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; @@ -113,12 +112,12 @@ impl Visitor<'_> for ArgumentDefaultVisitor<'_, '_> { ) }) { - self.checker.report_diagnostic(Diagnostic::new( + self.checker.report_diagnostic( FunctionCallInDefaultArgument { name: UnqualifiedName::from_expr(func).map(|name| name.to_string()), }, expr.range(), - )); + ); } visitor::walk_expr(self, expr); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs index f40692781c..bef045a9b4 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::types::Node; use ruff_python_ast::visitor; @@ -305,12 +305,12 @@ pub(crate) fn function_uses_loop_variable(checker: &Checker, node: &Node) { for name in suspicious_variables { if reassigned_in_loop.contains(&name.id.as_str()) { if checker.insert_flake8_bugbear_range(name.range()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( FunctionUsesLoopVariable { name: name.id.to_string(), }, name.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/getattr_with_constant.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/getattr_with_constant.rs index cdf6841774..3eee042415 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/getattr_with_constant.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/getattr_with_constant.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; @@ -68,7 +68,7 @@ pub(crate) fn getattr_with_constant(checker: &Checker, expr: &Expr, func: &Expr, return; } - let mut diagnostic = Diagnostic::new(GetAttrWithConstant, expr.range()); + let mut diagnostic = checker.report_diagnostic(GetAttrWithConstant, expr.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( pad( if matches!( @@ -88,5 +88,4 @@ pub(crate) fn getattr_with_constant(checker: &Checker, expr: &Expr, func: &Expr, ), expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs index e835a84dc4..b4c5d7f9ec 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -56,7 +56,7 @@ impl Violation for JumpStatementInFinally { fn walk_stmt(checker: &Checker, body: &[Stmt], f: fn(&Stmt) -> bool) { for stmt in body { if f(stmt) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( JumpStatementInFinally { name: match stmt { Stmt::Break(_) => "break", @@ -67,7 +67,7 @@ fn walk_stmt(checker: &Checker, body: &[Stmt], f: fn(&Stmt) -> bool) { .to_owned(), }, stmt.range(), - )); + ); } match stmt { Stmt::While(ast::StmtWhile { body, .. }) | Stmt::For(ast::StmtFor { body, .. }) => { diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_iterator_mutation.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_iterator_mutation.rs index 5b0e52543e..854c274664 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_iterator_mutation.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_iterator_mutation.rs @@ -1,7 +1,6 @@ use std::collections::HashMap; use std::fmt::Debug; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; @@ -110,7 +109,7 @@ pub(crate) fn loop_iterator_mutation(checker: &Checker, stmt_for: &StmtFor) { let name = UnqualifiedName::from_expr(iter) .map(|name| name.to_string()) .map(SourceCodeSnippet::new); - checker.report_diagnostic(Diagnostic::new(LoopIteratorMutation { name }, *mutation)); + checker.report_diagnostic(LoopIteratorMutation { name }, *mutation); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs index 51105419a8..647bf675a2 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr}; use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor; use ruff_python_ast::visitor::Visitor; @@ -64,12 +64,12 @@ pub(crate) fn loop_variable_overrides_iterator(checker: &Checker, target: &Expr, for (name, expr) in target_names { if iter_names.contains_key(name) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( LoopVariableOverridesIterator { name: name.to_string(), }, expr.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_argument_default.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_argument_default.rs index 01abdeacfa..7a4e462ad7 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_argument_default.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_argument_default.rs @@ -1,6 +1,6 @@ use std::fmt::Write; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::name::QualifiedName; @@ -111,7 +111,7 @@ pub(crate) fn mutable_argument_default(checker: &Checker, function_def: &ast::St is_immutable_annotation(expr, checker.semantic(), extend_immutable_calls.as_slice()) }) { - let mut diagnostic = Diagnostic::new(MutableArgumentDefault, default.range()); + let mut diagnostic = checker.report_diagnostic(MutableArgumentDefault, default.range()); // If the function body is on the same line as the function def, do not fix if let Some(fix) = move_initialization( @@ -126,7 +126,6 @@ pub(crate) fn mutable_argument_default(checker: &Checker, function_def: &ast::St ) { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_contextvar_default.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_contextvar_default.rs index 1923fcaa25..1188467478 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_contextvar_default.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_contextvar_default.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::name::QualifiedName; @@ -102,6 +102,6 @@ pub(crate) fn mutable_contextvar_default(checker: &Checker, call: &ast::ExprCall matches!(qualified_name.segments(), ["contextvars", "ContextVar"]) }) { - checker.report_diagnostic(Diagnostic::new(MutableContextvarDefault, default.range())); + checker.report_diagnostic(MutableContextvarDefault, default.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs index 261246d63e..30529639b9 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -85,7 +85,7 @@ pub(crate) fn no_explicit_stacklevel(checker: &Checker, call: &ast::ExprCall) { { return; } - let mut diagnostic = Diagnostic::new(NoExplicitStacklevel, call.func.range()); + let mut diagnostic = checker.report_diagnostic(NoExplicitStacklevel, call.func.range()); let edit = add_argument( "stacklevel=2", @@ -95,8 +95,6 @@ pub(crate) fn no_explicit_stacklevel(checker: &Checker, call: &ast::ExprCall) { ); diagnostic.set_fix(Fix::unsafe_edit(edit)); - - checker.report_diagnostic(diagnostic); } /// Returns `true` if `skip_file_prefixes` is set to its non-default value. diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_literal.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_literal.rs index 4c78d34598..980fde3422 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_literal.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_literal.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -39,6 +39,6 @@ impl Violation for RaiseLiteral { /// B016 pub(crate) fn raise_literal(checker: &Checker, expr: &Expr) { if expr.is_literal_expr() { - checker.report_diagnostic(Diagnostic::new(RaiseLiteral, expr.range())); + checker.report_diagnostic(RaiseLiteral, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs index 7e61499676..4b9797e327 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs @@ -1,7 +1,7 @@ use ruff_python_ast as ast; use ruff_python_ast::Stmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::RaiseStatementVisitor; use ruff_python_ast::statement_visitor::StatementVisitor; @@ -106,10 +106,7 @@ pub(crate) fn raise_without_from_inside_except( .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); - checker.report_diagnostic(Diagnostic::new( - RaiseWithoutFromInsideExcept { is_star }, - range, - )); + checker.report_diagnostic(RaiseWithoutFromInsideExcept { is_star }, range); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/re_sub_positional_args.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/re_sub_positional_args.rs index 93ac716753..f046d331d1 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/re_sub_positional_args.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/re_sub_positional_args.rs @@ -2,7 +2,7 @@ use std::fmt; use ruff_python_ast::{self as ast}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -75,10 +75,7 @@ pub(crate) fn re_sub_positional_args(checker: &Checker, call: &ast::ExprCall) { }; if call.arguments.args.len() > method.num_args() { - checker.report_diagnostic(Diagnostic::new( - ReSubPositionalArgs { method }, - call.range(), - )); + checker.report_diagnostic(ReSubPositionalArgs { method }, call.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs index 5fc41a1144..9af207f8b5 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, ExceptHandler, Expr}; use ruff_text_size::Ranged; @@ -79,7 +79,7 @@ pub(crate) fn redundant_tuple_in_exception_handler(checker: &Checker, handlers: if elt.is_starred_expr() { continue; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RedundantTupleInExceptionHandler { name: checker.generator().expr(elt), }, @@ -100,6 +100,5 @@ pub(crate) fn redundant_tuple_in_exception_handler(checker: &Checker, handlers: ), type_.range(), ))); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/return_in_generator.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/return_in_generator.rs index 6c77f89522..bfffb34494 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/return_in_generator.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/return_in_generator.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::statement_visitor; @@ -101,7 +100,7 @@ pub(crate) fn return_in_generator(checker: &Checker, function_def: &StmtFunction if visitor.has_yield { if let Some(return_) = visitor.return_ { - checker.report_diagnostic(Diagnostic::new(ReturnInGenerator, return_)); + checker.report_diagnostic(ReturnInGenerator, return_); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs index d140cc2078..460dab1031 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Comprehension, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::{self, Visitor}; use ruff_text_size::Ranged; @@ -339,6 +339,6 @@ pub(crate) fn reuse_of_groupby_generator( finder.visit_stmt(stmt); } for expr in finder.exprs { - checker.report_diagnostic(Diagnostic::new(ReuseOfGroupbyGenerator, expr.range())); + checker.report_diagnostic(ReuseOfGroupbyGenerator, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/setattr_with_constant.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/setattr_with_constant.rs index 4694c07df6..8ed5452a10 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/setattr_with_constant.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/setattr_with_constant.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr, ExprContext, Identifier, Stmt}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_codegen::Generator; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; @@ -90,12 +90,11 @@ pub(crate) fn setattr_with_constant(checker: &Checker, expr: &Expr, func: &Expr, }) = checker.semantic().current_statement() { if expr == child.as_ref() { - let mut diagnostic = Diagnostic::new(SetAttrWithConstant, expr.range()); + let mut diagnostic = checker.report_diagnostic(SetAttrWithConstant, expr.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( assignment(obj, name.to_str(), value, checker.generator()), expr.range(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs index dc295cb21f..c857b3be38 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, Keyword}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -71,9 +71,6 @@ pub(crate) fn star_arg_unpacking_after_keyword_arg( if arg.start() <= keyword.start() { continue; } - checker.report_diagnostic(Diagnostic::new( - StarArgUnpackingAfterKeywordArg, - arg.range(), - )); + checker.report_diagnostic(StarArgUnpackingAfterKeywordArg, arg.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/static_key_dict_comprehension.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/static_key_dict_comprehension.rs index fdd937ade2..5852ef71dc 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/static_key_dict_comprehension.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/static_key_dict_comprehension.rs @@ -1,6 +1,6 @@ use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::StoredNameFinder; use ruff_python_ast::visitor::Visitor; @@ -58,12 +58,12 @@ pub(crate) fn static_key_dict_comprehension(checker: &Checker, dict_comp: &ast:: }; if is_constant(&dict_comp.key, &names) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( StaticKeyDictComprehension { key: SourceCodeSnippet::from_str(checker.locator().slice(dict_comp.key.as_ref())), }, dict_comp.key.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs index 7eb149edd9..3f982e5592 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -73,6 +73,6 @@ pub(crate) fn strip_with_multi_characters( }; if value.chars().count() > 1 && !value.chars().all_unique() { - checker.report_diagnostic(Diagnostic::new(StripWithMultiCharacters, expr.range())); + checker.report_diagnostic(StripWithMultiCharacters, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unary_prefix_increment_decrement.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unary_prefix_increment_decrement.rs index d7b6c193c0..1fbfc42d5a 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unary_prefix_increment_decrement.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unary_prefix_increment_decrement.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, UnaryOp}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -61,20 +61,20 @@ pub(crate) fn unary_prefix_increment_decrement( }; match (op, nested_op) { (UnaryOp::UAdd, UnaryOp::UAdd) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnaryPrefixIncrementDecrement { operator: UnaryPrefixOperatorType::Increment, }, expr.range(), - )); + ); } (UnaryOp::USub, UnaryOp::USub) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnaryPrefixIncrementDecrement { operator: UnaryPrefixOperatorType::Decrement, }, expr.range(), - )); + ); } _ => {} } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs index 2c2b1442fe..e9230d664b 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -46,17 +46,13 @@ pub(crate) fn unintentional_type_annotation( match target { Expr::Subscript(ast::ExprSubscript { value, .. }) => { if value.is_name_expr() { - checker - .report_diagnostic(Diagnostic::new(UnintentionalTypeAnnotation, stmt.range())); + checker.report_diagnostic(UnintentionalTypeAnnotation, stmt.range()); } } Expr::Attribute(ast::ExprAttribute { value, .. }) => { if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() { if id != "self" { - checker.report_diagnostic(Diagnostic::new( - UnintentionalTypeAnnotation, - stmt.range(), - )); + checker.report_diagnostic(UnintentionalTypeAnnotation, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs index 632fd5d00f..8d0934505c 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -72,7 +72,7 @@ pub(crate) fn unreliable_callable_check( return; } - let mut diagnostic = Diagnostic::new(UnreliableCallableCheck, expr.range()); + let mut diagnostic = checker.report_diagnostic(UnreliableCallableCheck, expr.range()); if builtins_function == "hasattr" { diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol( @@ -87,5 +87,4 @@ pub(crate) fn unreliable_callable_check( Ok(Fix::safe_edits(binding_edit, import_edit)) }); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs index 01d01ad853..233d8e3c8c 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::helpers; @@ -121,7 +121,7 @@ pub(crate) fn unused_loop_control_variable(checker: &Checker, stmt_for: &ast::St .is_match(rename.as_str()) .then_some(rename); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnusedLoopControlVariable { name: name.to_string(), rename: rename.clone(), @@ -147,7 +147,6 @@ pub(crate) fn unused_loop_control_variable(checker: &Checker, stmt_for: &ast::St } } } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_comparison.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_comparison.rs index 2c1434106c..274beba9ae 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_comparison.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_comparison.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, Stmt}; use ruff_python_semantic::ScopeKind; @@ -78,22 +78,22 @@ pub(crate) fn useless_comparison(checker: &Checker, expr: &Expr) { .and_then(Stmt::as_expr_stmt) .is_some_and(|last_stmt| &*last_stmt.value == expr) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UselessComparison { at: ComparisonLocationAt::EndOfFunction, }, expr.range(), - )); + ); return; } } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UselessComparison { at: ComparisonLocationAt::MiddleBody, }, expr.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs index 350681548c..866ad761b6 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -63,6 +63,6 @@ pub(crate) fn useless_contextlib_suppress( matches!(qualified_name.segments(), ["contextlib", "suppress"]) }) { - checker.report_diagnostic(Diagnostic::new(UselessContextlibSuppress, expr.range())); + checker.report_diagnostic(UselessContextlibSuppress, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_expression.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_expression.rs index b711dcfdb6..39f01c9ed0 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_expression.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_expression.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_ast::helpers::contains_effect; @@ -100,22 +100,22 @@ pub(crate) fn useless_expression(checker: &Checker, value: &Expr) { // Flag attributes as useless expressions, even if they're attached to calls or other // expressions. if value.is_attribute_expr() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UselessExpression { kind: Kind::Attribute, }, value.range(), - )); + ); } return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UselessExpression { kind: Kind::Expression, }, value.range(), - )); + ); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs index 88e2554000..2dfb56826f 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr}; @@ -63,8 +63,9 @@ pub(crate) fn zip_without_explicit_strict(checker: &Checker, call: &ast::ExprCal .iter() .any(|arg| is_infinite_iterable(arg, semantic)) { - checker.report_diagnostic( - Diagnostic::new(ZipWithoutExplicitStrict, call.range()).with_fix(Fix::applicable_edit( + checker + .report_diagnostic(ZipWithoutExplicitStrict, call.range()) + .set_fix(Fix::applicable_edit( add_argument( "strict=False", &call.arguments, @@ -82,8 +83,7 @@ pub(crate) fn zip_without_explicit_strict(checker: &Checker, call: &ast::ExprCal } else { Applicability::Safe }, - )), - ); + )); } } diff --git a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_argument_shadowing.rs b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_argument_shadowing.rs index e2b24dd350..76175c7a7b 100644 --- a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_argument_shadowing.rs +++ b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_argument_shadowing.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, Parameter}; @@ -92,11 +91,11 @@ pub(crate) fn builtin_argument_shadowing(checker: &Checker, parameter: &Paramete return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BuiltinArgumentShadowing { name: parameter.name.to_string(), }, parameter.name.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_attribute_shadowing.rs b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_attribute_shadowing.rs index d75b1225f2..678e7ad4e0 100644 --- a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_attribute_shadowing.rs +++ b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_attribute_shadowing.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; @@ -135,14 +134,14 @@ pub(crate) fn builtin_attribute_shadowing( == Some(scope_id) }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BuiltinAttributeShadowing { kind, name: name.to_string(), row: checker.compute_source_row(binding.start()), }, reference.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_import_shadowing.rs b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_import_shadowing.rs index a426615f71..c1ce98c317 100644 --- a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_import_shadowing.rs +++ b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_import_shadowing.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Alias; @@ -63,11 +63,11 @@ pub(crate) fn builtin_import_shadowing(checker: &Checker, alias: &Alias) { &checker.settings.flake8_builtins.ignorelist, checker.target_version(), ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BuiltinImportShadowing { name: name.to_string(), }, name.range, - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_lambda_argument_shadowing.rs b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_lambda_argument_shadowing.rs index ff637cdb2d..20d895047e 100644 --- a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_lambda_argument_shadowing.rs +++ b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_lambda_argument_shadowing.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprLambda; use ruff_text_size::Ranged; @@ -46,12 +46,12 @@ pub(crate) fn builtin_lambda_argument_shadowing(checker: &Checker, lambda: &Expr &checker.settings.flake8_builtins.ignorelist, checker.target_version(), ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BuiltinLambdaArgumentShadowing { name: name.to_string(), }, name.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_variable_shadowing.rs b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_variable_shadowing.rs index 157f8d6a8f..23b622fc47 100644 --- a/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_variable_shadowing.rs +++ b/crates/ruff_linter/src/rules/flake8_builtins/rules/builtin_variable_shadowing.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::TextRange; @@ -74,11 +73,11 @@ pub(crate) fn builtin_variable_shadowing(checker: &Checker, name: &str, range: T &checker.settings.flake8_builtins.ignorelist, checker.target_version(), ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BuiltinVariableShadowing { name: name.to_string(), }, range, - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs index 444732b3fb..716ef5b6fa 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -79,7 +79,7 @@ pub(crate) fn unnecessary_call_around_sorted( if !semantic.match_builtin_expr(inner_func, "sorted") { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryCallAroundSorted { func: unnecessary_function, }, @@ -94,7 +94,6 @@ pub(crate) fn unnecessary_call_around_sorted( }; Ok(Fix::applicable_edit(edit, applicability)) }); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs index f19dd138b3..7c8d5b7386 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::{Ranged, TextSize}; @@ -89,7 +89,7 @@ pub(crate) fn unnecessary_collection_call( }; let mut diagnostic = - Diagnostic::new(UnnecessaryCollectionCall { kind: collection }, call.range()); + checker.report_diagnostic(UnnecessaryCollectionCall { kind: collection }, call.range()); // Convert `dict()` to `{}`. if call.arguments.keywords.is_empty() { @@ -128,8 +128,6 @@ pub(crate) fn unnecessary_collection_call( fixes::fix_unnecessary_collection_call(call, checker).map(Fix::unsafe_edit) }); } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs index 9b90fe5009..01d08a2664 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Comprehension, Expr}; use ruff_python_semantic::analyze::typing; @@ -85,7 +85,7 @@ fn add_diagnostic(checker: &Checker, expr: &Expr) { { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryComprehension { kind: comprehension_kind, }, @@ -95,7 +95,6 @@ fn add_diagnostic(checker: &Checker, expr: &Expr) { fixes::fix_unnecessary_comprehension(expr, checker.locator(), checker.stylist()) .map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } /// C416 diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_in_call.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_in_call.rs index cc9785d331..c503777cb5 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_in_call.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_in_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, FixAvailability}; +use ruff_diagnostics::FixAvailability; use ruff_diagnostics::{Edit, Fix, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; @@ -136,13 +136,13 @@ pub(crate) fn unnecessary_comprehension_in_call( } let mut diagnostic = match (arg, builtin_function.duplication_variance()) { - (Expr::ListComp(_), _) => Diagnostic::new( + (Expr::ListComp(_), _) => checker.report_diagnostic( UnnecessaryComprehensionInCall { comprehension_kind: ComprehensionKind::List, }, arg.range(), ), - (Expr::SetComp(_), DuplicationVariance::Invariant) => Diagnostic::new( + (Expr::SetComp(_), DuplicationVariance::Invariant) => checker.report_diagnostic( UnnecessaryComprehensionInCall { comprehension_kind: ComprehensionKind::Set, }, @@ -175,7 +175,6 @@ pub(crate) fn unnecessary_comprehension_in_call( diagnostic.set_fix(Fix::unsafe_edits(collection_start, [collection_end])); } - checker.report_diagnostic(diagnostic); } /// Return `true` if the [`Expr`] contains an `await` expression. diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_dict_comprehension_for_iterable.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_dict_comprehension_for_iterable.rs index e2662ca130..1705b3b0ec 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_dict_comprehension_for_iterable.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_dict_comprehension_for_iterable.rs @@ -1,5 +1,5 @@ use ast::ExprName; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::any_over_expr; @@ -113,7 +113,7 @@ pub(crate) fn unnecessary_dict_comprehension_for_iterable( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryDictComprehensionForIterable { is_value_none_literal: dict_comp.value.is_none_literal_expr(), }, @@ -131,8 +131,6 @@ pub(crate) fn unnecessary_dict_comprehension_for_iterable( dict_comp.range(), ))); } - - checker.report_diagnostic(diagnostic); } /// Returns `true` if the expression can be shared across multiple values. diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs index 07a9daf118..e8988e6661 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableKeyword; use ruff_python_ast::{self as ast, Arguments, Expr, Keyword}; @@ -125,7 +125,7 @@ pub(crate) fn unnecessary_double_cast_or_process( | ("set", "set") | ("list" | "tuple", "list" | "tuple") ) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryDoubleCastOrProcess { inner: inner_func_name.to_string(), outer: outer_func_name.to_string(), @@ -140,6 +140,5 @@ pub(crate) fn unnecessary_double_cast_or_process( ) .map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs index 644d5123a0..7602cd1e35 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_text_size::Ranged; @@ -70,8 +70,7 @@ pub(crate) fn unnecessary_generator_dict( if tuple.iter().any(Expr::is_starred_expr) { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryGeneratorDict, expr.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryGeneratorDict, expr.range()); diagnostic .try_set_fix(|| fixes::fix_unnecessary_generator_dict(expr, checker).map(Fix::unsafe_edit)); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs index ecf69a07e0..1627d76974 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::ExprGenerator; @@ -94,22 +94,23 @@ pub(crate) fn unnecessary_generator_list(checker: &Checker, call: &ast::ExprCall if let [generator] = generators.as_slice() { if generator.ifs.is_empty() && !generator.is_async { if ComparableExpr::from(elt) == ComparableExpr::from(&generator.target) { - let diagnostic = Diagnostic::new( - UnnecessaryGeneratorList { - short_circuit: true, - }, - call.range(), - ); let iterator = format!("list({})", checker.locator().slice(generator.iter.range())); let fix = Fix::unsafe_edit(Edit::range_replacement(iterator, call.range())); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic( + UnnecessaryGeneratorList { + short_circuit: true, + }, + call.range(), + ) + .set_fix(fix); return; } } } // Convert `list(f(x) for x in y)` to `[f(x) for x in y]`. - let diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryGeneratorList { short_circuit: false, }, @@ -158,5 +159,5 @@ pub(crate) fn unnecessary_generator_list(checker: &Checker, call: &ast::ExprCall Fix::unsafe_edits(call_start, [call_end]) } }; - checker.report_diagnostic(diagnostic.with_fix(fix)); + diagnostic.set_fix(fix); } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs index 1f2227087f..0db3228cbb 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::ExprGenerator; @@ -94,7 +94,7 @@ pub(crate) fn unnecessary_generator_set(checker: &Checker, call: &ast::ExprCall) if let [generator] = generators.as_slice() { if generator.ifs.is_empty() && !generator.is_async { if ComparableExpr::from(elt) == ComparableExpr::from(&generator.target) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryGeneratorSet { short_circuit: true, }, @@ -105,14 +105,13 @@ pub(crate) fn unnecessary_generator_set(checker: &Checker, call: &ast::ExprCall) iterator, call.range(), ))); - checker.report_diagnostic(diagnostic); return; } } } // Convert `set(f(x) for x in y)` to `{f(x) for x in y}`. - let diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryGeneratorSet { short_circuit: false, }, @@ -165,5 +164,5 @@ pub(crate) fn unnecessary_generator_set(checker: &Checker, call: &ast::ExprCall) Fix::unsafe_edits(call_start, [call_end]) } }; - checker.report_diagnostic(diagnostic.with_fix(fix)); + diagnostic.set_fix(fix); } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs index 62a7f5e11b..784105fda7 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Arguments, Expr, ExprCall}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -74,10 +74,9 @@ pub(crate) fn unnecessary_list_call(checker: &Checker, expr: &Expr, call: &ExprC if !checker.semantic().has_builtin_binding("list") { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryListCall, expr.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListCall, expr.range()); diagnostic.try_set_fix(|| { fixes::fix_unnecessary_list_call(expr, checker.locator(), checker.stylist()) .map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs index 6ea0f907a9..eeae7b838c 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_text_size::Ranged; @@ -68,9 +68,8 @@ pub(crate) fn unnecessary_list_comprehension_dict( if !checker.semantic().has_builtin_binding("dict") { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryListComprehensionDict, expr.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListComprehensionDict, expr.range()); diagnostic.try_set_fix(|| { fixes::fix_unnecessary_list_comprehension_dict(expr, checker).map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs index c0f8b29643..b1f1755a1f 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::parenthesize::parenthesized_range; @@ -60,7 +60,7 @@ pub(crate) fn unnecessary_list_comprehension_set(checker: &Checker, call: &ast:: if !argument.is_list_comp_expr() { return; } - let diagnostic = Diagnostic::new(UnnecessaryListComprehensionSet, call.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListComprehensionSet, call.range()); let one = TextSize::from(1); // Replace `set(` with `{`. @@ -100,5 +100,5 @@ pub(crate) fn unnecessary_list_comprehension_set(checker: &Checker, call: &ast:: let replacement = Edit::range_replacement(checker.source()[span].to_string(), replacement_range); let fix = Fix::unsafe_edits(call_start, [call_end, replacement]); - checker.report_diagnostic(diagnostic.with_fix(fix)); + diagnostic.set_fix(fix); } diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs index 111a5f8e5f..235e6e8c19 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Keyword}; use ruff_text_size::Ranged; @@ -78,10 +78,10 @@ pub(crate) fn unnecessary_literal_dict( if !checker.semantic().has_builtin_binding("dict") { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryLiteralDict { obj_type: kind }, expr.range()); + let mut diagnostic = + checker.report_diagnostic(UnnecessaryLiteralDict { obj_type: kind }, expr.range()); diagnostic .try_set_fix(|| fixes::fix_unnecessary_literal_dict(expr, checker).map(Fix::unsafe_edit)); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs index 2f9ee5bc08..f5b0f311b6 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::{Ranged, TextSize}; @@ -67,7 +67,7 @@ pub(crate) fn unnecessary_literal_set(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryLiteralSet { kind }, call.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryLiteralSet { kind }, call.range()); // Convert `set((1, 2))` to `{1, 2}`. diagnostic.set_fix({ @@ -124,8 +124,6 @@ pub(crate) fn unnecessary_literal_set(checker: &Checker, call: &ast::ExprCall) { } } }); - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs index 710e790e34..d80ad19733 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs @@ -2,7 +2,7 @@ use std::fmt; use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -71,7 +71,7 @@ pub(crate) fn unnecessary_literal_within_dict_call(checker: &Checker, call: &ast return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryLiteralWithinDictCall { kind: argument_kind, }, @@ -88,8 +88,6 @@ pub(crate) fn unnecessary_literal_within_dict_call(checker: &Checker, call: &ast Fix::unsafe_edits(call_start, [call_end]) }); - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs index 61df610404..e5b8fcfd3c 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::{Ranged, TextSize}; @@ -82,7 +82,7 @@ pub(crate) fn unnecessary_literal_within_list_call(checker: &Checker, call: &ast return; } - let diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryLiteralWithinListCall { kind: argument_kind, }, @@ -119,7 +119,7 @@ pub(crate) fn unnecessary_literal_within_list_call(checker: &Checker, call: &ast } }; - checker.report_diagnostic(diagnostic.with_fix(fix)); + diagnostic.set_fix(fix); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs index eae745afd9..7dd8231e7c 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; use ruff_python_ast::{self as ast, Expr}; @@ -110,7 +110,7 @@ pub(crate) fn unnecessary_literal_within_tuple_call( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryLiteralWithinTupleCall { literal_kind: argument_kind, }, @@ -165,10 +165,8 @@ pub(crate) fn unnecessary_literal_within_tuple_call( }); } - _ => return, + _ => (), } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_map.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_map.rs index 36b286b86e..bcd0090fca 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_map.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_map.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Fix}; +use ruff_diagnostics::Fix; use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; @@ -138,7 +138,7 @@ pub(crate) fn unnecessary_map(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryMap { object_type }, call.range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryMap { object_type }, call.range); diagnostic.try_set_fix(|| { fixes::fix_unnecessary_map( call, @@ -149,7 +149,6 @@ pub(crate) fn unnecessary_map(checker: &Checker, call: &ast::ExprCall) { ) .map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } fn is_list_set_or_dict(func: &Expr, semantic: &SemanticModel) -> bool { diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs index 2c26077bf4..d2e0d960fa 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, UnaryOp}; use ruff_text_size::Ranged; @@ -86,10 +86,10 @@ pub(crate) fn unnecessary_subscript_reversal(checker: &Checker, call: &ast::Expr if !matches!(function_name, "reversed" | "set" | "sorted") { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnnecessarySubscriptReversal { func: function_name.to_string(), }, call.range(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_fromtimestamp.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_fromtimestamp.rs index 111916a5ee..12ab428186 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_fromtimestamp.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_fromtimestamp.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -73,6 +73,6 @@ pub(crate) fn call_date_fromtimestamp(checker: &Checker, func: &Expr, location: ) }) { - checker.report_diagnostic(Diagnostic::new(CallDateFromtimestamp, location)); + checker.report_diagnostic(CallDateFromtimestamp, location); } } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_today.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_today.rs index 721073076f..b182c840ca 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_today.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_date_today.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -69,6 +69,6 @@ pub(crate) fn call_date_today(checker: &Checker, func: &Expr, location: TextRang matches!(qualified_name.segments(), ["datetime", "date", "today"]) }) { - checker.report_diagnostic(Diagnostic::new(CallDateToday, location)); + checker.report_diagnostic(CallDateToday, location); } } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_fromtimestamp.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_fromtimestamp.rs index 523254619b..6781be630c 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_fromtimestamp.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_fromtimestamp.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; @@ -97,8 +97,5 @@ pub(crate) fn call_datetime_fromtimestamp(checker: &Checker, call: &ast::ExprCal None => DatetimeModuleAntipattern::NoTzArgumentPassed, }; - checker.report_diagnostic(Diagnostic::new( - CallDatetimeFromtimestamp(antipattern), - call.range, - )); + checker.report_diagnostic(CallDatetimeFromtimestamp(antipattern), call.range); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_now_without_tzinfo.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_now_without_tzinfo.rs index cb02443b3e..693f15ddce 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_now_without_tzinfo.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_now_without_tzinfo.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; @@ -92,8 +92,5 @@ pub(crate) fn call_datetime_now_without_tzinfo(checker: &Checker, call: &ast::Ex None => DatetimeModuleAntipattern::NoTzArgumentPassed, }; - checker.report_diagnostic(Diagnostic::new( - CallDatetimeNowWithoutTzinfo(antipattern), - call.range, - )); + checker.report_diagnostic(CallDatetimeNowWithoutTzinfo(antipattern), call.range); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_strptime_without_zone.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_strptime_without_zone.rs index 4c89488b83..43a265e1ee 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_strptime_without_zone.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_strptime_without_zone.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; @@ -139,10 +139,7 @@ pub(crate) fn call_datetime_strptime_without_zone(checker: &Checker, call: &ast: semantic.current_expression_grandparent(), semantic.current_expression_parent(), ) { - checker.report_diagnostic(Diagnostic::new( - CallDatetimeStrptimeWithoutZone(antipattern), - call.range, - )); + checker.report_diagnostic(CallDatetimeStrptimeWithoutZone(antipattern), call.range); } } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_today.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_today.rs index 9ba0332eea..1f22d13087 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_today.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_today.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -75,5 +75,5 @@ pub(crate) fn call_datetime_today(checker: &Checker, func: &Expr, location: Text return; } - checker.report_diagnostic(Diagnostic::new(CallDatetimeToday, location)); + checker.report_diagnostic(CallDatetimeToday, location); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcfromtimestamp.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcfromtimestamp.rs index 4febc8f8f8..272ce7161b 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcfromtimestamp.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcfromtimestamp.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -82,5 +82,5 @@ pub(crate) fn call_datetime_utcfromtimestamp(checker: &Checker, func: &Expr, loc return; } - checker.report_diagnostic(Diagnostic::new(CallDatetimeUtcfromtimestamp, location)); + checker.report_diagnostic(CallDatetimeUtcfromtimestamp, location); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcnow.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcnow.rs index f54452ab6e..8a7068b050 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcnow.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_utcnow.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -82,5 +82,5 @@ pub(crate) fn call_datetime_utcnow(checker: &Checker, func: &Expr, location: Tex return; } - checker.report_diagnostic(Diagnostic::new(CallDatetimeUtcnow, location)); + checker.report_diagnostic(CallDatetimeUtcnow, location); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_without_tzinfo.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_without_tzinfo.rs index 2e46890d53..c59c321918 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_without_tzinfo.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/call_datetime_without_tzinfo.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; @@ -86,8 +86,5 @@ pub(crate) fn call_datetime_without_tzinfo(checker: &Checker, call: &ast::ExprCa None => DatetimeModuleAntipattern::NoTzArgumentPassed, }; - checker.report_diagnostic(Diagnostic::new( - CallDatetimeWithoutTzinfo(antipattern), - call.range, - )); + checker.report_diagnostic(CallDatetimeWithoutTzinfo(antipattern), call.range); } diff --git a/crates/ruff_linter/src/rules/flake8_datetimez/rules/datetime_min_max.rs b/crates/ruff_linter/src/rules/flake8_datetimez/rules/datetime_min_max.rs index 5f6a94ce18..83b9fcb8a1 100644 --- a/crates/ruff_linter/src/rules/flake8_datetimez/rules/datetime_min_max.rs +++ b/crates/ruff_linter/src/rules/flake8_datetimez/rules/datetime_min_max.rs @@ -1,6 +1,6 @@ use std::fmt::{Display, Formatter}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; use ruff_python_semantic::{Modules, SemanticModel}; @@ -74,7 +74,7 @@ pub(crate) fn datetime_min_max(checker: &Checker, expr: &Expr) { return; } - checker.report_diagnostic(Diagnostic::new(DatetimeMinMax { min_max }, expr.range())); + checker.report_diagnostic(DatetimeMinMax { min_max }, expr.range()); } /// Check if the current expression has the pattern `foo.replace(tzinfo=bar)` or `foo.time()`. diff --git a/crates/ruff_linter/src/rules/flake8_debugger/rules/debugger.rs b/crates/ruff_linter/src/rules/flake8_debugger/rules/debugger.rs index 9ac6c79bbb..807cb90981 100644 --- a/crates/ruff_linter/src/rules/flake8_debugger/rules/debugger.rs +++ b/crates/ruff_linter/src/rules/flake8_debugger/rules/debugger.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_text_size::Ranged; @@ -60,36 +60,35 @@ pub(crate) fn debugger_call(checker: &Checker, expr: &Expr, func: &Expr) { } }) { - checker.report_diagnostic(Diagnostic::new(Debugger { using_type }, expr.range())); + checker.report_diagnostic(Debugger { using_type }, expr.range()); } } /// Checks for the presence of a debugger import. -pub(crate) fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option { +pub(crate) fn debugger_import(checker: &Checker, stmt: &Stmt, module: Option<&str>, name: &str) { if let Some(module) = module { let qualified_name = QualifiedName::user_defined(module).append_member(name); if is_debugger_call(&qualified_name) { - return Some(Diagnostic::new( + checker.report_diagnostic( Debugger { using_type: DebuggerUsingType::Import(qualified_name.to_string()), }, stmt.range(), - )); + ); } } else { let qualified_name = QualifiedName::user_defined(name); if is_debugger_import(&qualified_name) { - return Some(Diagnostic::new( + checker.report_diagnostic( Debugger { using_type: DebuggerUsingType::Import(name.to_string()), }, stmt.range(), - )); + ); } } - None } fn is_debugger_call(qualified_name: &QualifiedName) -> bool { diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/all_with_model_form.rs b/crates/ruff_linter/src/rules/flake8_django/rules/all_with_model_form.rs index 794ae075d0..c9ccd941ed 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/all_with_model_form.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/all_with_model_form.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_python_semantic::Modules; @@ -78,19 +78,13 @@ pub(crate) fn all_with_model_form(checker: &Checker, class_def: &ast::StmtClassD match value.as_ref() { Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => { if value == "__all__" { - checker.report_diagnostic(Diagnostic::new( - DjangoAllWithModelForm, - element.range(), - )); + checker.report_diagnostic(DjangoAllWithModelForm, element.range()); return; } } Expr::BytesLiteral(ast::ExprBytesLiteral { value, .. }) => { if value == "__all__".as_bytes() { - checker.report_diagnostic(Diagnostic::new( - DjangoAllWithModelForm, - element.range(), - )); + checker.report_diagnostic(DjangoAllWithModelForm, element.range()); return; } } diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/exclude_with_model_form.rs b/crates/ruff_linter/src/rules/flake8_django/rules/exclude_with_model_form.rs index c92c0fc047..0de9346f4e 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/exclude_with_model_form.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/exclude_with_model_form.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_python_semantic::Modules; @@ -71,10 +71,7 @@ pub(crate) fn exclude_with_model_form(checker: &Checker, class_def: &ast::StmtCl continue; }; if id == "exclude" { - checker.report_diagnostic(Diagnostic::new( - DjangoExcludeWithModelForm, - target.range(), - )); + checker.report_diagnostic(DjangoExcludeWithModelForm, target.range()); return; } } diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/locals_in_render_function.rs b/crates/ruff_linter/src/rules/flake8_django/rules/locals_in_render_function.rs index 9dbf1ae2f7..8328d7d24b 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/locals_in_render_function.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/locals_in_render_function.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::{Modules, SemanticModel}; @@ -61,10 +61,7 @@ pub(crate) fn locals_in_render_function(checker: &Checker, call: &ast::ExprCall) if let Some(argument) = call.arguments.find_argument_value("context", 2) { if is_locals_call(argument, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( - DjangoLocalsInRenderFunction, - argument.range(), - )); + checker.report_diagnostic(DjangoLocalsInRenderFunction, argument.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/model_without_dunder_str.rs b/crates/ruff_linter/src/rules/flake8_django/rules/model_without_dunder_str.rs index 9ea374cca6..acb63289c0 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/model_without_dunder_str.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/model_without_dunder_str.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::identifier::Identifier; @@ -64,10 +64,7 @@ pub(crate) fn model_without_dunder_str(checker: &Checker, class_def: &ast::StmtC return; } - checker.report_diagnostic(Diagnostic::new( - DjangoModelWithoutDunderStr, - class_def.identifier(), - )); + checker.report_diagnostic(DjangoModelWithoutDunderStr, class_def.identifier()); } /// Returns `true` if the class has `__str__` method. diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs b/crates/ruff_linter/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs index 74ef6caf80..a4744674a9 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Decorator; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -70,10 +70,7 @@ pub(crate) fn non_leading_receiver_decorator(checker: &Checker, decorator_list: }) }); if i > 0 && is_receiver && !seen_receiver { - checker.report_diagnostic(Diagnostic::new( - DjangoNonLeadingReceiverDecorator, - decorator.range(), - )); + checker.report_diagnostic(DjangoNonLeadingReceiverDecorator, decorator.range()); } if !is_receiver && seen_receiver { seen_receiver = false; diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/nullable_model_string_field.rs b/crates/ruff_linter/src/rules/flake8_django/rules/nullable_model_string_field.rs index d01f351541..6840d46641 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/nullable_model_string_field.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/nullable_model_string_field.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_semantic::{Modules, SemanticModel}; @@ -64,12 +64,12 @@ pub(crate) fn nullable_model_string_field(checker: &Checker, body: &[Stmt]) { continue; }; if let Some(field_name) = is_nullable_field(value, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( DjangoNullableModelStringField { field_name: field_name.to_string(), }, value.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_django/rules/unordered_body_content_in_model.rs b/crates/ruff_linter/src/rules/flake8_django/rules/unordered_body_content_in_model.rs index fdc0b806b0..85f385be46 100644 --- a/crates/ruff_linter/src/rules/flake8_django/rules/unordered_body_content_in_model.rs +++ b/crates/ruff_linter/src/rules/flake8_django/rules/unordered_body_content_in_model.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_dunder; use ruff_python_ast::{self as ast, Expr, Stmt}; @@ -112,14 +112,13 @@ pub(crate) fn unordered_body_content_in_model(checker: &Checker, class_def: &ast .iter() .find(|&&prev_element_type| prev_element_type > element_type) { - let diagnostic = Diagnostic::new( + checker.report_diagnostic( DjangoUnorderedBodyContentInModel { element_type, prev_element_type, }, element.range(), ); - checker.report_diagnostic(diagnostic); } else { element_types.push(element_type); } 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 8576771406..560fbfd34a 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::whitespace; use ruff_python_ast::{self as ast, Arguments, Expr, Stmt}; @@ -188,7 +188,7 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { if checker.enabled(Rule::RawStringInException) { if string.len() >= checker.settings.flake8_errmsg.max_string_length { let mut diagnostic = - Diagnostic::new(RawStringInException, first.range()); + checker.report_diagnostic(RawStringInException, first.range()); if let Some(indentation) = whitespace::indentation(checker.source(), stmt) { @@ -200,14 +200,14 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { checker.locator(), )); } - checker.report_diagnostic(diagnostic); } } } // Check for f-strings. Expr::FString(_) => { if checker.enabled(Rule::FStringInException) { - let mut diagnostic = Diagnostic::new(FStringInException, first.range()); + let mut diagnostic = + checker.report_diagnostic(FStringInException, first.range()); if let Some(indentation) = whitespace::indentation(checker.source(), stmt) { diagnostic.set_fix(generate_fix( stmt, @@ -217,7 +217,6 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { checker.locator(), )); } - checker.report_diagnostic(diagnostic); } } // Check for .format() calls. @@ -228,7 +227,7 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { { if attr == "format" && value.is_literal_expr() { let mut diagnostic = - Diagnostic::new(DotFormatInException, first.range()); + checker.report_diagnostic(DotFormatInException, first.range()); if let Some(indentation) = whitespace::indentation(checker.source(), stmt) { @@ -240,7 +239,6 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { checker.locator(), )); } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_required_type_annotation.rs b/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_required_type_annotation.rs index 30207f02d7..7475d238fe 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_required_type_annotation.rs +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_required_type_annotation.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::{MemberNameImport, NameImport}; @@ -85,7 +85,8 @@ impl AlwaysFixableViolation for FutureRequiredTypeAnnotation { /// FA102 pub(crate) fn future_required_type_annotation(checker: &Checker, expr: &Expr, reason: Reason) { - let mut diagnostic = Diagnostic::new(FutureRequiredTypeAnnotation { reason }, expr.range()); + let mut diagnostic = + checker.report_diagnostic(FutureRequiredTypeAnnotation { reason }, expr.range()); let required_import = NameImport::ImportFrom(MemberNameImport::member( "__future__".to_string(), "annotations".to_string(), @@ -95,5 +96,4 @@ pub(crate) fn future_required_type_annotation(checker: &Checker, expr: &Expr, re .importer() .add_import(&required_import, TextSize::default()), )); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_rewritable_type_annotation.rs b/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_rewritable_type_annotation.rs index 654ed1acd5..12c67d0f9a 100644 --- a/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_rewritable_type_annotation.rs +++ b/crates/ruff_linter/src/rules/flake8_future_annotations/rules/future_rewritable_type_annotation.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -84,9 +84,6 @@ pub(crate) fn future_rewritable_type_annotation(checker: &Checker, expr: &Expr) .map(|binding| binding.to_string()); if let Some(name) = name { - checker.report_diagnostic(Diagnostic::new( - FutureRewritableTypeAnnotation { name }, - expr.range(), - )); + checker.report_diagnostic(FutureRewritableTypeAnnotation { name }, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_gettext/rules/f_string_in_gettext_func_call.rs b/crates/ruff_linter/src/rules/flake8_gettext/rules/f_string_in_gettext_func_call.rs index f9cbac5cab..d165cbe48b 100644 --- a/crates/ruff_linter/src/rules/flake8_gettext/rules/f_string_in_gettext_func_call.rs +++ b/crates/ruff_linter/src/rules/flake8_gettext/rules/f_string_in_gettext_func_call.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -54,7 +54,7 @@ impl Violation for FStringInGetTextFuncCall { pub(crate) fn f_string_in_gettext_func_call(checker: &Checker, args: &[Expr]) { if let Some(first) = args.first() { if first.is_f_string_expr() { - checker.report_diagnostic(Diagnostic::new(FStringInGetTextFuncCall {}, first.range())); + checker.report_diagnostic(FStringInGetTextFuncCall {}, first.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_gettext/rules/format_in_gettext_func_call.rs b/crates/ruff_linter/src/rules/flake8_gettext/rules/format_in_gettext_func_call.rs index 818d54e027..79e242d036 100644 --- a/crates/ruff_linter/src/rules/flake8_gettext/rules/format_in_gettext_func_call.rs +++ b/crates/ruff_linter/src/rules/flake8_gettext/rules/format_in_gettext_func_call.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -56,10 +56,7 @@ pub(crate) fn format_in_gettext_func_call(checker: &Checker, args: &[Expr]) { if let Expr::Call(ast::ExprCall { func, .. }) = &first { if let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() { if attr == "format" { - checker.report_diagnostic(Diagnostic::new( - FormatInGetTextFuncCall {}, - first.range(), - )); + checker.report_diagnostic(FormatInGetTextFuncCall {}, first.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_gettext/rules/printf_in_gettext_func_call.rs b/crates/ruff_linter/src/rules/flake8_gettext/rules/printf_in_gettext_func_call.rs index 993f9a7cbe..668ae71e2e 100644 --- a/crates/ruff_linter/src/rules/flake8_gettext/rules/printf_in_gettext_func_call.rs +++ b/crates/ruff_linter/src/rules/flake8_gettext/rules/printf_in_gettext_func_call.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr, Operator}; use crate::checkers::ast::Checker; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -60,8 +60,7 @@ pub(crate) fn printf_in_gettext_func_call(checker: &Checker, args: &[Expr]) { }) = &first { if left.is_string_literal_expr() { - checker - .report_diagnostic(Diagnostic::new(PrintfInGetTextFuncCall {}, first.range())); + checker.report_diagnostic(PrintfInGetTextFuncCall {}, first.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/rules/explicit.rs b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/rules/explicit.rs index 5af474d665..173c05b8a9 100644 --- a/crates/ruff_linter/src/rules/flake8_implicit_str_concat/rules/explicit.rs +++ b/crates/ruff_linter/src/rules/flake8_implicit_str_concat/rules/explicit.rs @@ -1,5 +1,5 @@ use ruff_diagnostics::AlwaysFixableViolation; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Operator}; use ruff_python_trivia::is_python_whitespace; @@ -47,13 +47,13 @@ impl AlwaysFixableViolation for ExplicitStringConcatenation { } /// ISC003 -pub(crate) fn explicit(expr: &Expr, checker: &Checker) -> Option { +pub(crate) fn explicit(checker: &Checker, expr: &Expr) { // If the user sets `allow-multiline` to `false`, then we should allow explicitly concatenated // strings that span multiple lines even if this rule is enabled. Otherwise, there's no way // for the user to write multiline strings, and that setting is "more explicit" than this rule // being enabled. if !checker.settings.flake8_implicit_str_concat.allow_multiline { - return None; + return; } if let Expr::BinOp(bin_op) = expr { @@ -76,13 +76,12 @@ pub(crate) fn explicit(expr: &Expr, checker: &Checker) -> Option { .locator() .contains_line_break(TextRange::new(left.end(), right.start())) { - let mut diagnostic = Diagnostic::new(ExplicitStringConcatenation, expr.range()); - diagnostic.set_fix(generate_fix(checker, bin_op)); - return Some(diagnostic); + checker + .report_diagnostic(ExplicitStringConcatenation, expr.range()) + .set_fix(generate_fix(checker, bin_op)); } } } - None } fn generate_fix(checker: &Checker, expr_bin_op: &ast::ExprBinOp) -> Fix { diff --git a/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_alias.rs b/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_alias.rs index d0a9039a14..412fd2fba1 100644 --- a/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_alias.rs +++ b/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_alias.rs @@ -1,10 +1,11 @@ use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; use crate::rules::flake8_import_conventions::settings::BannedAliases; /// ## What it does @@ -48,24 +49,24 @@ impl Violation for BannedImportAlias { /// ICN002 pub(crate) fn banned_import_alias( + checker: &Checker, stmt: &Stmt, name: &str, asname: &str, banned_conventions: &FxHashMap, -) -> Option { +) { if let Some(banned_aliases) = banned_conventions.get(name) { if banned_aliases .iter() .any(|banned_alias| banned_alias == asname) { - return Some(Diagnostic::new( + checker.report_diagnostic( BannedImportAlias { name: name.to_string(), asname: asname.to_string(), }, stmt.range(), - )); + ); } } - None } diff --git a/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_from.rs b/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_from.rs index afbfc8df49..da96e127cd 100644 --- a/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_from.rs +++ b/crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_from.rs @@ -1,10 +1,12 @@ use ruff_python_ast::Stmt; use rustc_hash::FxHashSet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for member imports that should instead be accessed by importing the /// module. @@ -46,17 +48,17 @@ impl Violation for BannedImportFrom { /// ICN003 pub(crate) fn banned_import_from( + checker: &Checker, stmt: &Stmt, name: &str, banned_conventions: &FxHashSet, -) -> Option { +) { if banned_conventions.contains(name) { - return Some(Diagnostic::new( + checker.report_diagnostic( BannedImportFrom { name: name.to_string(), }, stmt.range(), - )); + ); } - None } diff --git a/crates/ruff_linter/src/rules/flake8_import_conventions/rules/unconventional_import_alias.rs b/crates/ruff_linter/src/rules/flake8_import_conventions/rules/unconventional_import_alias.rs index 815582df8f..ccf58de5f3 100644 --- a/crates/ruff_linter/src/rules/flake8_import_conventions/rules/unconventional_import_alias.rs +++ b/crates/ruff_linter/src/rules/flake8_import_conventions/rules/unconventional_import_alias.rs @@ -1,6 +1,6 @@ use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Binding, Imported}; use ruff_text_size::Ranged; @@ -60,17 +60,21 @@ pub(crate) fn unconventional_import_alias( checker: &Checker, binding: &Binding, conventions: &FxHashMap, -) -> Option { - let import = binding.as_any_import()?; +) { + let Some(import) = binding.as_any_import() else { + return; + }; let qualified_name = import.qualified_name().to_string(); - let expected_alias = conventions.get(qualified_name.as_str())?; + let Some(expected_alias) = conventions.get(qualified_name.as_str()) else { + return; + }; let name = binding.name(checker.source()); if name == expected_alias { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnconventionalImportAlias { name: qualified_name, asname: expected_alias.to_string(), @@ -92,5 +96,4 @@ pub(crate) fn unconventional_import_alias( }); } } - Some(diagnostic) } diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/direct_logger_instantiation.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/direct_logger_instantiation.rs index 83dae3049c..d372a8aab8 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/direct_logger_instantiation.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/direct_logger_instantiation.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; @@ -64,7 +64,8 @@ pub(crate) fn direct_logger_instantiation(checker: &Checker, call: &ast::ExprCal .resolve_qualified_name(call.func.as_ref()) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["logging", "Logger"])) { - let mut diagnostic = Diagnostic::new(DirectLoggerInstantiation, call.func.range()); + let mut diagnostic = + checker.report_diagnostic(DirectLoggerInstantiation, call.func.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("logging", "getLogger"), @@ -74,6 +75,5 @@ pub(crate) fn direct_logger_instantiation(checker: &Checker, call: &ast::ExprCal let reference_edit = Edit::range_replacement(binding, call.func.range()); Ok(Fix::unsafe_edits(import_edit, [reference_edit])) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/exc_info_outside_except_handler.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/exc_info_outside_except_handler.rs index ec74ffdc48..b016bc0ca9 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/exc_info_outside_except_handler.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/exc_info_outside_except_handler.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::Truthiness; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; @@ -107,12 +107,10 @@ pub(crate) fn exc_info_outside_except_handler(checker: &Checker, call: &ExprCall let arguments = &call.arguments; let source = checker.source(); - let mut diagnostic = Diagnostic::new(ExcInfoOutsideExceptHandler, exc_info.range); + let mut diagnostic = checker.report_diagnostic(ExcInfoOutsideExceptHandler, exc_info.range); diagnostic.try_set_fix(|| { let edit = remove_argument(exc_info, arguments, Parentheses::Preserve, source)?; Ok(Fix::unsafe_edit(edit)) }); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/exception_without_exc_info.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/exception_without_exc_info.rs index f8c36980d2..8329823b46 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/exception_without_exc_info.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/exception_without_exc_info.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::Truthiness; use ruff_python_ast::{self as ast, Expr, ExprCall}; @@ -74,7 +74,7 @@ pub(crate) fn exception_without_exc_info(checker: &Checker, call: &ExprCall) { } if exc_info_arg_is_falsey(call, checker) { - checker.report_diagnostic(Diagnostic::new(ExceptionWithoutExcInfo, call.range())); + checker.report_diagnostic(ExceptionWithoutExcInfo, call.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/invalid_get_logger_argument.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/invalid_get_logger_argument.rs index f2a30ee900..68c5144a27 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/invalid_get_logger_argument.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/invalid_get_logger_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; @@ -84,12 +84,11 @@ pub(crate) fn invalid_get_logger_argument(checker: &Checker, call: &ast::ExprCal return; } - let mut diagnostic = Diagnostic::new(InvalidGetLoggerArgument, expr.range()); + let mut diagnostic = checker.report_diagnostic(InvalidGetLoggerArgument, expr.range()); if checker.semantic().has_builtin_binding("__name__") { diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( "__name__".to_string(), expr.range(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/log_exception_outside_except_handler.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/log_exception_outside_except_handler.rs index 5122f9cb00..d92a88ff93 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/log_exception_outside_except_handler.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/log_exception_outside_except_handler.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; use ruff_python_semantic::analyze::logging; @@ -99,11 +99,9 @@ pub(crate) fn log_exception_outside_except_handler(checker: &Checker, call: &Exp _ => return, }; - let mut diagnostic = Diagnostic::new(LogExceptionOutsideExceptHandler, call.range); + let mut diagnostic = checker.report_diagnostic(LogExceptionOutsideExceptHandler, call.range); if let Some(fix) = fix { diagnostic.set_fix(fix); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/root_logger_call.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/root_logger_call.rs index 167eab4b3a..a98850d7f7 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/root_logger_call.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/root_logger_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprCall; use ruff_python_semantic::Modules; @@ -63,9 +63,7 @@ pub(crate) fn root_logger_call(checker: &Checker, call: &ExprCall) { let kind = RootLoggerCall { attr: (*attr).to_string(), }; - let diagnostic = Diagnostic::new(kind, call.range); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(kind, call.range); } #[inline] diff --git a/crates/ruff_linter/src/rules/flake8_logging/rules/undocumented_warn.rs b/crates/ruff_linter/src/rules/flake8_logging/rules/undocumented_warn.rs index 8ed90df6d0..a71f372d65 100644 --- a/crates/ruff_linter/src/rules/flake8_logging/rules/undocumented_warn.rs +++ b/crates/ruff_linter/src/rules/flake8_logging/rules/undocumented_warn.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -59,7 +59,7 @@ pub(crate) fn undocumented_warn(checker: &Checker, expr: &Expr) { .resolve_qualified_name(expr) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["logging", "WARN"])) { - let mut diagnostic = Diagnostic::new(UndocumentedWarn, expr.range()); + let mut diagnostic = checker.report_diagnostic(UndocumentedWarn, expr.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("logging", "WARNING"), @@ -69,6 +69,5 @@ pub(crate) fn undocumented_warn(checker: &Checker, expr: &Expr) { let reference_edit = Edit::range_replacement(binding, expr.range()); Ok(Fix::safe_edits(import_edit, [reference_edit])) }); - checker.report_diagnostic(diagnostic); } } 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 a053b4514f..7780b72dc7 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_python_ast::{self as ast, Arguments, Expr, Keyword, Operator}; use ruff_python_semantic::analyze::logging; use ruff_python_stdlib::logging::LoggingLevel; @@ -48,12 +48,12 @@ fn check_msg(checker: &Checker, msg: &Expr) { Expr::BinOp(ast::ExprBinOp { op, .. }) => match op { Operator::Add => { if checker.enabled(Rule::LoggingStringConcat) { - checker.report_diagnostic(Diagnostic::new(LoggingStringConcat, msg.range())); + checker.report_diagnostic(LoggingStringConcat, msg.range()); } } Operator::Mod => { if checker.enabled(Rule::LoggingPercentFormat) { - checker.report_diagnostic(Diagnostic::new(LoggingPercentFormat, msg.range())); + checker.report_diagnostic(LoggingPercentFormat, msg.range()); } } _ => {} @@ -61,7 +61,7 @@ fn check_msg(checker: &Checker, msg: &Expr) { // Check for f-strings. Expr::FString(_) => { if checker.enabled(Rule::LoggingFString) { - checker.report_diagnostic(Diagnostic::new(LoggingFString, msg.range())); + checker.report_diagnostic(LoggingFString, msg.range()); } } // Check for .format() calls. @@ -69,8 +69,7 @@ fn check_msg(checker: &Checker, msg: &Expr) { if checker.enabled(Rule::LoggingStringFormat) { if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() { if attr == "format" && value.is_literal_expr() { - checker - .report_diagnostic(Diagnostic::new(LoggingStringFormat, msg.range())); + checker.report_diagnostic(LoggingStringFormat, msg.range()); } } } @@ -91,10 +90,10 @@ fn check_log_record_attr_clash(checker: &Checker, extra: &Keyword) { None } }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( LoggingExtraAttrClash(invalid_key.value.to_string()), invalid_key.range(), - )); + ); } } Expr::Call(ast::ExprCall { @@ -106,10 +105,10 @@ fn check_log_record_attr_clash(checker: &Checker, extra: &Keyword) { for keyword in keywords { if let Some(attr) = &keyword.arg { if is_reserved_attr(attr) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( LoggingExtraAttrClash(attr.to_string()), keyword.range(), - )); + ); } } } @@ -184,12 +183,11 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { logging_call_type, LoggingCallType::LevelCall(LoggingLevel::Warn) ) { - let mut diagnostic = Diagnostic::new(LoggingWarn, range); + let mut diagnostic = checker.report_diagnostic(LoggingWarn, range); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "warning".to_string(), range, ))); - checker.report_diagnostic(diagnostic); } } @@ -212,15 +210,12 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { match logging_level { LoggingLevel::Error => { if checker.enabled(Rule::LoggingExcInfo) { - checker.report_diagnostic(Diagnostic::new(LoggingExcInfo, range)); + checker.report_diagnostic(LoggingExcInfo, range); } } LoggingLevel::Exception => { if checker.enabled(Rule::LoggingRedundantExcInfo) { - checker.report_diagnostic(Diagnostic::new( - LoggingRedundantExcInfo, - exc_info.range(), - )); + checker.report_diagnostic(LoggingRedundantExcInfo, exc_info.range()); } } _ => {} diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/duplicate_class_field_definition.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/duplicate_class_field_definition.rs index 5474c528fd..c1dc478341 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/duplicate_class_field_definition.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/duplicate_class_field_definition.rs @@ -1,6 +1,5 @@ use rustc_hash::FxHashSet; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; @@ -94,7 +93,7 @@ pub(crate) fn duplicate_class_field_definition(checker: &Checker, body: &[Stmt]) } if !seen_targets.insert(target.id.as_str()) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DuplicateClassFieldDefinition { name: target.id.to_string(), }, @@ -105,7 +104,6 @@ pub(crate) fn duplicate_class_field_definition(checker: &Checker, body: &[Stmt]) diagnostic.set_fix(Fix::unsafe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_id(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/multiple_starts_ends_with.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/multiple_starts_ends_with.rs index 62c75c9c18..a15ff26141 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/multiple_starts_ends_with.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/multiple_starts_ends_with.rs @@ -9,7 +9,7 @@ use ruff_text_size::{Ranged, TextRange}; use ruff_python_ast::{self as ast, Arguments, BoolOp, Expr, ExprContext, Identifier}; use ruff_diagnostics::AlwaysFixableViolation; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -128,7 +128,7 @@ pub(crate) fn multiple_starts_ends_with(checker: &Checker, expr: &Expr) { // Generate a `Diagnostic` for each duplicate. for ((attr_name, arg_name), indices) in duplicates { if indices.len() > 1 { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MultipleStartsEndsWith { attr: attr_name.to_string(), }, @@ -219,7 +219,6 @@ pub(crate) fn multiple_starts_ends_with(checker: &Checker, expr: &Expr) { checker.generator().expr(&bool_op), expr.range(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/non_unique_enums.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/non_unique_enums.rs index d54919bc3c..4426008298 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/non_unique_enums.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/non_unique_enums.rs @@ -1,7 +1,6 @@ use ruff_python_semantic::SemanticModel; use rustc_hash::FxHashSet; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; @@ -91,13 +90,12 @@ pub(crate) fn non_unique_enums(checker: &Checker, parent: &Stmt, body: &[Stmt]) let comparable = ComparableExpr::from(value); if !seen_targets.insert(comparable) { - let diagnostic = Diagnostic::new( + checker.report_diagnostic( NonUniqueEnums { value: checker.generator().expr(value), }, stmt.range(), ); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/reimplemented_container_builtin.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/reimplemented_container_builtin.rs index 0f99c813e8..e78083888e 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/reimplemented_container_builtin.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/reimplemented_container_builtin.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, ExprLambda}; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -74,7 +74,8 @@ pub(crate) fn reimplemented_container_builtin(checker: &Checker, expr: &ExprLamb Expr::Dict(dict) if dict.is_empty() => Container::Dict, _ => return, }; - let mut diagnostic = Diagnostic::new(ReimplementedContainerBuiltin { container }, expr.range()); + let mut diagnostic = + checker.report_diagnostic(ReimplementedContainerBuiltin { container }, expr.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol( container.as_str(), @@ -84,7 +85,6 @@ pub(crate) fn reimplemented_container_builtin(checker: &Checker, expr: &ExprLamb let binding_edit = Edit::range_replacement(binding, expr.range()); Ok(Fix::safe_edits(binding_edit, import_edit)) }); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_dict_kwargs.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_dict_kwargs.rs index d8bba791e0..6164c549ed 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_dict_kwargs.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_dict_kwargs.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use rustc_hash::{FxBuildHasher, FxHashSet}; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{self as ast, Expr}; @@ -92,12 +92,13 @@ pub(crate) fn unnecessary_dict_kwargs(checker: &Checker, call: &ast::ExprCall) { // Ex) `foo(**{**bar})` if let [ast::DictItem { key: None, value }] = dict.items.as_slice() { - let diagnostic = Diagnostic::new(UnnecessaryDictKwargs, keyword.range()); let edit = Edit::range_replacement( format!("**{}", checker.locator().slice(value)), keyword.range(), ); - checker.report_diagnostic(diagnostic.with_fix(Fix::safe_edit(edit))); + checker + .report_diagnostic(UnnecessaryDictKwargs, keyword.range()) + .set_fix(Fix::safe_edit(edit)); continue; } @@ -111,7 +112,7 @@ pub(crate) fn unnecessary_dict_kwargs(checker: &Checker, call: &ast::ExprCall) { continue; } - let mut diagnostic = Diagnostic::new(UnnecessaryDictKwargs, keyword.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryDictKwargs, keyword.range()); if dict.is_empty() { diagnostic.try_set_fix(|| { @@ -168,8 +169,6 @@ pub(crate) fn unnecessary_dict_kwargs(checker: &Checker, call: &ast::ExprCall) { } } } - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_placeholder.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_placeholder.rs index e704243b35..8e2dbd34fd 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_placeholder.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_placeholder.rs @@ -1,5 +1,5 @@ use ruff_diagnostics::{AlwaysFixableViolation, Applicability}; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::whitespace::trailing_comment_start_offset; @@ -138,14 +138,14 @@ fn add_diagnostic( let isolation_level = Checker::isolation(checker.semantic().current_statement_id()); let fix = Fix::applicable_edit(edit, applicability).isolate(isolation_level); - let diagnostic = Diagnostic::new( - UnnecessaryPlaceholder { - kind: placeholder_kind, - }, - stmt.range(), - ); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic( + UnnecessaryPlaceholder { + kind: placeholder_kind, + }, + stmt.range(), + ) + .set_fix(fix); } #[derive(Debug, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_range_start.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_range_start.rs index b046df61d0..3540b534f9 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_range_start.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_range_start.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; @@ -70,7 +69,7 @@ pub(crate) fn unnecessary_range_start(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryRangeStart, start.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryRangeStart, start.range()); diagnostic.try_set_fix(|| { remove_argument( &start, @@ -80,5 +79,4 @@ pub(crate) fn unnecessary_range_start(checker: &Checker, call: &ast::ExprCall) { ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_spread.rs b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_spread.rs index e1d3eed5b9..353b83bf14 100644 --- a/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_spread.rs +++ b/crates/ruff_linter/src/rules/flake8_pie/rules/unnecessary_spread.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_parser::{TokenKind, Tokens}; @@ -52,11 +52,10 @@ pub(crate) fn unnecessary_spread(checker: &Checker, dict: &ast::ExprDict) { // We only care about when the key is None which indicates a spread `**` // inside a dict. if let Expr::Dict(inner) = value { - let mut diagnostic = Diagnostic::new(UnnecessarySpread, value.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessarySpread, value.range()); if let Some(fix) = unnecessary_spread_fix(inner, prev_end, checker.tokens()) { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } } prev_end = value.end(); diff --git a/crates/ruff_linter/src/rules/flake8_print/rules/print_call.rs b/crates/ruff_linter/src/rules/flake8_print/rules/print_call.rs index 41e4cde22e..ed7f4ce866 100644 --- a/crates/ruff_linter/src/rules/flake8_print/rules/print_call.rs +++ b/crates/ruff_linter/src/rules/flake8_print/rules/print_call.rs @@ -1,11 +1,10 @@ -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits::delete_stmt; -use crate::registry::AsRule; /// ## What it does /// Checks for `print` statements. @@ -121,7 +120,7 @@ pub(crate) fn print_call(checker: &Checker, call: &ast::ExprCall) { return; }; - let mut diagnostic = match qualified_name.segments() { + let diagnostic = match qualified_name.segments() { ["" | "builtins", "print"] => { // If the print call has a `file=` argument (that isn't `None`, `"sys.stdout"`, // or `"sys.stderr"`), don't trigger T201. @@ -136,15 +135,15 @@ pub(crate) fn print_call(checker: &Checker, call: &ast::ExprCall) { } } } - Diagnostic::new(Print, call.func.range()) + checker.report_diagnostic_if_enabled(Print, call.func.range()) } - ["pprint", "pprint"] => Diagnostic::new(PPrint, call.func.range()), + ["pprint", "pprint"] => checker.report_diagnostic_if_enabled(PPrint, call.func.range()), _ => return, }; - if !checker.enabled(diagnostic.rule()) { + let Some(mut diagnostic) = diagnostic else { return; - } + }; // Remove the `print`, if it's a standalone statement. if semantic.current_expression_parent().is_none() { @@ -156,6 +155,4 @@ pub(crate) fn print_call(checker: &Checker, call: &ast::ExprCall) { .isolate(Checker::isolation(semantic.current_statement_parent_id())), ); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/any_eq_ne_annotation.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/any_eq_ne_annotation.rs index 6532298198..db61dcff95 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/any_eq_ne_annotation.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/any_eq_ne_annotation.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Parameters; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -84,7 +84,7 @@ pub(crate) fn any_eq_ne_annotation(checker: &Checker, name: &str, parameters: &P return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( AnyEqNeAnnotation { method_name: name.to_string(), }, @@ -100,5 +100,4 @@ pub(crate) fn any_eq_ne_annotation(checker: &Checker, name: &str, parameters: &P let binding_edit = Edit::range_replacement(binding, annotation.range()); Ok(Fix::safe_edits(binding_edit, import_edit)) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_generator_return_type.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_generator_return_type.rs index d3fbb436bf..b6033ebab1 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_generator_return_type.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_generator_return_type.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::helpers::map_subscript; @@ -210,7 +210,7 @@ pub(crate) fn bad_generator_return_type(function_def: &ast::StmtFunctionDef, che } } } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( GeneratorReturnFromIterMethod { return_type: member.to_iter(), method, @@ -228,8 +228,6 @@ pub(crate) fn bad_generator_return_type(function_def: &ast::StmtFunctionDef, che checker, ) }); - - checker.report_diagnostic(diagnostic); } /// Returns `true` if the [`ast::Expr`] is a `None` literal or a `typing.Any` expression. 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 1feef776c2..4d4a21d84f 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 @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, CmpOp, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -144,12 +144,12 @@ pub(crate) fn bad_version_info_comparison(checker: &Checker, test: &Expr, has_el && (checker.source_type.is_stub() || is_bad_version_info_in_non_stub_enabled(checker.settings)) { if has_else_clause { - checker.report_diagnostic(Diagnostic::new(BadVersionInfoOrder, test.range())); + checker.report_diagnostic(BadVersionInfoOrder, test.range()); } } } else { if checker.enabled(Rule::BadVersionInfoComparison) { - checker.report_diagnostic(Diagnostic::new(BadVersionInfoComparison, test.range())); + checker.report_diagnostic(BadVersionInfoComparison, test.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/bytestring_usage.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/bytestring_usage.rs index 7b8ff0ce6d..3267c08e5e 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/bytestring_usage.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/bytestring_usage.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, FixAvailability, Violation}; +use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; @@ -74,10 +74,7 @@ pub(crate) fn bytestring_attribute(checker: &Checker, attribute: &Expr) { ["collections", "abc", "ByteString"] => ByteStringOrigin::CollectionsAbc, _ => return, }; - checker.report_diagnostic(Diagnostic::new( - ByteStringUsage { origin }, - attribute.range(), - )); + checker.report_diagnostic(ByteStringUsage { origin }, attribute.range()); } /// PYI057 @@ -97,7 +94,7 @@ pub(crate) fn bytestring_import(checker: &Checker, import_from: &ast::StmtImport for name in names { if name.name.as_str() == "ByteString" { - checker.report_diagnostic(Diagnostic::new(ByteStringUsage { origin }, name.range())); + checker.report_diagnostic(ByteStringUsage { origin }, name.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/collections_named_tuple.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/collections_named_tuple.rs index 9e01fb1420..ea122dfdaa 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/collections_named_tuple.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/collections_named_tuple.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -62,6 +62,6 @@ pub(crate) fn collections_named_tuple(checker: &Checker, expr: &Expr) { matches!(qualified_name.segments(), ["collections", "namedtuple"]) }) { - checker.report_diagnostic(Diagnostic::new(CollectionsNamedTuple, expr.range())); + checker.report_diagnostic(CollectionsNamedTuple, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_assignment_in_stub.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_assignment_in_stub.rs index 08d7b95f76..dda0042d59 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_assignment_in_stub.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_assignment_in_stub.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, StmtAssign}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -56,5 +56,5 @@ pub(crate) fn complex_assignment_in_stub(checker: &Checker, stmt: &StmtAssign) { if matches!(stmt.targets.as_slice(), [Expr::Name(_)]) { return; } - checker.report_diagnostic(Diagnostic::new(ComplexAssignmentInStub, stmt.range)); + checker.report_diagnostic(ComplexAssignmentInStub, stmt.range); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_if_statement_in_stub.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_if_statement_in_stub.rs index c600137143..a2525a8dfc 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_if_statement_in_stub.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/complex_if_statement_in_stub.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -48,12 +48,12 @@ pub(crate) fn complex_if_statement_in_stub(checker: &Checker, test: &Expr) { left, comparators, .. }) = test else { - checker.report_diagnostic(Diagnostic::new(ComplexIfStatementInStub, test.range())); + checker.report_diagnostic(ComplexIfStatementInStub, test.range()); return; }; if comparators.len() != 1 { - checker.report_diagnostic(Diagnostic::new(ComplexIfStatementInStub, test.range())); + checker.report_diagnostic(ComplexIfStatementInStub, test.range()); return; } @@ -74,5 +74,5 @@ pub(crate) fn complex_if_statement_in_stub(checker: &Checker, test: &Expr) { return; } - checker.report_diagnostic(Diagnostic::new(ComplexIfStatementInStub, test.range())); + checker.report_diagnostic(ComplexIfStatementInStub, test.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs index c3655eebda..24e39f267a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs @@ -1,7 +1,7 @@ use anyhow::{Context, bail}; use itertools::Itertools; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::analyze::class::is_metaclass; @@ -112,14 +112,18 @@ impl Violation for CustomTypeVarForSelf { } /// PYI019 -pub(crate) fn custom_type_var_instead_of_self( - checker: &Checker, - binding: &Binding, -) -> Option { +pub(crate) fn custom_type_var_instead_of_self(checker: &Checker, binding: &Binding) { let semantic = checker.semantic(); let current_scope = &semantic.scopes[binding.scope]; - let function_def = binding.statement(semantic)?.as_function_def_stmt()?; - let importer = checker.typing_importer("Self", PythonVersion::PY311)?; + let Some(function_def) = binding + .statement(semantic) + .and_then(|stmt| stmt.as_function_def_stmt()) + else { + return; + }; + let Some(importer) = checker.typing_importer("Self", PythonVersion::PY311) else { + return; + }; let ast::StmtFunctionDef { name: function_name, @@ -133,14 +137,17 @@ pub(crate) fn custom_type_var_instead_of_self( let type_params = type_params.as_deref(); // Given, e.g., `def foo(self: _S, arg: bytes)`, extract `_S`. - let self_or_cls_parameter = parameters - .posonlyargs - .iter() - .chain(¶meters.args) - .next()?; + let Some(self_or_cls_parameter) = parameters.posonlyargs.iter().chain(¶meters.args).next() + else { + return; + }; - let self_or_cls_annotation = self_or_cls_parameter.annotation()?; - let parent_class = current_scope.kind.as_class()?; + let Some(self_or_cls_annotation) = self_or_cls_parameter.annotation() else { + return; + }; + let Some(parent_class) = current_scope.kind.as_class() else { + return; + }; // Skip any abstract/static/overloaded methods, // and any methods in metaclasses @@ -148,7 +155,7 @@ pub(crate) fn custom_type_var_instead_of_self( || is_overload(decorator_list, semantic) || is_metaclass(parent_class, semantic).is_yes() { - return None; + return; } let function_kind = function_type::classify( @@ -169,17 +176,19 @@ pub(crate) fn custom_type_var_instead_of_self( self_annotation: self_or_cls_annotation, type_params, }), - FunctionType::Function | FunctionType::StaticMethod => return None, + FunctionType::Function | FunctionType::StaticMethod => return, }; - let custom_typevar = method.custom_typevar(semantic, binding.scope)?; + let Some(custom_typevar) = method.custom_typevar(semantic, binding.scope) else { + return; + }; let function_header_end = returns .as_deref() .map(Ranged::end) .unwrap_or_else(|| parameters.end()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CustomTypeVarForSelf { typevar_name: custom_typevar.name(checker.source()).to_string(), }, @@ -196,8 +205,6 @@ pub(crate) fn custom_type_var_instead_of_self( self_or_cls_annotation, ) }); - - Some(diagnostic) } #[derive(Debug)] diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/docstring_in_stubs.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/docstring_in_stubs.rs index 140df88d42..f74b7046e7 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/docstring_in_stubs.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/docstring_in_stubs.rs @@ -1,6 +1,6 @@ use ruff_python_ast::ExprStringLiteral; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -63,8 +63,6 @@ pub(crate) fn docstring_in_stubs( Edit::range_deletion(docstring_range) }; - let fix = Fix::unsafe_edit(edit); - let diagnostic = Diagnostic::new(DocstringInStub, docstring_range).with_fix(fix); - - checker.report_diagnostic(diagnostic); + let mut diagnostic = checker.report_diagnostic(DocstringInStub, docstring_range); + diagnostic.set_fix(Fix::unsafe_edit(edit)); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_literal_member.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_literal_member.rs index e2f831d0a1..6a8cdc0a21 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_literal_member.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_literal_member.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use rustc_hash::FxHashSet; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::{self as ast, Expr, ExprContext}; @@ -55,7 +55,7 @@ impl AlwaysFixableViolation for DuplicateLiteralMember { pub(crate) fn duplicate_literal_member<'a>(checker: &Checker, expr: &'a Expr) { let mut seen_nodes: HashSet, _> = FxHashSet::default(); let mut unique_nodes: Vec<&Expr> = Vec::new(); - let mut diagnostics: Vec = Vec::new(); + let mut diagnostics = Vec::new(); // Adds a member to `literal_exprs` if it is a `Literal` annotation let mut check_for_duplicate_members = |expr: &'a Expr, _: &'a Expr| { @@ -63,7 +63,7 @@ pub(crate) fn duplicate_literal_member<'a>(checker: &Checker, expr: &'a Expr) { if seen_nodes.insert(expr.into()) { unique_nodes.push(expr); } else { - diagnostics.push(Diagnostic::new( + diagnostics.push(checker.report_diagnostic( DuplicateLiteralMember { duplicate_name: checker.generator().expr(expr), }, @@ -108,8 +108,4 @@ pub(crate) fn duplicate_literal_member<'a>(checker: &Checker, expr: &'a Expr) { diagnostic.set_fix(fix.clone()); } } - - for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); - } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_union_member.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_union_member.rs index 6ed4436c44..81eb281244 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_union_member.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/duplicate_union_member.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use rustc_hash::FxHashSet; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::{Expr, ExprBinOp, Operator, PythonVersion}; @@ -62,7 +62,7 @@ impl Violation for DuplicateUnionMember { pub(crate) fn duplicate_union_member<'a>(checker: &Checker, expr: &'a Expr) { let mut seen_nodes: HashSet, _> = FxHashSet::default(); let mut unique_nodes: Vec<&Expr> = Vec::new(); - let mut diagnostics: Vec = Vec::new(); + let mut diagnostics = Vec::new(); let mut union_type = UnionKind::TypingUnion; // Adds a member to `literal_exprs` if it is a `Literal` annotation @@ -75,7 +75,7 @@ pub(crate) fn duplicate_union_member<'a>(checker: &Checker, expr: &'a Expr) { if seen_nodes.insert(expr.into()) { unique_nodes.push(expr); } else { - diagnostics.push(Diagnostic::new( + diagnostics.push(checker.report_diagnostic( DuplicateUnionMember { duplicate_name: checker.generator().expr(expr), }, @@ -137,11 +137,6 @@ pub(crate) fn duplicate_union_member<'a>(checker: &Checker, expr: &'a Expr) { diagnostic.set_fix(fix.clone()); } } - - // Add all diagnostics to the checker - for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); - } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/ellipsis_in_non_empty_class_body.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/ellipsis_in_non_empty_class_body.rs index b358ad8018..028ab7c5a6 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/ellipsis_in_non_empty_class_body.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/ellipsis_in_non_empty_class_body.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Stmt, StmtExpr}; use ruff_text_size::Ranged; @@ -55,13 +55,13 @@ pub(crate) fn ellipsis_in_non_empty_class_body(checker: &Checker, body: &[Stmt]) }; if value.is_ellipsis_literal_expr() { - let mut diagnostic = Diagnostic::new(EllipsisInNonEmptyClassBody, stmt.range()); + let mut diagnostic = + checker.report_diagnostic(EllipsisInNonEmptyClassBody, stmt.range()); let edit = fix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer()); diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_id(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/exit_annotations.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/exit_annotations.rs index 1829f4930b..bb1f636bbd 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/exit_annotations.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/exit_annotations.rs @@ -6,7 +6,7 @@ use ruff_python_ast::{ }; use smallvec::SmallVec; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{SemanticModel, analyze::visibility::is_overload}; @@ -181,13 +181,13 @@ pub(crate) fn bad_exit_annotation(checker: &Checker, function: &StmtFunctionDef) .skip(3) .filter(|parameter| parameter.default.is_none()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadExitAnnotation { func_kind, error_kind: ErrorKind::ArgsAfterFirstFourMustHaveDefault, }, parameter.range(), - )); + ); } // ...as should all keyword-only arguments. @@ -196,13 +196,13 @@ pub(crate) fn bad_exit_annotation(checker: &Checker, function: &StmtFunctionDef) .iter() .filter(|arg| arg.default.is_none()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadExitAnnotation { func_kind, error_kind: ErrorKind::AllKwargsMustHaveDefault, }, parameter.range(), - )); + ); } check_positional_args_for_non_overloaded_method(checker, &non_self_positional_args, func_kind); @@ -216,7 +216,7 @@ fn check_short_args_list(checker: &Checker, parameters: &Parameters, func_kind: .annotation() .filter(|ann| !is_object_or_unused(ann, checker.semantic())) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BadExitAnnotation { func_kind, error_kind: ErrorKind::StarArgsNotAnnotated, @@ -233,17 +233,15 @@ fn check_short_args_list(checker: &Checker, parameters: &Parameters, func_kind: let binding_edit = Edit::range_replacement(binding, annotation.range()); Ok(Fix::safe_edits(binding_edit, import_edit)) }); - - checker.report_diagnostic(diagnostic); } } else { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadExitAnnotation { func_kind, error_kind: ErrorKind::MissingArgs, }, parameters.range(), - )); + ); } } @@ -284,13 +282,13 @@ fn check_positional_args_for_non_overloaded_method( continue; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadExitAnnotation { func_kind: kind, error_kind: error_info, }, annotation.range(), - )); + ); } } @@ -423,13 +421,13 @@ fn check_positional_args_for_overloaded_method( } // Okay, neither of them match... - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadExitAnnotation { func_kind: kind, error_kind: ErrorKind::UnrecognizedExitOverload, }, parameters_range, - )); + ); } /// Return the non-`None` annotation element of a PEP 604-style union or `Optional` annotation. diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/future_annotations_in_stub.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/future_annotations_in_stub.rs index 7f8d85871c..28ae4ef701 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/future_annotations_in_stub.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/future_annotations_in_stub.rs @@ -1,6 +1,6 @@ use ruff_python_ast::StmtImportFrom; -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::{checkers::ast::Checker, fix, preview::is_fix_future_annotations_in_stub_enabled}; @@ -53,7 +53,7 @@ pub(crate) fn from_future_import(checker: &Checker, target: &StmtImportFrom) { return; } - let mut diagnostic = Diagnostic::new(FutureAnnotationsInStub, *range); + let mut diagnostic = checker.report_diagnostic(FutureAnnotationsInStub, *range); if is_fix_future_annotations_in_stub_enabled(checker.settings) { let stmt = checker.semantic().current_statement(); @@ -71,6 +71,4 @@ pub(crate) fn from_future_import(checker: &Checker, target: &StmtImportFrom) { Ok(Fix::safe_edit(edit)) }); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/generic_not_last_base_class.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/generic_not_last_base_class.rs index f4af4d5fef..5aa851fb8d 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/generic_not_last_base_class.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/generic_not_last_base_class.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, helpers::map_subscript}; use ruff_text_size::Ranged; @@ -92,14 +92,12 @@ pub(crate) fn generic_not_last_base_class(checker: &Checker, class_def: &ast::St return; } - let mut diagnostic = Diagnostic::new(GenericNotLastBaseClass, bases.range()); + let mut diagnostic = checker.report_diagnostic(GenericNotLastBaseClass, bases.range()); // No fix if multiple `Generic[]`s are seen in the class bases. if generic_base_iter.next().is_none() { diagnostic.try_set_fix(|| generate_fix(generic_base, bases, checker)); } - - checker.report_diagnostic(diagnostic); } fn generate_fix( diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/iter_method_return_iterable.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/iter_method_return_iterable.rs index bcaa46086f..d2a25aa029 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/iter_method_return_iterable.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/iter_method_return_iterable.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_text_size::Ranged; @@ -125,9 +125,6 @@ pub(crate) fn iter_method_return_iterable(checker: &Checker, definition: &Defini } }) { - checker.report_diagnostic(Diagnostic::new( - IterMethodReturnIterable { is_async }, - returns.range(), - )); + checker.report_diagnostic(IterMethodReturnIterable { is_async }, returns.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/no_return_argument_annotation.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/no_return_argument_annotation.rs index c657dce97e..87cd4ff8c6 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/no_return_argument_annotation.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/no_return_argument_annotation.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; @@ -65,7 +65,7 @@ pub(crate) fn no_return_argument_annotation(checker: &Checker, parameters: &ast: .filter_map(ast::AnyParameterRef::annotation) { if is_no_return(annotation, checker) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NoReturnArgumentAnnotationInStub { module: if checker.target_version() >= PythonVersion::PY311 { TypingModule::Typing @@ -74,7 +74,7 @@ pub(crate) fn no_return_argument_annotation(checker: &Checker, parameters: &ast: }, }, annotation.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/non_empty_stub_body.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/non_empty_stub_body.rs index f6ec5b567d..02b5a61b0d 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/non_empty_stub_body.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/non_empty_stub_body.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::{self as ast, Stmt}; @@ -65,10 +65,9 @@ pub(crate) fn non_empty_stub_body(checker: &Checker, body: &[Stmt]) { } } - let mut diagnostic = Diagnostic::new(NonEmptyStubBody, stmt.range()); + let mut diagnostic = checker.report_diagnostic(NonEmptyStubBody, stmt.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), stmt.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/non_self_return_type.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/non_self_return_type.rs index 1329cabaac..ae2bf52d7f 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/non_self_return_type.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/non_self_return_type.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::{Checker, TypingImporter}; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::PythonVersion; @@ -208,7 +208,7 @@ fn add_diagnostic( return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NonSelfReturnType { class_name: class_def.name.to_string(), method_name: method_name.to_string(), @@ -219,8 +219,6 @@ fn add_diagnostic( diagnostic.try_set_fix(|| { replace_with_self_fix(checker.semantic(), &importer, stmt, returns, class_def) }); - - checker.report_diagnostic(diagnostic); } fn replace_with_self_fix( diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/numeric_literal_too_long.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/numeric_literal_too_long.rs index fc258077a6..a9f805501d 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/numeric_literal_too_long.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/numeric_literal_too_long.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_text_size::{Ranged, TextSize}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -50,10 +50,9 @@ pub(crate) fn numeric_literal_too_long(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new(NumericLiteralTooLong, expr.range()); + let mut diagnostic = checker.report_diagnostic(NumericLiteralTooLong, expr.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_in_class_body.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_in_class_body.rs index 2ba5d60dcd..830107855e 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_in_class_body.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_in_class_body.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; @@ -52,11 +52,10 @@ pub(crate) fn pass_in_class_body(checker: &Checker, class_def: &ast::StmtClassDe continue; } - let mut diagnostic = Diagnostic::new(PassInClassBody, stmt.range()); + let mut diagnostic = checker.report_diagnostic(PassInClassBody, stmt.range()); let edit = fix::edits::delete_stmt(stmt, Some(stmt), checker.locator(), checker.indexer()); diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_id(), ))); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs index c3ea8bccca..8ecd9f23f8 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; @@ -44,10 +44,9 @@ pub(crate) fn pass_statement_stub_body(checker: &Checker, body: &[Stmt]) { return; }; - let mut diagnostic = Diagnostic::new(PassStatementStubBody, pass.range()); + let mut diagnostic = checker.report_diagnostic(PassStatementStubBody, pass.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), pass.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/pre_pep570_positional_argument.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/pre_pep570_positional_argument.rs index f078e74cdd..344cb22744 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/pre_pep570_positional_argument.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/pre_pep570_positional_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::{self as ast, ParameterWithDefault}; @@ -87,10 +87,7 @@ pub(crate) fn pep_484_positional_parameter(checker: &Checker, function_def: &ast if let Some(arg) = function_def.parameters.args.get(skip) { if is_old_style_positional_only(arg) { - checker.report_diagnostic(Diagnostic::new( - Pep484StylePositionalOnlyParameter, - arg.identifier(), - )); + checker.report_diagnostic(Pep484StylePositionalOnlyParameter, arg.identifier()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/prefix_type_params.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/prefix_type_params.rs index 73c452fe23..fd1d872a61 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/prefix_type_params.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/prefix_type_params.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -106,5 +106,5 @@ pub(crate) fn prefix_type_params(checker: &Checker, value: &Expr, targets: &[Exp return; }; - checker.report_diagnostic(Diagnostic::new(UnprefixedTypeParam { kind }, value.range())); + checker.report_diagnostic(UnprefixedTypeParam { kind }, value.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs index 6b00c41d92..529e1e0674 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs @@ -1,6 +1,6 @@ use ruff_text_size::TextRange; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -44,10 +44,9 @@ impl AlwaysFixableViolation for QuotedAnnotationInStub { /// PYI020 pub(crate) fn quoted_annotation_in_stub(checker: &Checker, annotation: &str, range: TextRange) { - let mut diagnostic = Diagnostic::new(QuotedAnnotationInStub, range); + let mut diagnostic = checker.report_diagnostic(QuotedAnnotationInStub, range); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( annotation.to_string(), range, ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_final_literal.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_final_literal.rs index 1d5761db77..50c34c4820 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_final_literal.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_final_literal.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, comparable::ComparableExpr}; use ruff_text_size::{Ranged, TextSize}; @@ -97,7 +97,7 @@ pub(crate) fn redundant_final_literal(checker: &Checker, ann_assign: &ast::StmtA return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RedundantFinalLiteral { literal: SourceCodeSnippet::from_str(checker.locator().slice(literal.range())), }, @@ -113,8 +113,6 @@ pub(crate) fn redundant_final_literal(checker: &Checker, ann_assign: &ast::StmtA } else { diagnostic.set_fix(generate_fix(annotation, Some(literal), checker.locator())); } - - checker.report_diagnostic(diagnostic); } /// Generate a fix to convert a `Final[Literal[...]]` annotation to a `Final` annotation. diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_literal_union.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_literal_union.rs index fdb545bedf..7eb69aa53a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_literal_union.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_literal_union.rs @@ -2,7 +2,7 @@ use std::fmt; use rustc_hash::FxHashSet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, LiteralExpressionRef}; use ruff_python_semantic::SemanticModel; @@ -90,7 +90,7 @@ pub(crate) fn redundant_literal_union<'a>(checker: &Checker, union: &'a Expr) { }; if builtin_types_in_union.contains(&literal_type) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RedundantLiteralUnion { literal: SourceCodeSnippet::from_str( checker.locator().slice(typing_literal_expr), @@ -98,7 +98,7 @@ pub(crate) fn redundant_literal_union<'a>(checker: &Checker, union: &'a Expr) { builtin_type: literal_type, }, typing_literal_expr.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_none_literal.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_none_literal.rs index a9f1b50226..6d32946ca5 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_none_literal.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_none_literal.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ self as ast, Expr, ExprBinOp, ExprContext, ExprNoneLiteral, Operator, PythonVersion, @@ -120,7 +120,7 @@ pub(crate) fn redundant_none_literal<'a>(checker: &Checker, literal_expr: &'a Ex // N.B. Applying the fix can leave an unused import to be fixed by the `unused-import` rule. for none_expr in none_exprs { let mut diagnostic = - Diagnostic::new(RedundantNoneLiteral { union_kind }, none_expr.range()); + checker.report_diagnostic(RedundantNoneLiteral { union_kind }, none_expr.range()); diagnostic.try_set_optional_fix(|| { create_fix( checker, @@ -136,7 +136,6 @@ pub(crate) fn redundant_none_literal<'a>(checker: &Checker, literal_expr: &'a Ex fix.map(|fix| fix.isolate(Checker::isolation(semantic.current_statement_id()))) }) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_numeric_union.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_numeric_union.rs index 23f7cb4a03..3e5a47e60c 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_numeric_union.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_numeric_union.rs @@ -1,6 +1,6 @@ use bitflags::bitflags; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{AnyParameterRef, Expr, ExprBinOp, Operator, Parameters, PythonVersion}; use ruff_python_semantic::analyze::typing::traverse_union; @@ -129,7 +129,8 @@ fn check_annotation<'a>(checker: &Checker, annotation: &'a Expr) { // Traverse the union a second time to construct a [`Fix`]. traverse_union(&mut remove_numeric_type, checker.semantic(), annotation); - let mut diagnostic = Diagnostic::new(RedundantNumericUnion { redundancy }, annotation.range()); + let mut diagnostic = + checker.report_diagnostic(RedundantNumericUnion { redundancy }, annotation.range()); // Mark [`Fix`] as unsafe when comments are in range. let applicability = if checker.comment_ranges().intersects(annotation.range()) { @@ -173,8 +174,6 @@ fn check_annotation<'a>(checker: &Checker, annotation: &'a Expr) { if let Some(fix) = fix { diagnostic.set_fix(fix); } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, Eq, PartialEq)] diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/simple_defaults.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/simple_defaults.rs index c67b1c7815..bc3025d0f0 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/simple_defaults.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/simple_defaults.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Expr, Operator, Parameters, Stmt, UnaryOp}; @@ -509,14 +509,13 @@ pub(crate) fn typed_argument_simple_defaults(checker: &Checker, parameters: &Par checker.locator(), checker.semantic(), ) { - let mut diagnostic = Diagnostic::new(TypedArgumentDefaultInStub, default.range()); + let mut diagnostic = + checker.report_diagnostic(TypedArgumentDefaultInStub, default.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), default.range(), ))); - - checker.report_diagnostic(diagnostic); } } } @@ -535,14 +534,13 @@ pub(crate) fn argument_simple_defaults(checker: &Checker, parameters: &Parameter checker.locator(), checker.semantic(), ) { - let mut diagnostic = Diagnostic::new(ArgumentDefaultInStub, default.range()); + let mut diagnostic = + checker.report_diagnostic(ArgumentDefaultInStub, default.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), default.range(), ))); - - checker.report_diagnostic(diagnostic); } } } @@ -569,12 +567,11 @@ pub(crate) fn assignment_default_in_stub(checker: &Checker, targets: &[Expr], va return; } - let mut diagnostic = Diagnostic::new(AssignmentDefaultInStub, value.range()); + let mut diagnostic = checker.report_diagnostic(AssignmentDefaultInStub, value.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), value.range(), ))); - checker.report_diagnostic(diagnostic); } /// PYI015 @@ -603,12 +600,11 @@ pub(crate) fn annotated_assignment_default_in_stub( return; } - let mut diagnostic = Diagnostic::new(AssignmentDefaultInStub, value.range()); + let mut diagnostic = checker.report_diagnostic(AssignmentDefaultInStub, value.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), value.range(), ))); - checker.report_diagnostic(diagnostic); } /// PYI052 @@ -638,12 +634,12 @@ pub(crate) fn unannotated_assignment_in_stub(checker: &Checker, targets: &[Expr] return; } } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnannotatedAssignmentInStub { name: id.to_string(), }, value.range(), - )); + ); } /// PYI035 @@ -656,12 +652,12 @@ pub(crate) fn unassigned_special_variable_in_stub(checker: &Checker, target: &Ex return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnassignedSpecialVariableInStub { name: id.to_string(), }, stmt.range(), - )); + ); } /// PYI026 @@ -688,7 +684,7 @@ pub(crate) fn type_alias_without_annotation(checker: &Checker, value: &Expr, tar return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( TypeAliasWithoutAnnotation { module, name: id.to_string(), @@ -703,5 +699,4 @@ pub(crate) fn type_alias_without_annotation(checker: &Checker, value: &Expr, tar [import_edit], )) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/str_or_repr_defined_in_stub.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/str_or_repr_defined_in_stub.rs index 5d0870b554..670d2022ec 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/str_or_repr_defined_in_stub.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/str_or_repr_defined_in_stub.rs @@ -1,7 +1,7 @@ use ruff_python_ast as ast; use ruff_python_ast::Stmt; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility::is_abstract; @@ -82,7 +82,7 @@ pub(crate) fn str_or_repr_defined_in_stub(checker: &Checker, stmt: &Stmt) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( StrOrReprDefinedInStub { name: name.to_string(), }, @@ -94,5 +94,4 @@ pub(crate) fn str_or_repr_defined_in_stub(checker: &Checker, stmt: &Stmt) { diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_parent_id(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/string_or_bytes_too_long.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/string_or_bytes_too_long.rs index e5098c4ca3..a9d60412f4 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/string_or_bytes_too_long.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/string_or_bytes_too_long.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::{self as ast, StringLike}; @@ -72,12 +72,11 @@ pub(crate) fn string_or_bytes_too_long(checker: &Checker, string: StringLike) { return; } - let mut diagnostic = Diagnostic::new(StringOrBytesTooLong, string.range()); + let mut diagnostic = checker.report_diagnostic(StringOrBytesTooLong, string.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "...".to_string(), string.range(), ))); - checker.report_diagnostic(diagnostic); } /// Count the number of visible characters in an f-string. This accounts for diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/stub_body_multiple_statements.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/stub_body_multiple_statements.rs index 0d7f7728da..e29aac789f 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/stub_body_multiple_statements.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/stub_body_multiple_statements.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_python_ast::identifier::Identifier; @@ -41,9 +41,6 @@ impl Violation for StubBodyMultipleStatements { /// PYI048 pub(crate) fn stub_body_multiple_statements(checker: &Checker, stmt: &Stmt, body: &[Stmt]) { if body.len() > 1 { - checker.report_diagnostic(Diagnostic::new( - StubBodyMultipleStatements, - stmt.identifier(), - )); + checker.report_diagnostic(StubBodyMultipleStatements, stmt.identifier()); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/type_alias_naming.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/type_alias_naming.rs index 0454fe9491..d2c27f8f93 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/type_alias_naming.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/type_alias_naming.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -109,12 +109,12 @@ pub(crate) fn snake_case_type_alias(checker: &Checker, target: &Expr) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SnakeCaseTypeAlias { name: id.to_string(), }, *range, - )); + ); } } @@ -125,11 +125,11 @@ pub(crate) fn t_suffixed_type_alias(checker: &Checker, target: &Expr) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TSuffixedTypeAlias { name: id.to_string(), }, *range, - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unaliased_collections_abc_set_import.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unaliased_collections_abc_set_import.rs index 244f600abf..d0bc616c09 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unaliased_collections_abc_set_import.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unaliased_collections_abc_set_import.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Imported; use ruff_python_semantic::{Binding, BindingKind, Scope}; @@ -57,26 +57,24 @@ impl Violation for UnaliasedCollectionsAbcSetImport { } /// PYI025 -pub(crate) fn unaliased_collections_abc_set_import( - checker: &Checker, - binding: &Binding, -) -> Option { +pub(crate) fn unaliased_collections_abc_set_import(checker: &Checker, binding: &Binding) { let BindingKind::FromImport(import) = &binding.kind else { - return None; + return; }; if !matches!( import.qualified_name().segments(), ["collections", "abc", "Set"] ) { - return None; + return; } let name = binding.name(checker.source()); if name == "AbstractSet" { - return None; + return; } - let mut diagnostic = Diagnostic::new(UnaliasedCollectionsAbcSetImport, binding.range()); + let mut diagnostic = + checker.report_diagnostic(UnaliasedCollectionsAbcSetImport, binding.range()); if checker.semantic().is_available("AbstractSet") { diagnostic.try_set_fix(|| { let semantic = checker.semantic(); @@ -87,7 +85,6 @@ pub(crate) fn unaliased_collections_abc_set_import( Ok(Fix::applicable_edits(edit, rest, applicability)) }); } - Some(diagnostic) } fn determine_applicability(binding: &Binding, scope: &Scope, checker: &Checker) -> Applicability { diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_literal_union.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_literal_union.rs index e3374dbe86..5283220dc1 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_literal_union.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_literal_union.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::pep_604_union; use ruff_python_ast::{self as ast, Expr, ExprContext}; @@ -124,7 +124,7 @@ pub(crate) fn unnecessary_literal_union<'a>(checker: &Checker, expr: &'a Expr) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryLiteralUnion { members: literal_exprs .iter() @@ -180,6 +180,4 @@ pub(crate) fn unnecessary_literal_union<'a>(checker: &Checker, expr: &'a Expr) { Fix::safe_edit(edit) } }); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_type_union.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_type_union.rs index 3a4daa8e16..cf6505fa6c 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_type_union.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unnecessary_type_union.rs @@ -1,5 +1,5 @@ use ast::ExprContext; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::pep_604_union; use ruff_python_ast::name::Name; @@ -116,7 +116,7 @@ pub(crate) fn unnecessary_type_union<'a>(checker: &Checker, union: &'a Expr) { .map(|type_expr| Name::new(checker.locator().slice(type_expr))) .collect(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryTypeUnion { members: type_members.clone(), union_kind, @@ -218,8 +218,6 @@ pub(crate) fn unnecessary_type_union<'a>(checker: &Checker, union: &'a Expr) { applicability, )); } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] 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 34675e1dce..97914b0536 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 @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, CmpOp, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -115,7 +115,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) { - checker.report_diagnostic(Diagnostic::new(UnrecognizedPlatformCheck, test.range())); + checker.report_diagnostic(UnrecognizedPlatformCheck, test.range()); } return; } @@ -125,17 +125,17 @@ pub(crate) fn unrecognized_platform(checker: &Checker, test: &Expr) { // This protects against typos. if checker.enabled(Rule::UnrecognizedPlatformName) { if !matches!(value.to_str(), "linux" | "win32" | "cygwin" | "darwin") { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnrecognizedPlatformName { platform: value.to_string(), }, right.range(), - )); + ); } } } else { if checker.enabled(Rule::UnrecognizedPlatformCheck) { - checker.report_diagnostic(Diagnostic::new(UnrecognizedPlatformCheck, test.range())); + 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 7b474858d8..cccf71d073 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::{self as ast, CmpOp, Expr, Int}; @@ -148,7 +148,7 @@ pub(crate) fn unrecognized_version_info(checker: &Checker, test: &Expr) { version_check(checker, expected, test, *op, comparator); } else { if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { - checker.report_diagnostic(Diagnostic::new(UnrecognizedVersionInfoCheck, test.range())); + checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } } } @@ -164,8 +164,7 @@ fn version_check( if expected == ExpectedComparator::MajorDigit { if !is_int_constant(comparator) { if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { - checker - .report_diagnostic(Diagnostic::new(UnrecognizedVersionInfoCheck, test.range())); + checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } } return; @@ -174,7 +173,7 @@ fn version_check( // Tuple comparison, e.g., `sys.version_info == (3, 4)`. let Expr::Tuple(tuple) = comparator else { if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { - checker.report_diagnostic(Diagnostic::new(UnrecognizedVersionInfoCheck, test.range())); + checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } return; }; @@ -183,13 +182,13 @@ fn version_check( // 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) { - checker.report_diagnostic(Diagnostic::new(UnrecognizedVersionInfoCheck, test.range())); + 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) { - checker.report_diagnostic(Diagnostic::new(PatchVersionComparison, test.range())); + checker.report_diagnostic(PatchVersionComparison, test.range()); } } @@ -202,10 +201,10 @@ fn version_check( }; if tuple.len() != expected_length { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( WrongTupleLengthVersionComparison { expected_length }, test.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unsupported_method_call_on_all.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unsupported_method_call_on_all.rs index f00b918155..082cf4bdd8 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unsupported_method_call_on_all.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unsupported_method_call_on_all.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -69,12 +69,12 @@ pub(crate) fn unsupported_method_call_on_all(checker: &Checker, func: &Expr) { if !is_unsupported_method(attr.as_str()) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnsupportedMethodCallOnAll { name: attr.to_string(), }, func.range(), - )); + ); } fn is_unsupported_method(name: &str) -> bool { diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unused_private_type_definition.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unused_private_type_definition.rs index 03178a3a0a..5e481a724a 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unused_private_type_definition.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unused_private_type_definition.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::{self as ast, Expr, Stmt}; @@ -224,21 +224,20 @@ pub(crate) fn unused_private_type_var(checker: &Checker, scope: &Scope) { continue; }; - let diagnostic = Diagnostic::new( - UnusedPrivateTypeVar { - type_var_like_name: id.to_string(), - type_var_like_kind: type_var_like_kind.to_string(), - }, - binding.range(), - ) - .with_fix(Fix::unsafe_edit(fix::edits::delete_stmt( - stmt, - None, - checker.locator(), - checker.indexer(), - ))); - - checker.report_diagnostic(diagnostic); + checker + .report_diagnostic( + UnusedPrivateTypeVar { + type_var_like_name: id.to_string(), + type_var_like_kind: type_var_like_kind.to_string(), + }, + binding.range(), + ) + .set_fix(Fix::unsafe_edit(fix::edits::delete_stmt( + stmt, + None, + checker.locator(), + checker.indexer(), + ))); } } @@ -271,12 +270,12 @@ pub(crate) fn unused_private_protocol(checker: &Checker, scope: &Scope) { continue; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnusedPrivateProtocol { name: class_def.name.to_string(), }, binding.range(), - )); + ); } } @@ -303,12 +302,12 @@ pub(crate) fn unused_private_type_alias(checker: &Checker, scope: &Scope) { continue; }; - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnusedPrivateTypeAlias { name: alias_name.to_string(), }, binding.range(), - )); + ); } } @@ -358,12 +357,12 @@ pub(crate) fn unused_private_typed_dict(checker: &Checker, scope: &Scope) { continue; }; - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnusedPrivateTypedDict { name: class_name.to_string(), }, binding.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs index 0d5200dbee..71ba1e1de4 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/assertion.rs @@ -8,7 +8,7 @@ use libcst_native::{ SimpleWhitespace, SmallStatement, Statement, TrailingWhitespace, }; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::Truthiness; use ruff_python_ast::parenthesize::parenthesized_range; @@ -243,12 +243,12 @@ impl<'a> Visitor<'a> for ExceptionHandlerVisitor<'a, '_> { Expr::Name(ast::ExprName { id, .. }) => { if let Some(current_assert) = self.current_assert { if id.as_str() == self.exception_name { - self.checker.report_diagnostic(Diagnostic::new( + self.checker.report_diagnostic( PytestAssertInExcept { name: id.to_string(), }, current_assert.range(), - )); + ); } } } @@ -281,7 +281,7 @@ pub(crate) fn unittest_assertion( return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestUnittestAssertion { assertion: unittest_assert.to_string(), }, @@ -307,8 +307,6 @@ pub(crate) fn unittest_assertion( ))); } } - - checker.report_diagnostic(diagnostic); } /// ## What it does @@ -378,28 +376,23 @@ pub(crate) fn unittest_raises_assertion_call(checker: &Checker, call: &ast::Expr } } - if let Some(diagnostic) = unittest_raises_assertion(call, vec![], checker) { - checker.report_diagnostic(diagnostic); - } + unittest_raises_assertion(call, vec![], checker); } /// PT027 -pub(crate) fn unittest_raises_assertion_binding( - checker: &Checker, - binding: &Binding, -) -> Option { +pub(crate) fn unittest_raises_assertion_binding(checker: &Checker, binding: &Binding) { if !matches!(binding.kind, BindingKind::WithItemVar) { - return None; + return; } let semantic = checker.semantic(); - let Stmt::With(with) = binding.statement(semantic)? else { - return None; + let Some(Stmt::With(with)) = binding.statement(semantic) else { + return; }; - let Expr::Call(call) = corresponding_context_expr(binding, with)? else { - return None; + let Some(Expr::Call(call)) = corresponding_context_expr(binding, with) else { + return; }; let mut edits = vec![]; @@ -418,11 +411,13 @@ pub(crate) fn unittest_raises_assertion_binding( // ``` for reference_id in binding.references() { let reference = semantic.reference(reference_id); - let node_id = reference.expression_id()?; + let Some(node_id) = reference.expression_id() else { + return; + }; let mut ancestors = semantic.expressions(node_id).skip(1); - let Expr::Attribute(ast::ExprAttribute { attr, .. }) = ancestors.next()? else { + let Some(Expr::Attribute(ast::ExprAttribute { attr, .. })) = ancestors.next() else { continue; }; @@ -431,7 +426,7 @@ pub(crate) fn unittest_raises_assertion_binding( } } - unittest_raises_assertion(call, edits, checker) + unittest_raises_assertion(call, edits, checker); } fn corresponding_context_expr<'a>(binding: &Binding, with: &'a ast::StmtWith) -> Option<&'a Expr> { @@ -452,23 +447,19 @@ fn corresponding_context_expr<'a>(binding: &Binding, with: &'a ast::StmtWith) -> }) } -fn unittest_raises_assertion( - call: &ast::ExprCall, - extra_edits: Vec, - checker: &Checker, -) -> Option { +fn unittest_raises_assertion(call: &ast::ExprCall, extra_edits: Vec, checker: &Checker) { let Expr::Attribute(ast::ExprAttribute { attr, .. }) = call.func.as_ref() else { - return None; + return; }; if !matches!( attr.as_str(), "assertRaises" | "failUnlessRaises" | "assertRaisesRegex" | "assertRaisesRegexp" ) { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestUnittestRaisesAssertion { assertion: attr.to_string(), }, @@ -496,8 +487,6 @@ fn unittest_raises_assertion( }); } } - - Some(diagnostic) } fn to_pytest_raises_args<'a>( @@ -589,7 +578,7 @@ fn to_pytest_raises_args<'a>( pub(crate) fn assert_falsy(checker: &Checker, stmt: &Stmt, test: &Expr) { let truthiness = Truthiness::from_expr(test, |id| checker.semantic().has_builtin_binding(id)); if truthiness.into_bool() == Some(false) { - checker.report_diagnostic(Diagnostic::new(PytestAssertAlwaysFalse, stmt.range())); + checker.report_diagnostic(PytestAssertAlwaysFalse, stmt.range()); } } @@ -824,7 +813,7 @@ fn fix_composite_condition(stmt: &Stmt, locator: &Locator, stylist: &Stylist) -> pub(crate) fn composite_condition(checker: &Checker, stmt: &Stmt, test: &Expr, msg: Option<&Expr>) { let composite = is_composite_condition(test); if matches!(composite, CompositionKind::Simple | CompositionKind::Mixed) { - let mut diagnostic = Diagnostic::new(PytestCompositeAssertion, stmt.range()); + let mut diagnostic = checker.report_diagnostic(PytestCompositeAssertion, stmt.range()); if matches!(composite, CompositionKind::Simple) && msg.is_none() && !checker.comment_ranges().intersects(stmt.range()) @@ -837,6 +826,5 @@ pub(crate) fn composite_condition(checker: &Checker, stmt: &Stmt, test: &Expr, m .map(Fix::unsafe_edit) }); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fail.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fail.rs index 7435e12184..3c38e08c2b 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fail.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fail.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; @@ -65,7 +65,7 @@ pub(crate) fn fail_call(checker: &Checker, call: &ast::ExprCall) { .or_else(|| call.arguments.find_argument_value("msg", 0)) .is_none_or(is_empty_or_null_string) { - checker.report_diagnostic(Diagnostic::new(PytestFailWithoutMessage, call.func.range())); + checker.report_diagnostic(PytestFailWithoutMessage, call.func.range()); } } } 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 3803100689..c3b5e0cb99 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 @@ -1,5 +1,5 @@ use ruff_diagnostics::{AlwaysFixableViolation, Violation}; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Decorator; use ruff_python_ast::helpers::map_callable; @@ -672,12 +672,11 @@ fn pytest_fixture_parentheses( expected: Parentheses, actual: Parentheses, ) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestFixtureIncorrectParenthesesStyle { expected, actual }, decorator.range(), ); diagnostic.set_fix(fix); - checker.report_diagnostic(diagnostic); } /// PT001, PT002, PT003 @@ -706,20 +705,20 @@ fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decor if checker.enabled(Rule::PytestFixturePositionalArgs) { if !arguments.args.is_empty() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PytestFixturePositionalArgs { function: func_name.to_string(), }, decorator.range(), - )); + ); } } if checker.enabled(Rule::PytestExtraneousScopeFunction) { if let Some(keyword) = arguments.find_keyword("scope") { if keyword_is_literal(keyword, "function") { - let mut diagnostic = - Diagnostic::new(PytestExtraneousScopeFunction, keyword.range()); + let mut diagnostic = checker + .report_diagnostic(PytestExtraneousScopeFunction, keyword.range()); diagnostic.try_set_fix(|| { edits::remove_argument( keyword, @@ -729,7 +728,6 @@ fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decor ) .map(Fix::unsafe_edit) }); - checker.report_diagnostic(diagnostic); } } } @@ -775,7 +773,7 @@ fn check_fixture_returns(checker: &Checker, name: &str, body: &[Stmt], returns: if visitor.yield_statements.len() != 1 { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestUselessYieldFixture { name: name.to_string(), }, @@ -804,7 +802,6 @@ fn check_fixture_returns(checker: &Checker, name: &str, body: &[Stmt], returns: } else { diagnostic.set_fix(Fix::safe_edit(yield_edit)); } - checker.report_diagnostic(diagnostic); } } @@ -854,12 +851,12 @@ fn check_test_function_args(checker: &Checker, parameters: &Parameters, decorato for parameter in parameters.iter_non_variadic_params() { let name = parameter.name(); if name.starts_with('_') && !named_parametrize.contains(name.as_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PytestFixtureParamWithoutValue { name: name.to_string(), }, parameter.range(), - )); + ); } } } @@ -867,10 +864,7 @@ fn check_test_function_args(checker: &Checker, parameters: &Parameters, decorato /// PT020 fn check_fixture_decorator_name(checker: &Checker, decorator: &Decorator) { if is_pytest_yield_fixture(decorator, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( - PytestDeprecatedYieldFixture, - decorator.range(), - )); + checker.report_diagnostic(PytestDeprecatedYieldFixture, decorator.range()); } } @@ -887,10 +881,7 @@ fn check_fixture_addfinalizer(checker: &Checker, parameters: &Parameters, body: } if let Some(addfinalizer) = visitor.addfinalizer_call { - checker.report_diagnostic(Diagnostic::new( - PytestFixtureFinalizerCallback, - addfinalizer.range(), - )); + checker.report_diagnostic(PytestFixtureFinalizerCallback, addfinalizer.range()); } } @@ -900,20 +891,18 @@ fn check_fixture_marks(checker: &Checker, decorators: &[Decorator]) { if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) { if marker == "asyncio" { let mut diagnostic = - Diagnostic::new(PytestUnnecessaryAsyncioMarkOnFixture, expr.range()); + checker.report_diagnostic(PytestUnnecessaryAsyncioMarkOnFixture, expr.range()); let range = checker.locator().full_lines_range(expr.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(range))); - checker.report_diagnostic(diagnostic); } } if checker.enabled(Rule::PytestErroneousUseFixturesOnFixture) { if marker == "usefixtures" { let mut diagnostic = - Diagnostic::new(PytestErroneousUseFixturesOnFixture, expr.range()); + checker.report_diagnostic(PytestErroneousUseFixturesOnFixture, expr.range()); let line_range = checker.locator().full_lines_range(expr.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(line_range))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/imports.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/imports.rs index 1b99c5c25d..e92b0f1fdc 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/imports.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/imports.rs @@ -1,9 +1,11 @@ use ruff_python_ast::Stmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for incorrect import of pytest. /// @@ -36,39 +38,26 @@ fn is_pytest_or_subpackage(imported_name: &str) -> bool { } /// PT013 -pub(crate) fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option { +pub(crate) fn import(checker: &Checker, import_from: &Stmt, name: &str, asname: Option<&str>) { if is_pytest_or_subpackage(name) { if let Some(alias) = asname { if alias != name { - return Some(Diagnostic::new( - PytestIncorrectPytestImport, - import_from.range(), - )); + checker.report_diagnostic(PytestIncorrectPytestImport, import_from.range()); } } } - None } /// PT013 -pub(crate) fn import_from( - import_from: &Stmt, - module: Option<&str>, - level: u32, -) -> Option { +pub(crate) fn import_from(checker: &Checker, import_from: &Stmt, module: Option<&str>, level: u32) { // If level is not zero or module is none, return if level != 0 { - return None; + return; } if let Some(module) = module { if is_pytest_or_subpackage(module) { - return Some(Diagnostic::new( - PytestIncorrectPytestImport, - import_from.range(), - )); + checker.report_diagnostic(PytestIncorrectPytestImport, import_from.range()); } } - - None } 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 458aa5d846..513398827d 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 @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Arguments, Decorator, Expr}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -126,7 +126,7 @@ fn pytest_mark_parentheses( preferred: Parentheses, actual: Parentheses, ) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestIncorrectMarkParenthesesStyle { mark_name: marker.to_string(), expected_parens: preferred, @@ -135,7 +135,6 @@ fn pytest_mark_parentheses( decorator.range(), ); diagnostic.set_fix(fix); - checker.report_diagnostic(diagnostic); } fn check_mark_parentheses(checker: &Checker, decorator: &Decorator, marker: &str) { @@ -204,9 +203,9 @@ fn check_useless_usefixtures(checker: &Checker, decorator: &Decorator, marker: & _ => return, } - let mut diagnostic = Diagnostic::new(PytestUseFixturesWithoutParameters, decorator.range()); + let mut diagnostic = + checker.report_diagnostic(PytestUseFixturesWithoutParameters, decorator.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_deletion(decorator.range()))); - checker.report_diagnostic(diagnostic); } pub(crate) fn marks(checker: &Checker, decorators: &[Decorator]) { 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 cfe9351ab4..a0f1d8f9bc 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 @@ -1,6 +1,6 @@ use rustc_hash::{FxBuildHasher, FxHashMap}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::parenthesize::parenthesized_range; @@ -349,7 +349,7 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr checker.locator().contents(), ) .unwrap_or(expr.range()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: false, expected: names_type, @@ -375,7 +375,6 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr format!("({})", checker.generator().expr(&node)), name_range, ))); - checker.report_diagnostic(diagnostic); } types::ParametrizeNameType::List => { let name_range = get_parametrize_name_range( @@ -385,7 +384,7 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr checker.locator().contents(), ) .unwrap_or(expr.range()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: false, expected: names_type, @@ -410,7 +409,6 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr checker.generator().expr(&node), name_range, ))); - checker.report_diagnostic(diagnostic); } types::ParametrizeNameType::Csv => {} } @@ -423,7 +421,7 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr match names_type { types::ParametrizeNameType::Tuple => {} types::ParametrizeNameType::List => { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: false, expected: names_type, @@ -439,10 +437,9 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr checker.generator().expr(&node), expr.range(), ))); - checker.report_diagnostic(diagnostic); } types::ParametrizeNameType::Csv => { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: false, expected: names_type, @@ -457,7 +454,6 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr expr.range(), ))); } - checker.report_diagnostic(diagnostic); } } } @@ -469,7 +465,7 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr match names_type { types::ParametrizeNameType::List => {} types::ParametrizeNameType::Tuple => { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: false, expected: names_type, @@ -486,10 +482,9 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr format!("({})", checker.generator().expr(&node)), expr.range(), ))); - checker.report_diagnostic(diagnostic); } types::ParametrizeNameType::Csv => { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: false, expected: names_type, @@ -504,7 +499,6 @@ fn check_names(checker: &Checker, call: &ExprCall, expr: &Expr, argvalues: &Expr expr.range(), ))); } - checker.report_diagnostic(diagnostic); } } } @@ -531,7 +525,7 @@ fn check_values(checker: &Checker, names: &Expr, values: &Expr) { match values { Expr::List(ast::ExprList { elts, .. }) => { if values_type != types::ParametrizeValuesType::List { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeValuesWrongType { values: values_type, row: values_row_type, @@ -570,7 +564,6 @@ fn check_values(checker: &Checker, names: &Expr, values: &Expr) { ); Fix::unsafe_edits(values_start, [values_end]) }); - checker.report_diagnostic(diagnostic); } if is_multi_named { @@ -579,7 +572,7 @@ fn check_values(checker: &Checker, names: &Expr, values: &Expr) { } Expr::Tuple(ast::ExprTuple { elts, .. }) => { if values_type != types::ParametrizeValuesType::Tuple { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeValuesWrongType { values: values_type, row: values_row_type, @@ -618,7 +611,6 @@ fn check_values(checker: &Checker, names: &Expr, values: &Expr) { Fix::unsafe_edits(values_start, [values_end]) }); - checker.report_diagnostic(diagnostic); } if is_multi_named { @@ -664,7 +656,7 @@ fn check_duplicates(checker: &Checker, values: &Expr) { let expr = ComparableExpr::from(element); seen.entry(expr) .and_modify(|index| { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestDuplicateParametrizeTestCases { index: *index }, element.range(), ); @@ -679,7 +671,6 @@ fn check_duplicates(checker: &Checker, values: &Expr) { diagnostic.set_fix(Fix::unsafe_edit(Edit::range_deletion(deletion_range))); } } - checker.report_diagnostic(diagnostic); }) .or_insert(index); prev = Some(element); @@ -687,7 +678,7 @@ fn check_duplicates(checker: &Checker, values: &Expr) { } fn handle_single_name(checker: &Checker, argnames: &Expr, value: &Expr, argvalues: &Expr) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeNamesWrongType { single_argument: true, expected: types::ParametrizeNameType::Csv, @@ -730,7 +721,6 @@ fn handle_single_name(checker: &Checker, argnames: &Expr, value: &Expr, argvalue Fix::safe_edits(argnames_edit, argvalues_edits) }; diagnostic.set_fix(fix); - checker.report_diagnostic(diagnostic); } /// Generate [`Edit`]s to unpack single-element lists or tuples in the given [`Expr`]. @@ -775,7 +765,7 @@ fn handle_value_rows( match elt { Expr::Tuple(ast::ExprTuple { elts, .. }) => { if values_row_type != types::ParametrizeValuesRowType::Tuple { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeValuesWrongType { values: values_type, row: values_row_type, @@ -813,12 +803,11 @@ fn handle_value_rows( let elt_end = Edit::replacement("]".into(), start, elt.end()); Fix::unsafe_edits(elt_start, [elt_end]) }); - checker.report_diagnostic(diagnostic); } } Expr::List(ast::ExprList { elts, .. }) => { if values_row_type != types::ParametrizeValuesRowType::List { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PytestParametrizeValuesWrongType { values: values_type, row: values_row_type, @@ -857,7 +846,6 @@ fn handle_value_rows( ); Fix::unsafe_edits(elt_start, [elt_end]) }); - checker.report_diagnostic(diagnostic); } } _ => {} diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/patch.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/patch.rs index 21876daa19..2954531a9c 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/patch.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/patch.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::visitor; @@ -6,6 +6,8 @@ use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, Parameters}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for mocked calls that use a dummy `lambda` function instead of /// `return_value`. @@ -73,19 +75,22 @@ impl<'a> Visitor<'a> for LambdaBodyVisitor<'a> { } } -fn check_patch_call(call: &ast::ExprCall, index: usize) -> Option { +fn check_patch_call(checker: &Checker, call: &ast::ExprCall, index: usize) { if call.arguments.find_keyword("return_value").is_some() { - return None; + return; } - let ast::ExprLambda { + let Some(ast::ExprLambda { parameters, body, range: _, - } = call + }) = call .arguments - .find_argument_value("new", index)? - .as_lambda_expr()?; + .find_argument_value("new", index) + .and_then(|expr| expr.as_lambda_expr()) + else { + return; + }; // Walk the lambda body. If the lambda uses the arguments, then it's valid. if let Some(parameters) = parameters { @@ -95,16 +100,18 @@ fn check_patch_call(call: &ast::ExprCall, index: usize) -> Option { }; visitor.visit_expr(body); if visitor.uses_args { - return None; + return; } } - Some(Diagnostic::new(PytestPatchWithLambda, call.func.range())) + checker.report_diagnostic(PytestPatchWithLambda, call.func.range()); } /// PT008 -pub(crate) fn patch_with_lambda(call: &ast::ExprCall) -> Option { - let name = UnqualifiedName::from_expr(&call.func)?; +pub(crate) fn patch_with_lambda(checker: &Checker, call: &ast::ExprCall) { + let Some(name) = UnqualifiedName::from_expr(&call.func) else { + return; + }; if matches!( name.segments(), @@ -118,7 +125,7 @@ pub(crate) fn patch_with_lambda(call: &ast::ExprCall) -> Option { "patch" ] | ["unittest", "mock", "patch"] ) { - check_patch_call(call, 1) + check_patch_call(checker, call, 1); } else if matches!( name.segments(), [ @@ -132,8 +139,6 @@ pub(crate) fn patch_with_lambda(call: &ast::ExprCall) -> Option { "object" ] | ["unittest", "mock", "patch", "object"] ) { - check_patch_call(call, 2) - } else { - None + check_patch_call(checker, call, 2); } } 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 791843e271..4fc0d62833 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_compound_statement; use ruff_python_ast::{self as ast, Expr, Stmt, WithItem}; @@ -178,10 +178,7 @@ pub(crate) fn raises_call(checker: &Checker, call: &ast::ExprCall) { .find_argument("expected_exception", 0) .is_none() { - checker.report_diagnostic(Diagnostic::new( - PytestRaisesWithoutException, - call.func.range(), - )); + checker.report_diagnostic(PytestRaisesWithoutException, call.func.range()); } } @@ -234,10 +231,7 @@ pub(crate) fn complex_raises(checker: &Checker, stmt: &Stmt, items: &[WithItem], }; if is_too_complex { - checker.report_diagnostic(Diagnostic::new( - PytestRaisesWithMultipleStatements, - stmt.range(), - )); + checker.report_diagnostic(PytestRaisesWithMultipleStatements, stmt.range()); } } } @@ -264,11 +258,11 @@ fn exception_needs_match(checker: &Checker, exception: &Expr) { .then_some(qualified_name) }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PytestRaisesTooBroad { exception: qualified_name, }, exception.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/test_functions.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/test_functions.rs index d6d7c4e6cd..1da6464166 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/test_functions.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/test_functions.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::rules::flake8_pytest_style::rules::helpers::is_likely_pytest_test; -use ruff_diagnostics::{Diagnostic, Edit, Fix, Violation}; +use ruff_diagnostics::{Edit, Fix, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StmtFunctionDef; use ruff_text_size::Ranged; @@ -61,9 +61,10 @@ pub(crate) fn parameter_with_default_argument(checker: &Checker, function_def: & }; let parameter_name = parameter.name().to_string(); let kind = PytestParameterWithDefaultArgument { parameter_name }; - let diagnostic = Diagnostic::new(kind, default.range()); let edit = Edit::deletion(parameter.parameter.end(), parameter.end()); let fix = Fix::display_only_edit(edit); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(kind, default.range()) + .set_fix(fix); } } 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 a0ccb4a52d..ceadb3ba08 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_compound_statement; use ruff_python_ast::{self as ast, Expr, Stmt, WithItem}; @@ -174,10 +174,7 @@ pub(crate) fn warns_call(checker: &Checker, call: &ast::ExprCall) { if is_pytest_warns(&call.func, checker.semantic()) { if checker.enabled(Rule::PytestWarnsWithoutWarning) { if call.arguments.is_empty() { - checker.report_diagnostic(Diagnostic::new( - PytestWarnsWithoutWarning, - call.func.range(), - )); + checker.report_diagnostic(PytestWarnsWithoutWarning, call.func.range()); } } @@ -222,10 +219,7 @@ pub(crate) fn complex_warns(checker: &Checker, stmt: &Stmt, items: &[WithItem], }; if is_too_complex { - checker.report_diagnostic(Diagnostic::new( - PytestWarnsWithMultipleStatements, - stmt.range(), - )); + checker.report_diagnostic(PytestWarnsWithMultipleStatements, stmt.range()); } } } @@ -253,11 +247,11 @@ fn warning_needs_match(checker: &Checker, warning: &Expr) { .then_some(qualified_name) }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PytestWarnsTooBroad { warning: qualified_name, }, warning.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_quotes/rules/avoidable_escaped_quote.rs b/crates/ruff_linter/src/rules/flake8_quotes/rules/avoidable_escaped_quote.rs index f1fc4c5a50..64b1b83de2 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/rules/avoidable_escaped_quote.rs +++ b/crates/ruff_linter/src/rules/flake8_quotes/rules/avoidable_escaped_quote.rs @@ -1,12 +1,11 @@ use flake8_quotes::helpers::{contains_escaped_quote, raw_contents, unescape_string}; use flake8_quotes::settings::Quote; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::{Visitor, walk_f_string}; use ruff_python_ast::{self as ast, AnyStringFlags, PythonVersion, StringFlags, StringLike}; use ruff_text_size::{Ranged, TextRange, TextSize}; -use crate::Locator; use crate::checkers::ast::Checker; use crate::rules::flake8_quotes; @@ -94,25 +93,21 @@ impl<'a, 'b> AvoidableEscapedQuoteChecker<'a, 'b> { impl Visitor<'_> for AvoidableEscapedQuoteChecker<'_, '_> { fn visit_string_literal(&mut self, string_literal: &ast::StringLiteral) { - if let Some(diagnostic) = check_string_or_bytes( - self.checker.locator(), + check_string_or_bytes( + self.checker, self.quotes_settings, string_literal.range(), AnyStringFlags::from(string_literal.flags), - ) { - self.checker.report_diagnostic(diagnostic); - } + ); } fn visit_bytes_literal(&mut self, bytes_literal: &ast::BytesLiteral) { - if let Some(diagnostic) = check_string_or_bytes( - self.checker.locator(), + check_string_or_bytes( + self.checker, self.quotes_settings, bytes_literal.range(), AnyStringFlags::from(bytes_literal.flags), - ) { - self.checker.report_diagnostic(diagnostic); - } + ); } fn visit_f_string(&mut self, f_string: &'_ ast::FString) { @@ -184,11 +179,7 @@ impl Visitor<'_> for AvoidableEscapedQuoteChecker<'_, '_> { .literals() .any(|literal| contains_quote(literal, opposite_quote_char)) { - if let Some(diagnostic) = - check_f_string(self.checker.locator(), self.quotes_settings, f_string) - { - self.checker.report_diagnostic(diagnostic); - } + check_f_string(self.checker, self.quotes_settings, f_string); } walk_f_string(self, f_string); @@ -201,20 +192,22 @@ impl Visitor<'_> for AvoidableEscapedQuoteChecker<'_, '_> { /// /// If the string kind is an f-string. fn check_string_or_bytes( - locator: &Locator, + checker: &Checker, quotes_settings: &flake8_quotes::settings::Settings, range: TextRange, flags: AnyStringFlags, -) -> Option { +) { assert!(!flags.is_f_string()); + let locator = checker.locator(); + if flags.is_triple_quoted() || flags.is_raw_string() { - return None; + return; } // Check if we're using the preferred quotation style. if Quote::from(flags.quote_style()) != quotes_settings.inline_quotes { - return None; + return; } let contents = raw_contents(locator.slice(range), flags); @@ -222,10 +215,10 @@ fn check_string_or_bytes( if !contains_escaped_quote(contents, quotes_settings.inline_quotes.as_char()) || contains_quote(contents, quotes_settings.inline_quotes.opposite().as_char()) { - return None; + return; } - let mut diagnostic = Diagnostic::new(AvoidableEscapedQuote, range); + let mut diagnostic = checker.report_diagnostic(AvoidableEscapedQuote, range); let fixed_contents = format!( "{prefix}{quote}{value}{quote}", prefix = flags.prefix(), @@ -236,24 +229,25 @@ fn check_string_or_bytes( fixed_contents, range, ))); - Some(diagnostic) } /// Checks for unnecessary escaped quotes in an f-string. fn check_f_string( - locator: &Locator, + checker: &Checker, quotes_settings: &flake8_quotes::settings::Settings, f_string: &ast::FString, -) -> Option { +) { + let locator = checker.locator(); + let ast::FString { flags, range, .. } = f_string; if flags.is_triple_quoted() || flags.prefix().is_raw() { - return None; + return; } // Check if we're using the preferred quotation style. if Quote::from(flags.quote_style()) != quotes_settings.inline_quotes { - return None; + return; } let quote_char = quotes_settings.inline_quotes.as_char(); @@ -272,7 +266,7 @@ fn check_f_string( } if edits.is_empty() { - return None; + return; } // Replacement for the f-string opening quote. We don't perform the check for raw and @@ -303,9 +297,9 @@ fn check_f_string( ), )); - Some( - Diagnostic::new(AvoidableEscapedQuote, *range).with_fix(Fix::safe_edits(start_edit, edits)), - ) + checker + .report_diagnostic(AvoidableEscapedQuote, *range) + .set_fix(Fix::safe_edits(start_edit, edits)); } #[derive(Debug, Default)] 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 128bc32714..8ad5310f90 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StringLike; use ruff_text_size::{Ranged, TextRange}; @@ -261,12 +261,12 @@ fn docstring(checker: &Checker, range: TextRange) { { // Fixing this would result in a one-sided multi-line docstring, which would // introduce a syntax error. - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadQuotesDocstring { preferred_quote: quotes_settings.docstring_quotes, }, range, - )); + ); return; } @@ -277,7 +277,7 @@ fn docstring(checker: &Checker, range: TextRange) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BadQuotesDocstring { preferred_quote: quotes_settings.docstring_quotes, }, @@ -298,7 +298,6 @@ fn docstring(checker: &Checker, range: TextRange) { fixed_contents, range, ))); - checker.report_diagnostic(diagnostic); } /// Q000, Q001 @@ -353,7 +352,7 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { continue; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BadQuotesMultilineString { preferred_quote: quotes_settings.multiline_quotes, }, @@ -373,7 +372,6 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { fixed_contents, *range, ))); - checker.report_diagnostic(diagnostic); } else if trivia.last_quote_char != quotes_settings.inline_quotes.as_char() // If we're not using the preferred type, only allow use to avoid escapes. && !relax_quote @@ -391,12 +389,12 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { // ```python // ''"assert" ' SAM macro definitions ''' // ``` - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadQuotesInlineString { preferred_quote: quotes_settings.inline_quotes, }, *range, - )); + ); continue; } @@ -406,16 +404,16 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { // ```python // ''"assert" ' SAM macro definitions ''' // ``` - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadQuotesInlineString { preferred_quote: quotes_settings.inline_quotes, }, *range, - )); + ); continue; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BadQuotesInlineString { preferred_quote: quotes_settings.inline_quotes, }, @@ -433,7 +431,6 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { fixed_contents, *range, ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_quotes/rules/unnecessary_escaped_quote.rs b/crates/ruff_linter/src/rules/flake8_quotes/rules/unnecessary_escaped_quote.rs index df7aed1032..8a58fccf00 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/rules/unnecessary_escaped_quote.rs +++ b/crates/ruff_linter/src/rules/flake8_quotes/rules/unnecessary_escaped_quote.rs @@ -1,9 +1,8 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, AnyStringFlags, StringFlags, StringLike}; use ruff_text_size::{Ranged, TextRange}; -use crate::Locator; use crate::checkers::ast::Checker; use super::super::helpers::{contains_escaped_quote, raw_contents, unescape_string}; @@ -51,33 +50,19 @@ pub(crate) fn unnecessary_escaped_quote(checker: &Checker, string_like: StringLi return; } - let locator = checker.locator(); - for part in string_like.parts() { match part { - ast::StringLikePart::String(string_literal) => { - if let Some(diagnostic) = check_string_or_bytes( - locator, - string_literal.range(), - AnyStringFlags::from(string_literal.flags), - ) { - checker.report_diagnostic(diagnostic); - } - } - ast::StringLikePart::Bytes(bytes_literal) => { - if let Some(diagnostic) = check_string_or_bytes( - locator, - bytes_literal.range(), - AnyStringFlags::from(bytes_literal.flags), - ) { - checker.report_diagnostic(diagnostic); - } - } - ast::StringLikePart::FString(f_string) => { - if let Some(diagnostic) = check_f_string(locator, f_string) { - checker.report_diagnostic(diagnostic); - } - } + ast::StringLikePart::String(string_literal) => check_string_or_bytes( + checker, + string_literal.range(), + AnyStringFlags::from(string_literal.flags), + ), + ast::StringLikePart::Bytes(bytes_literal) => check_string_or_bytes( + checker, + bytes_literal.range(), + AnyStringFlags::from(bytes_literal.flags), + ), + ast::StringLikePart::FString(f_string) => check_f_string(checker, f_string), } } } @@ -87,47 +72,42 @@ pub(crate) fn unnecessary_escaped_quote(checker: &Checker, string_like: StringLi /// # Panics /// /// If the string kind is an f-string. -fn check_string_or_bytes( - locator: &Locator, - range: TextRange, - flags: AnyStringFlags, -) -> Option { +fn check_string_or_bytes(checker: &Checker, range: TextRange, flags: AnyStringFlags) { assert!(!flags.is_f_string()); if flags.is_triple_quoted() || flags.is_raw_string() { - return None; + return; } - let contents = raw_contents(locator.slice(range), flags); + let contents = raw_contents(checker.locator().slice(range), flags); let quote = flags.quote_style(); let opposite_quote_char = quote.opposite().as_char(); if !contains_escaped_quote(contents, opposite_quote_char) { - return None; + return; } - let mut diagnostic = Diagnostic::new(UnnecessaryEscapedQuote, range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryEscapedQuote, range); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( flags .display_contents(&unescape_string(contents, opposite_quote_char)) .to_string(), range, ))); - Some(diagnostic) } /// Checks for unnecessary escaped quotes in an f-string. -fn check_f_string(locator: &Locator, f_string: &ast::FString) -> Option { +fn check_f_string(checker: &Checker, f_string: &ast::FString) { let ast::FString { flags, range, .. } = f_string; if flags.is_triple_quoted() || flags.prefix().is_raw() { - return None; + return; } let opposite_quote_char = flags.quote_style().opposite().as_char(); let mut edits = vec![]; for literal in f_string.elements.literals() { - let content = locator.slice(literal); + let content = checker.locator().slice(literal); if !contains_escaped_quote(content, opposite_quote_char) { continue; } @@ -138,9 +118,10 @@ fn check_f_string(locator: &Locator, f_string: &ast::FString) -> Option bool { } fn add_return_none(checker: &Checker, stmt: &Stmt, range: TextRange) { - let mut diagnostic = Diagnostic::new(ImplicitReturn, range); + let mut diagnostic = checker.report_diagnostic(ImplicitReturn, range); if let Some(indent) = indentation(checker.source(), stmt) { let mut content = String::new(); content.push_str(checker.stylist().line_ending().as_str()); @@ -466,7 +461,6 @@ fn add_return_none(checker: &Checker, stmt: &Stmt, range: TextRange) { end_of_last_statement(stmt, checker.locator()), ))); } - checker.report_diagnostic(diagnostic); } /// Returns a list of all implicit returns in the given statement. @@ -607,7 +601,7 @@ fn unnecessary_assign(checker: &Checker, stack: &Stack) { continue; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryAssign { name: assigned_id.to_string(), }, @@ -652,7 +646,6 @@ fn unnecessary_assign(checker: &Checker, stack: &Stack) { Ok(Fix::unsafe_edits(replace_assign, [delete_return])) }); - checker.report_diagnostic(diagnostic); } } @@ -667,83 +660,24 @@ fn superfluous_else_node( } else { Branch::Else }; + let range = elif_else_range(elif_else, checker.locator().contents()) + .unwrap_or_else(|| elif_else.range()); for child in if_elif_body { - if child.is_return_stmt() { - let mut diagnostic = Diagnostic::new( - SuperfluousElseReturn { branch }, - elif_else_range(elif_else, checker.locator().contents()) - .unwrap_or_else(|| elif_else.range()), - ); - if checker.enabled(diagnostic.rule()) { - diagnostic.try_set_fix(|| { - remove_else( - elif_else, - checker.locator(), - checker.indexer(), - checker.stylist(), - ) - }); - checker.report_diagnostic(diagnostic); - } - return true; + let diagnostic = if child.is_return_stmt() { + checker.report_diagnostic_if_enabled(SuperfluousElseReturn { branch }, range) } else if child.is_break_stmt() { - let mut diagnostic = Diagnostic::new( - SuperfluousElseBreak { branch }, - elif_else_range(elif_else, checker.locator().contents()) - .unwrap_or_else(|| elif_else.range()), - ); - if checker.enabled(diagnostic.rule()) { - diagnostic.try_set_fix(|| { - remove_else( - elif_else, - checker.locator(), - checker.indexer(), - checker.stylist(), - ) - }); - - checker.report_diagnostic(diagnostic); - } - return true; + checker.report_diagnostic_if_enabled(SuperfluousElseBreak { branch }, range) } else if child.is_raise_stmt() { - let mut diagnostic = Diagnostic::new( - SuperfluousElseRaise { branch }, - elif_else_range(elif_else, checker.locator().contents()) - .unwrap_or_else(|| elif_else.range()), - ); - if checker.enabled(diagnostic.rule()) { - diagnostic.try_set_fix(|| { - remove_else( - elif_else, - checker.locator(), - checker.indexer(), - checker.stylist(), - ) - }); - - checker.report_diagnostic(diagnostic); - } - return true; + checker.report_diagnostic_if_enabled(SuperfluousElseRaise { branch }, range) } else if child.is_continue_stmt() { - let mut diagnostic = Diagnostic::new( - SuperfluousElseContinue { branch }, - elif_else_range(elif_else, checker.locator().contents()) - .unwrap_or_else(|| elif_else.range()), - ); - if checker.enabled(diagnostic.rule()) { - diagnostic.try_set_fix(|| { - remove_else( - elif_else, - checker.locator(), - checker.indexer(), - checker.stylist(), - ) - }); - - checker.report_diagnostic(diagnostic); - } - return true; + checker.report_diagnostic_if_enabled(SuperfluousElseContinue { branch }, range) + } else { + continue; + }; + if let Some(mut d) = diagnostic { + d.try_set_fix(|| remove_else(checker, elif_else)); } + return true; } false } @@ -826,12 +760,11 @@ pub(crate) fn function(checker: &Checker, function_def: &ast::StmtFunctionDef) { } /// Generate a [`Fix`] to remove an `else` or `elif` clause. -fn remove_else( - elif_else: &ElifElseClause, - locator: &Locator, - indexer: &Indexer, - stylist: &Stylist, -) -> Result { +fn remove_else(checker: &Checker, elif_else: &ElifElseClause) -> Result { + let locator = checker.locator(); + let indexer = checker.indexer(); + let stylist = checker.stylist(); + if elif_else.test.is_some() { // Ex) `elif` -> `if` Ok(Fix::safe_edit(Edit::deletion( diff --git a/crates/ruff_linter/src/rules/flake8_self/rules/private_member_access.rs b/crates/ruff_linter/src/rules/flake8_self/rules/private_member_access.rs index 5c3872d0ff..7bb4ff3b21 100644 --- a/crates/ruff_linter/src/rules/flake8_self/rules/private_member_access.rs +++ b/crates/ruff_linter/src/rules/flake8_self/rules/private_member_access.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::{is_dunder, is_sunder}; use ruff_python_ast::name::UnqualifiedName; @@ -144,12 +144,12 @@ pub(crate) fn private_member_access(checker: &Checker, expr: &Expr) { } } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PrivateMemberAccess { access: attr.to_string(), }, expr.range(), - )); + ); } /// Check for the following cases: diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_bool_op.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_bool_op.rs index 76181cc76b..07f2bcb20d 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_bool_op.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_bool_op.rs @@ -6,7 +6,7 @@ use itertools::Itertools; use ruff_python_ast::{self as ast, Arguments, BoolOp, CmpOp, Expr, ExprContext, UnaryOp}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::{Truthiness, contains_effect}; @@ -374,7 +374,7 @@ pub(crate) fn duplicate_isinstance_call(checker: &Checker, expr: &Expr) { } else { unreachable!("Indices should only contain `isinstance` calls") }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DuplicateIsinstanceCall { name: if let Expr::Name(ast::ExprName { id, .. }) = target { Some(id.to_string()) @@ -462,7 +462,6 @@ pub(crate) fn duplicate_isinstance_call(checker: &Checker, expr: &Expr) { expr.range(), ))); } - checker.report_diagnostic(diagnostic); } } } @@ -557,7 +556,7 @@ pub(crate) fn compare_with_tuple(checker: &Checker, expr: &Expr) { range: TextRange::default(), }; let in_expr = node2.into(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CompareWithTuple { replacement: checker.generator().expr(&in_expr), }, @@ -584,7 +583,6 @@ pub(crate) fn compare_with_tuple(checker: &Checker, expr: &Expr) { checker.generator().expr(&in_expr), expr.range(), ))); - checker.report_diagnostic(diagnostic); } } @@ -629,7 +627,7 @@ pub(crate) fn expr_and_not_expr(checker: &Checker, expr: &Expr) { for negate_expr in negated_expr { for non_negate_expr in &non_negated_expr { if let Some(id) = is_same_expr(negate_expr, non_negate_expr) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ExprAndNotExpr { name: id.to_string(), }, @@ -639,7 +637,6 @@ pub(crate) fn expr_and_not_expr(checker: &Checker, expr: &Expr) { "False".to_string(), expr.range(), ))); - checker.report_diagnostic(diagnostic); } } } @@ -686,7 +683,7 @@ pub(crate) fn expr_or_not_expr(checker: &Checker, expr: &Expr) { for negate_expr in negated_expr { for non_negate_expr in &non_negated_expr { if let Some(id) = is_same_expr(negate_expr, non_negate_expr) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ExprOrNotExpr { name: id.to_string(), }, @@ -696,7 +693,6 @@ pub(crate) fn expr_or_not_expr(checker: &Checker, expr: &Expr) { "True".to_string(), expr.range(), ))); - checker.report_diagnostic(diagnostic); } } } @@ -838,7 +834,7 @@ pub(crate) fn expr_or_true(checker: &Checker, expr: &Expr) { } if let Some((edit, remove)) = is_short_circuit(expr, BoolOp::Or, checker) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ExprOrTrue { expr: edit.content().unwrap_or_default().to_string(), remove, @@ -846,7 +842,6 @@ pub(crate) fn expr_or_true(checker: &Checker, expr: &Expr) { edit.range(), ); diagnostic.set_fix(Fix::unsafe_edit(edit)); - checker.report_diagnostic(diagnostic); } } @@ -857,7 +852,7 @@ pub(crate) fn expr_and_false(checker: &Checker, expr: &Expr) { } if let Some((edit, remove)) = is_short_circuit(expr, BoolOp::And, checker) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ExprAndFalse { expr: edit.content().unwrap_or_default().to_string(), remove, @@ -865,6 +860,5 @@ pub(crate) fn expr_and_false(checker: &Checker, expr: &Expr) { edit.range(), ); diagnostic.set_fix(Fix::unsafe_edit(edit)); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_expr.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_expr.rs index ab832240bd..8a8b5268fd 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_expr.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_expr.rs @@ -2,7 +2,7 @@ use ruff_python_ast::{self as ast, Arguments, Expr, str_prefix::StringLiteralPre use ruff_text_size::{Ranged, TextRange}; use crate::fix::snippet::SourceCodeSnippet; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_python_semantic::analyze::typing::is_dict; @@ -175,13 +175,13 @@ pub(crate) fn use_capital_environment_variables(checker: &Checker, expr: &Expr) return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UncapitalizedEnvironmentVariables { expected: SourceCodeSnippet::new(capital_env_var), actual: SourceCodeSnippet::new(env_var.to_string()), }, arg.range(), - )); + ); } fn check_os_environ_subscript(checker: &Checker, expr: &Expr) { @@ -215,7 +215,7 @@ fn check_os_environ_subscript(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UncapitalizedEnvironmentVariables { expected: SourceCodeSnippet::new(capital_env_var.clone()), actual: SourceCodeSnippet::new(env_var.to_string()), @@ -238,7 +238,6 @@ fn check_os_environ_subscript(checker: &Checker, expr: &Expr) { checker.generator().expr(&new_env_var), slice.range(), ))); - checker.report_diagnostic(diagnostic); } /// SIM910 @@ -298,7 +297,7 @@ pub(crate) fn dict_get_with_none_default(checker: &Checker, expr: &Expr) { ); let actual = checker.locator().slice(expr); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DictGetWithNoneDefault { expected: SourceCodeSnippet::new(expected.clone()), actual: SourceCodeSnippet::from_str(actual), @@ -309,5 +308,4 @@ pub(crate) fn dict_get_with_none_default(checker: &Checker, expr: &Expr) { expected, expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_ifexp.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_ifexp.rs index 10746d0588..8207ec4f3f 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_ifexp.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_ifexp.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, UnaryOp}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::{is_const_false, is_const_true}; use ruff_python_ast::name::Name; @@ -157,7 +157,7 @@ pub(crate) fn if_expr_with_true_false( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfExprWithTrueFalse { is_compare: test.is_compare_expr(), }, @@ -203,7 +203,6 @@ pub(crate) fn if_expr_with_true_false( expr.range(), ))); } - checker.report_diagnostic(diagnostic); } /// SIM211 @@ -218,7 +217,7 @@ pub(crate) fn if_expr_with_false_true( return; } - let mut diagnostic = Diagnostic::new(IfExprWithFalseTrue, expr.range()); + let mut diagnostic = checker.report_diagnostic(IfExprWithFalseTrue, expr.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( checker.generator().expr( &ast::ExprUnaryOp { @@ -230,7 +229,6 @@ pub(crate) fn if_expr_with_false_true( ), expr.range(), ))); - checker.report_diagnostic(diagnostic); } /// SIM212 @@ -264,7 +262,7 @@ pub(crate) fn twisted_arms_in_ifexpr( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfExprWithTwistedArms { expr_body: checker.generator().expr(body), expr_else: checker.generator().expr(orelse), @@ -284,5 +282,4 @@ pub(crate) fn twisted_arms_in_ifexpr( checker.generator().expr(&node3.into()), expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_unary_op.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_unary_op.rs index 9667ebf2bf..b615c4d908 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_unary_op.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_unary_op.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Arguments, CmpOp, Expr, ExprContext, Stmt, UnaryOp}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_semantic::ScopeKind; @@ -173,7 +173,7 @@ pub(crate) fn negation_with_equal_op(checker: &Checker, expr: &Expr, op: UnaryOp } } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NegateEqualOp { left: checker.generator().expr(left), right: checker.generator().expr(&comparators[0]), @@ -190,7 +190,6 @@ pub(crate) fn negation_with_equal_op(checker: &Checker, expr: &Expr, op: UnaryOp checker.generator().expr(&node.into()), expr.range(), ))); - checker.report_diagnostic(diagnostic); } /// SIM202 @@ -228,7 +227,7 @@ pub(crate) fn negation_with_not_equal_op( } } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NegateNotEqualOp { left: checker.generator().expr(left), right: checker.generator().expr(&comparators[0]), @@ -245,7 +244,6 @@ pub(crate) fn negation_with_not_equal_op( checker.generator().expr(&node.into()), expr.range(), ))); - checker.report_diagnostic(diagnostic); } /// SIM208 @@ -265,7 +263,7 @@ pub(crate) fn double_negation(checker: &Checker, expr: &Expr, op: UnaryOp, opera return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DoubleNegation { expr: checker.generator().expr(operand), }, @@ -296,5 +294,4 @@ pub(crate) fn double_negation(checker: &Checker, expr: &Expr, op: UnaryOp, opera expr.range(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_with.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_with.rs index 0dca0aed22..06cd73d100 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_with.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_with.rs @@ -1,7 +1,7 @@ use anyhow::bail; use ast::Expr; -use ruff_diagnostics::{Diagnostic, Fix}; +use ruff_diagnostics::Fix; use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Stmt, WithItem}; @@ -171,7 +171,7 @@ pub(crate) fn multiple_with_statements( return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MultipleWithStatements, TextRange::new(with_stmt.start(), colon.end()), ); @@ -208,6 +208,5 @@ pub(crate) fn multiple_with_statements( } }); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/collapsible_if.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/collapsible_if.rs index 3ba8c62775..fc590eaf58 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/collapsible_if.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/collapsible_if.rs @@ -3,7 +3,7 @@ use std::borrow::Cow; use anyhow::{Result, bail}; use libcst_native::ParenthesizedNode; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{self as ast, ElifElseClause, Expr, Stmt, whitespace}; @@ -107,7 +107,7 @@ pub(crate) fn nested_if_statements( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CollapsibleIf, TextRange::new(nested_if.start(), colon.end()), ); @@ -138,7 +138,6 @@ pub(crate) fn nested_if_statements( } }); } - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy)] diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/enumerate_for_loop.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/enumerate_for_loop.rs index 07e45e6e82..e3c66683b8 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/enumerate_for_loop.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/enumerate_for_loop.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; use ruff_python_ast::{self as ast, Expr, Int, Number, Operator, Stmt}; @@ -139,13 +139,12 @@ pub(crate) fn enumerate_for_loop(checker: &Checker, for_stmt: &ast::StmtFor) { continue; } - let diagnostic = Diagnostic::new( + checker.report_diagnostic( EnumerateForLoop { index: index.id.to_string(), }, stmt.range(), ); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_get.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_get.rs index d65085aae9..35b40b17d9 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_get.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_get.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::contains_effect; @@ -216,7 +216,7 @@ pub(crate) fn if_else_block_instead_of_dict_get(checker: &Checker, stmt_if: &ast return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfElseBlockInsteadOfDictGet { contents: contents.clone(), }, @@ -231,7 +231,6 @@ pub(crate) fn if_else_block_instead_of_dict_get(checker: &Checker, stmt_if: &ast stmt_if.range(), ))); } - checker.report_diagnostic(diagnostic); } /// SIM401 @@ -305,7 +304,7 @@ pub(crate) fn if_exp_instead_of_dict_get( let contents = checker.generator().expr(&fixed_node.into()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfElseBlockInsteadOfDictGet { contents: contents.clone(), }, @@ -320,5 +319,4 @@ pub(crate) fn if_exp_instead_of_dict_get( expr.range(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_lookup.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_lookup.rs index b1b4a384f4..55a2baee3e 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_lookup.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_lookup.rs @@ -1,6 +1,6 @@ use rustc_hash::FxHashSet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableLiteral; use ruff_python_ast::helpers::contains_effect; @@ -156,8 +156,5 @@ pub(crate) fn if_else_block_instead_of_dict_lookup(checker: &Checker, stmt_if: & return; } - checker.report_diagnostic(Diagnostic::new( - IfElseBlockInsteadOfDictLookup, - stmt_if.range(), - )); + checker.report_diagnostic(IfElseBlockInsteadOfDictLookup, stmt_if.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_if_exp.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_if_exp.rs index f8d8e7cd6d..278f7e9b26 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_if_exp.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_if_exp.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::contains_effect; @@ -233,7 +233,7 @@ pub(crate) fn if_else_block_instead_of_if_exp(checker: &Checker, stmt_if: &ast:: return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfElseBlockInsteadOfIfExp { contents: contents.clone(), kind: assignment_kind, @@ -249,7 +249,6 @@ pub(crate) fn if_else_block_instead_of_if_exp(checker: &Checker, stmt_if: &ast:: stmt_if.range(), ))); } - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_with_same_arms.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_with_same_arms.rs index ab59e87955..76fa1d5ef0 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/if_with_same_arms.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/if_with_same_arms.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableStmt; use ruff_python_ast::parenthesize::parenthesized_range; @@ -87,7 +87,7 @@ pub(crate) fn if_with_same_arms(checker: &Checker, stmt_if: &ast::StmtIf) { continue; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfWithSameArms, TextRange::new(current_branch.start(), following_branch.end()), ); @@ -101,8 +101,6 @@ pub(crate) fn if_with_same_arms(checker: &Checker, stmt_if: &ast::StmtIf) { checker.comment_ranges(), ) }); - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/key_in_dict.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/key_in_dict.rs index 9a2b32e7ea..5a21b7a9da 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/key_in_dict.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/key_in_dict.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_diagnostics::{Applicability, Edit}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::AnyNodeRef; @@ -103,7 +103,7 @@ fn key_in_dict(checker: &Checker, left: &Expr, right: &Expr, operator: CmpOp, pa ) .unwrap_or(right.range()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( InDictKeys { operator: operator.as_str().to_string(), }, @@ -158,7 +158,6 @@ fn key_in_dict(checker: &Checker, left: &Expr, right: &Expr, operator: CmpOp, pa )); } } - checker.report_diagnostic(diagnostic); } /// SIM118 in a `for` loop. diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/needless_bool.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/needless_bool.rs index 427561c767..40c5cc9f5a 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/needless_bool.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/needless_bool.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::traversal; @@ -305,7 +305,7 @@ pub(crate) fn needless_bool(checker: &Checker, stmt: &Stmt) { .as_ref() .map(|expr| checker.generator().expr(expr)); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NeedlessBool { condition: condition.map(SourceCodeSnippet::new), negate: inverted, @@ -318,7 +318,6 @@ pub(crate) fn needless_bool(checker: &Checker, stmt: &Stmt) { range, ))); } - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs index e46086f1fc..3c664654e6 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{ScopeKind, SemanticModel}; use ruff_text_size::Ranged; @@ -265,8 +265,5 @@ pub(crate) fn open_file_with_context_handler(checker: &Checker, call: &ast::Expr } } - checker.report_diagnostic(Diagnostic::new( - OpenFileWithContextHandler, - call.func.range(), - )); + checker.report_diagnostic(OpenFileWithContextHandler, call.func.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs index 4530751a69..c021a8ca0c 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; use ruff_python_ast::name::Name; @@ -111,7 +111,7 @@ pub(crate) fn convert_for_loop_to_any_all(checker: &Checker, stmt: &Stmt) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ReimplementedBuiltin { replacement: contents.to_string(), }, @@ -124,7 +124,6 @@ pub(crate) fn convert_for_loop_to_any_all(checker: &Checker, stmt: &Stmt) { terminal.stmt.end(), ))); } - checker.report_diagnostic(diagnostic); } // Replace with `all`. (false, true) => { @@ -203,7 +202,7 @@ pub(crate) fn convert_for_loop_to_any_all(checker: &Checker, stmt: &Stmt) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ReimplementedBuiltin { replacement: contents.to_string(), }, @@ -216,7 +215,6 @@ pub(crate) fn convert_for_loop_to_any_all(checker: &Checker, stmt: &Stmt) { terminal.stmt.end(), ))); } - checker.report_diagnostic(diagnostic); } _ => {} } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs index b050859cec..707e9b3ad9 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -69,10 +69,7 @@ pub(crate) fn return_in_try_except_finally( if try_has_return || except_has_return { if let Some(finally_return) = find_return(finalbody) { - checker.report_diagnostic(Diagnostic::new( - ReturnInTryExceptFinally, - finally_return.range(), - )); + checker.report_diagnostic(ReturnInTryExceptFinally, finally_return.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/split_static_string.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/split_static_string.rs index 1e1d9aefca..780d985b47 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/split_static_string.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/split_static_string.rs @@ -1,6 +1,6 @@ use std::cmp::Ordering; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ Expr, ExprCall, ExprContext, ExprList, ExprUnaryOp, StringLiteral, StringLiteralFlags, @@ -102,7 +102,7 @@ pub(crate) fn split_static_string( split_default(str_value, maxsplit_value, direction) }; - let mut diagnostic = Diagnostic::new(SplitStaticString, call.range()); + let mut diagnostic = checker.report_diagnostic(SplitStaticString, call.range()); if let Some(ref replacement_expr) = split_replacement { diagnostic.set_fix(Fix::applicable_edit( Edit::range_replacement(checker.generator().expr(replacement_expr), call.range()), @@ -114,7 +114,6 @@ pub(crate) fn split_static_string( }, )); } - checker.report_diagnostic(diagnostic); } fn construct_replacement(elts: &[&str], flags: StringLiteralFlags) -> Expr { diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/suppressible_exception.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/suppressible_exception.rs index c0a59746fd..03d01cc898 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/suppressible_exception.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/suppressible_exception.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers; use ruff_python_ast::name::UnqualifiedName; @@ -120,7 +120,7 @@ pub(crate) fn suppressible_exception( handler_names.join(", ") }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( SuppressibleException { exception: exception.clone(), }, @@ -147,5 +147,4 @@ pub(crate) fn suppressible_exception( )) }); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/yoda_conditions.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/yoda_conditions.rs index 7f0760073d..f741bbeb14 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/yoda_conditions.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/yoda_conditions.rs @@ -3,7 +3,7 @@ use std::cmp; use anyhow::Result; use libcst_native::CompOp; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr, UnaryOp}; use ruff_python_codegen::Stylist; @@ -225,7 +225,7 @@ pub(crate) fn yoda_conditions( } if let Ok(suggestion) = reverse_comparison(expr, checker.locator(), checker.stylist()) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( YodaConditions { suggestion: Some(SourceCodeSnippet::new(suggestion.clone())), }, @@ -235,11 +235,7 @@ pub(crate) fn yoda_conditions( pad(suggestion, expr.range(), checker.locator()), expr.range(), ))); - checker.report_diagnostic(diagnostic); } else { - checker.report_diagnostic(Diagnostic::new( - YodaConditions { suggestion: None }, - expr.range(), - )); + checker.report_diagnostic(YodaConditions { suggestion: None }, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/zip_dict_keys_and_values.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/zip_dict_keys_and_values.rs index 375276306a..31dbcf7266 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/zip_dict_keys_and_values.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/zip_dict_keys_and_values.rs @@ -4,7 +4,7 @@ use ruff_python_ast::{self as ast, Arguments, Expr}; use ruff_text_size::Ranged; use crate::{checkers::ast::Checker, fix::snippet::SourceCodeSnippet}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_python_semantic::analyze::typing::is_dict; /// ## What it does @@ -104,7 +104,7 @@ pub(crate) fn zip_dict_keys_and_values(checker: &Checker, expr: &ast::ExprCall) let expected = format!("{}.items()", checker.locator().slice(var1)); let actual = checker.locator().slice(expr); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ZipDictKeysAndValues { expected: SourceCodeSnippet::new(expected.clone()), actual: SourceCodeSnippet::from_str(actual), @@ -115,7 +115,6 @@ pub(crate) fn zip_dict_keys_and_values(checker: &Checker, expr: &ast::ExprCall) expected, expr.range(), ))); - checker.report_diagnostic(diagnostic); } fn get_var_attr(expr: &Expr) -> Option<(&ExprName, &Identifier)> { diff --git a/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_namedtuple_subclass.rs b/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_namedtuple_subclass.rs index 1433439578..b10f8473d1 100644 --- a/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_namedtuple_subclass.rs +++ b/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_namedtuple_subclass.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr, Stmt, StmtClassDef, identifier::Identifier}; use ruff_python_semantic::SemanticModel; @@ -88,10 +88,10 @@ pub(crate) fn no_slots_in_namedtuple_subclass( if let Some(namedtuple_kind) = namedtuple_base(bases, checker.semantic()) { if !has_slots(&class.body) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NoSlotsInNamedtupleSubclass(namedtuple_kind), stmt.identifier(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_str_subclass.rs b/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_str_subclass.rs index c033850648..3603db1709 100644 --- a/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_str_subclass.rs +++ b/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_str_subclass.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::{Arguments, Expr, Stmt, StmtClassDef}; @@ -73,7 +73,7 @@ pub(crate) fn no_slots_in_str_subclass(checker: &Checker, stmt: &Stmt, class: &S return; } - checker.report_diagnostic(Diagnostic::new(NoSlotsInStrSubclass, stmt.identifier())); + checker.report_diagnostic(NoSlotsInStrSubclass, stmt.identifier()); } /// Return `true` if the class is a subclass of `str`. diff --git a/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_tuple_subclass.rs b/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_tuple_subclass.rs index 3c8b561843..c95db4be11 100644 --- a/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_tuple_subclass.rs +++ b/crates/ruff_linter/src/rules/flake8_slots/rules/no_slots_in_tuple_subclass.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Arguments, Stmt, StmtClassDef}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::identifier::Identifier; @@ -66,7 +66,7 @@ pub(crate) fn no_slots_in_tuple_subclass(checker: &Checker, stmt: &Stmt, class: semantic.match_builtin_expr(base, "tuple") || semantic.match_typing_expr(base, "Tuple") }) { if !has_slots(&class.body) { - checker.report_diagnostic(Diagnostic::new(NoSlotsInTupleSubclass, stmt.identifier())); + checker.report_diagnostic(NoSlotsInTupleSubclass, stmt.identifier()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_api.rs b/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_api.rs index 05cc14b992..9c65b36a83 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_api.rs +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_api.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_text_size::Ranged; @@ -43,13 +43,13 @@ pub(crate) fn banned_api(checker: &Checker, policy: &NameMatchPolicy, let banned_api = &checker.settings.flake8_tidy_imports.banned_api; if let Some(banned_module) = policy.find(banned_api.keys().map(AsRef::as_ref)) { if let Some(reason) = banned_api.get(&banned_module) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BannedApi { name: banned_module, message: reason.msg.to_string(), }, node.range(), - )); + ); } } } @@ -71,12 +71,12 @@ pub(crate) fn banned_attribute_access(checker: &Checker, expr: &Expr) { }) }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BannedApi { name: banned_path.to_string(), message: ban.msg.to_string(), }, expr.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_module_level_imports.rs b/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_module_level_imports.rs index cc6d47776d..dee32f1831 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_module_level_imports.rs +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/banned_module_level_imports.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::resolve_imported_module_path; use ruff_python_ast::{Alias, AnyNodeRef, Stmt, StmtImport, StmtImportFrom}; @@ -68,12 +68,12 @@ pub(crate) fn banned_module_level_imports(checker: &Checker, stmt: &Stmt) { .flake8_tidy_imports .banned_module_level_imports(), ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BannedModuleLevelImports { name: banned_module, }, node.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/relative_imports.rs b/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/relative_imports.rs index de8dfa69fc..f181a894c7 100644 --- a/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/relative_imports.rs +++ b/crates/ruff_linter/src/rules/flake8_tidy_imports/rules/relative_imports.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Identifier, Stmt}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::resolve_imported_module_path; use ruff_python_codegen::Generator; @@ -117,20 +117,18 @@ pub(crate) fn banned_relative_import( module: Option<&str>, module_path: Option<&[String]>, strictness: Strictness, -) -> Option { +) { let strictness_level = match strictness { Strictness::All => 0, Strictness::Parents => 1, }; if level > strictness_level { - let mut diagnostic = Diagnostic::new(RelativeImports { strictness }, stmt.range()); + let mut diagnostic = + checker.report_diagnostic(RelativeImports { strictness }, stmt.range()); if let Some(fix) = fix_banned_relative_import(stmt, level, module, module_path, checker.generator()) { diagnostic.set_fix(fix); } - Some(diagnostic) - } else { - None } } diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs b/crates/ruff_linter/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs index 54da378b8a..11f11825a6 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs +++ b/crates/ruff_linter/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs @@ -1,6 +1,6 @@ use ruff_python_ast as ast; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::typing; use ruff_text_size::Ranged; @@ -63,7 +63,7 @@ pub(crate) fn empty_type_checking_block(checker: &Checker, stmt: &ast::StmtIf) { return; } - let mut diagnostic = Diagnostic::new(EmptyTypeCheckingBlock, stmt.range()); + let mut diagnostic = checker.report_diagnostic(EmptyTypeCheckingBlock, stmt.range()); // Delete the entire type-checking block. let stmt = checker.semantic().current_statement(); let parent = checker.semantic().current_statement_parent(); @@ -71,5 +71,4 @@ pub(crate) fn empty_type_checking_block(checker: &Checker, stmt: &ast::StmtIf) { diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_parent_id(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_cast_value.rs b/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_cast_value.rs index ec6ffee598..5dbb249f7c 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_cast_value.rs +++ b/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_cast_value.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -62,7 +62,7 @@ pub(crate) fn runtime_cast_value(checker: &Checker, type_expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new(RuntimeCastValue, type_expr.range()); + let mut diagnostic = checker.report_diagnostic(RuntimeCastValue, type_expr.range()); let edit = quote_type_expression( type_expr, checker.semantic(), @@ -75,5 +75,4 @@ pub(crate) fn runtime_cast_value(checker: &Checker, type_expr: &Expr) { } else { diagnostic.set_fix(Fix::safe_edit(edit)); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs b/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs index dc3b337984..1d9cb39e08 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs +++ b/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs @@ -3,7 +3,7 @@ use std::borrow::Cow; use anyhow::Result; use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Imported, NodeId, Scope, ScopeId}; use ruff_text_size::Ranged; @@ -198,7 +198,7 @@ pub(crate) fn runtime_import_in_type_checking_block(checker: &Checker, scope: &S .. } in imports { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RuntimeImportInTypeCheckingBlock { qualified_name: import.qualified_name().to_string(), strategy: Strategy::MoveImport, @@ -211,7 +211,6 @@ pub(crate) fn runtime_import_in_type_checking_block(checker: &Checker, scope: &S if let Some(fix) = fix.as_ref() { diagnostic.set_fix(fix.clone()); } - checker.report_diagnostic(diagnostic); } } @@ -227,7 +226,7 @@ pub(crate) fn runtime_import_in_type_checking_block(checker: &Checker, scope: &S .. } in imports { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RuntimeImportInTypeCheckingBlock { qualified_name: import.qualified_name().to_string(), strategy: Strategy::QuoteUsages, @@ -238,7 +237,6 @@ pub(crate) fn runtime_import_in_type_checking_block(checker: &Checker, scope: &S diagnostic.set_parent(range.start()); } diagnostic.set_fix(fix.clone()); - checker.report_diagnostic(diagnostic); } } @@ -252,7 +250,7 @@ pub(crate) fn runtime_import_in_type_checking_block(checker: &Checker, scope: &S .. } in imports { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RuntimeImportInTypeCheckingBlock { qualified_name: import.qualified_name().to_string(), strategy: Strategy::MoveImport, @@ -262,7 +260,6 @@ pub(crate) fn runtime_import_in_type_checking_block(checker: &Checker, scope: &S if let Some(range) = parent_range { diagnostic.set_parent(range.start()); } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_string_union.rs b/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_string_union.rs index d5142b6dbe..42ac5c1b91 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_string_union.rs +++ b/crates/ruff_linter/src/rules/flake8_type_checking/rules/runtime_string_union.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::{Expr, Operator}; @@ -66,7 +66,7 @@ pub(crate) fn runtime_string_union(checker: &Checker, expr: &Expr) { traverse_op(expr, &mut strings); for string in strings { - checker.report_diagnostic(Diagnostic::new(RuntimeStringUnion, string.range())); + checker.report_diagnostic(RuntimeStringUnion, string.range()); } } 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 3f0572aa63..f478fda4c9 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 @@ -1,5 +1,5 @@ use ast::{ExprContext, Operator}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::{Expr, Stmt}; @@ -179,11 +179,9 @@ pub(crate) fn unquoted_type_alias(checker: &Checker, binding: &Binding) { checker.default_string_flags(), ); for name in names { - checker.report_diagnostic( - Diagnostic::new(UnquotedTypeAlias, name.range()) - .with_parent(parent) - .with_fix(Fix::unsafe_edit(edit.clone())), - ); + let mut diagnostic = checker.report_diagnostic(UnquotedTypeAlias, name.range()); + diagnostic.set_parent(parent); + diagnostic.set_fix(Fix::unsafe_edit(edit.clone())); } } @@ -288,14 +286,13 @@ pub(crate) fn quoted_type_alias( } let range = annotation_expr.range(); - let mut diagnostic = Diagnostic::new(QuotedTypeAlias, range); + let mut diagnostic = checker.report_diagnostic(QuotedTypeAlias, range); let edit = Edit::range_replacement(annotation_expr.value.to_string(), range); if checker.comment_ranges().intersects(range) { diagnostic.set_fix(Fix::unsafe_edit(edit)); } else { diagnostic.set_fix(Fix::safe_edit(edit)); } - checker.report_diagnostic(diagnostic); } /// Traverses the type expression and checks if the expression can safely 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 61aaa0f344..d4a183e905 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 @@ -3,12 +3,12 @@ use std::borrow::Cow; use anyhow::Result; use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Binding, Imported, NodeId, Scope}; use ruff_text_size::{Ranged, TextRange}; -use crate::checkers::ast::Checker; +use crate::checkers::ast::{Checker, DiagnosticGuard}; use crate::codes::Rule; use crate::fix; use crate::importer::ImportedMembers; @@ -393,15 +393,18 @@ pub(crate) fn typing_only_runtime_import( .. } in imports { - let mut diagnostic = - diagnostic_for(import_type, import.qualified_name().to_string(), range); + let mut diagnostic = diagnostic_for( + checker, + import_type, + import.qualified_name().to_string(), + range, + ); if let Some(range) = parent_range { diagnostic.set_parent(range.start()); } if let Some(fix) = fix.as_ref() { diagnostic.set_fix(fix.clone()); } - checker.report_diagnostic(diagnostic); } } @@ -415,12 +418,15 @@ pub(crate) fn typing_only_runtime_import( .. } in imports { - let mut diagnostic = - diagnostic_for(import_type, import.qualified_name().to_string(), range); + let mut diagnostic = diagnostic_for( + checker, + import_type, + import.qualified_name().to_string(), + range, + ); if let Some(range) = parent_range { diagnostic.set_parent(range.start()); } - checker.report_diagnostic(diagnostic); } } } @@ -436,16 +442,21 @@ fn rule_for(import_type: ImportType) -> Rule { } /// Return the [`Diagnostic`] for the given import type. -fn diagnostic_for(import_type: ImportType, qualified_name: String, range: TextRange) -> Diagnostic { +fn diagnostic_for<'a, 'b>( + checker: &'a Checker<'b>, + import_type: ImportType, + qualified_name: String, + range: TextRange, +) -> DiagnosticGuard<'a, 'b> { match import_type { ImportType::StandardLibrary => { - Diagnostic::new(TypingOnlyStandardLibraryImport { qualified_name }, range) + checker.report_diagnostic(TypingOnlyStandardLibraryImport { qualified_name }, range) } ImportType::ThirdParty => { - Diagnostic::new(TypingOnlyThirdPartyImport { qualified_name }, range) + checker.report_diagnostic(TypingOnlyThirdPartyImport { qualified_name }, range) } ImportType::FirstParty => { - Diagnostic::new(TypingOnlyFirstPartyImport { qualified_name }, range) + checker.report_diagnostic(TypingOnlyFirstPartyImport { qualified_name }, range) } _ => unreachable!("Unexpected import type"), } 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 d1216ba670..b6ef9c1549 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 @@ -1,7 +1,7 @@ use ruff_python_ast as ast; use ruff_python_ast::{Parameter, Parameters, Stmt, StmtExpr, StmtFunctionDef, StmtRaise}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::{function_type, visibility}; use ruff_python_semantic::{Scope, ScopeKind, SemanticModel}; @@ -222,14 +222,18 @@ enum Argumentable { } impl Argumentable { - fn check_for(self, name: String, range: TextRange) -> Diagnostic { + fn check_for(self, checker: &Checker, name: String, range: TextRange) { match self { - Self::Function => Diagnostic::new(UnusedFunctionArgument { name }, range), - Self::Method => Diagnostic::new(UnusedMethodArgument { name }, range), - Self::ClassMethod => Diagnostic::new(UnusedClassMethodArgument { name }, range), - Self::StaticMethod => Diagnostic::new(UnusedStaticMethodArgument { name }, range), - Self::Lambda => Diagnostic::new(UnusedLambdaArgument { name }, range), - } + Self::Function => checker.report_diagnostic(UnusedFunctionArgument { name }, range), + Self::Method => checker.report_diagnostic(UnusedMethodArgument { name }, range), + Self::ClassMethod => { + checker.report_diagnostic(UnusedClassMethodArgument { name }, range) + } + Self::StaticMethod => { + checker.report_diagnostic(UnusedStaticMethodArgument { name }, range) + } + Self::Lambda => checker.report_diagnostic(UnusedLambdaArgument { name }, range), + }; } const fn rule_code(self) -> Rule { @@ -315,8 +319,7 @@ fn call<'a>( && binding.is_unused() && !dummy_variable_rgx.is_match(arg.name()) { - checker - .report_diagnostic(argumentable.check_for(arg.name.to_string(), binding.range())); + argumentable.check_for(checker, arg.name.to_string(), binding.range()); } } } diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/invalid_pathlib_with_suffix.rs b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/invalid_pathlib_with_suffix.rs index a3afa9374c..167700d37e 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/invalid_pathlib_with_suffix.rs +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/invalid_pathlib_with_suffix.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, StringFlags}; use ruff_python_semantic::SemanticModel; @@ -108,7 +108,8 @@ pub(crate) fn invalid_pathlib_with_suffix(checker: &Checker, call: &ast::ExprCal }; let single_dot = string_value == "."; - let mut diagnostic = Diagnostic::new(InvalidPathlibWithSuffix { single_dot }, call.range); + let mut diagnostic = + checker.report_diagnostic(InvalidPathlibWithSuffix { single_dot }, call.range); if !single_dot { let after_leading_quote = string.start() + first_part.flags.opener_len(); diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( @@ -116,8 +117,6 @@ pub(crate) fn invalid_pathlib_with_suffix(checker: &Checker, call: &ast::ExprCal after_leading_quote, ))); } - - checker.report_diagnostic(diagnostic); } fn is_path_with_suffix_call(semantic: &SemanticModel, func: &ast::Expr) -> bool { diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_sep_split.rs b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_sep_split.rs index 27d74c80cb..a35ca49b53 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_sep_split.rs +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_sep_split.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprAttribute}; use ruff_python_semantic::Modules; @@ -94,5 +94,5 @@ pub(crate) fn os_sep_split(checker: &Checker, call: &ast::ExprCall) { return; } - checker.report_diagnostic(Diagnostic::new(OsSepSplit, attr.range())); + checker.report_diagnostic(OsSepSplit, attr.range()); } diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/path_constructor_current_directory.rs b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/path_constructor_current_directory.rs index e7c3a75fd4..a9475bf6bf 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/path_constructor_current_directory.rs +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/path_constructor_current_directory.rs @@ -1,6 +1,6 @@ use std::ops::Range; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{Expr, ExprBinOp, ExprCall, Operator}; @@ -83,7 +83,7 @@ pub(crate) fn path_constructor_current_directory(checker: &Checker, call: &ExprC return; } - let mut diagnostic = Diagnostic::new(PathConstructorCurrentDirectory, arg.range()); + let mut diagnostic = checker.report_diagnostic(PathConstructorCurrentDirectory, arg.range()); match parent_and_next_path_fragment_range( checker.semantic(), @@ -111,8 +111,6 @@ pub(crate) fn path_constructor_current_directory(checker: &Checker, call: &ExprC Ok(Fix::applicable_edit(edit, applicability(call.range()))) }), } - - checker.report_diagnostic(diagnostic); } fn parent_and_next_path_fragment_range( diff --git a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/replaceable_by_pathlib.rs b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/replaceable_by_pathlib.rs index 243729c70f..ec64457fae 100644 --- a/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/replaceable_by_pathlib.rs +++ b/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/replaceable_by_pathlib.rs @@ -1,11 +1,9 @@ -use ruff_diagnostics::Diagnostic; use ruff_python_ast::{self as ast, Expr, ExprBooleanLiteral, ExprCall}; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::typing; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; -use crate::registry::AsRule; use crate::rules::flake8_use_pathlib::rules::{ Glob, OsPathGetatime, OsPathGetctime, OsPathGetmtime, OsPathGetsize, }; @@ -23,9 +21,9 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { }; let range = call.func.range(); - let diagnostic = match qualified_name.segments() { + match qualified_name.segments() { // PTH100 - ["os", "path", "abspath"] => Diagnostic::new(OsPathAbspath, range), + ["os", "path", "abspath"] => checker.report_diagnostic_if_enabled(OsPathAbspath, range), // PTH101 ["os", "chmod"] => { // `dir_fd` is not supported by pathlib, so check if it's set to non-default values. @@ -42,10 +40,10 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { { return; } - Diagnostic::new(OsChmod, range) + checker.report_diagnostic_if_enabled(OsChmod, range) } // PTH102 - ["os", "makedirs"] => Diagnostic::new(OsMakedirs, range), + ["os", "makedirs"] => checker.report_diagnostic_if_enabled(OsMakedirs, range), // PTH103 ["os", "mkdir"] => { // `dir_fd` is not supported by pathlib, so check if it's set to non-default values. @@ -57,7 +55,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { return; } - Diagnostic::new(OsMkdir, range) + checker.report_diagnostic_if_enabled(OsMkdir, range) } // PTH104 ["os", "rename"] => { @@ -73,7 +71,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { { return; } - Diagnostic::new(OsRename, range) + checker.report_diagnostic_if_enabled(OsRename, range) } // PTH105 ["os", "replace"] => { @@ -89,7 +87,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { { return; } - Diagnostic::new(OsReplace, range) + checker.report_diagnostic_if_enabled(OsReplace, range) } // PTH106 ["os", "rmdir"] => { @@ -102,7 +100,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { return; } - Diagnostic::new(OsRmdir, range) + checker.report_diagnostic_if_enabled(OsRmdir, range) } // PTH107 ["os", "remove"] => { @@ -115,7 +113,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { return; } - Diagnostic::new(OsRemove, range) + checker.report_diagnostic_if_enabled(OsRemove, range) } // PTH108 ["os", "unlink"] => { @@ -128,21 +126,23 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { return; } - Diagnostic::new(OsUnlink, range) + checker.report_diagnostic_if_enabled(OsUnlink, range) } // PTH109 - ["os", "getcwd"] => Diagnostic::new(OsGetcwd, range), - ["os", "getcwdb"] => Diagnostic::new(OsGetcwd, range), + ["os", "getcwd"] => checker.report_diagnostic_if_enabled(OsGetcwd, range), + ["os", "getcwdb"] => checker.report_diagnostic_if_enabled(OsGetcwd, range), // PTH110 - ["os", "path", "exists"] => Diagnostic::new(OsPathExists, range), + ["os", "path", "exists"] => checker.report_diagnostic_if_enabled(OsPathExists, range), // PTH111 - ["os", "path", "expanduser"] => Diagnostic::new(OsPathExpanduser, range), + ["os", "path", "expanduser"] => { + checker.report_diagnostic_if_enabled(OsPathExpanduser, range) + } // PTH112 - ["os", "path", "isdir"] => Diagnostic::new(OsPathIsdir, range), + ["os", "path", "isdir"] => checker.report_diagnostic_if_enabled(OsPathIsdir, range), // PTH113 - ["os", "path", "isfile"] => Diagnostic::new(OsPathIsfile, range), + ["os", "path", "isfile"] => checker.report_diagnostic_if_enabled(OsPathIsfile, range), // PTH114 - ["os", "path", "islink"] => Diagnostic::new(OsPathIslink, range), + ["os", "path", "islink"] => checker.report_diagnostic_if_enabled(OsPathIslink, range), // PTH116 ["os", "stat"] => { // `dir_fd` is not supported by pathlib, so check if it's set to non-default values. @@ -159,12 +159,12 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { { return; } - Diagnostic::new(OsStat, range) + checker.report_diagnostic_if_enabled(OsStat, range) } // PTH117 - ["os", "path", "isabs"] => Diagnostic::new(OsPathIsabs, range), + ["os", "path", "isabs"] => checker.report_diagnostic_if_enabled(OsPathIsabs, range), // PTH118 - ["os", "path", "join"] => Diagnostic::new( + ["os", "path", "join"] => checker.report_diagnostic_if_enabled( OsPathJoin { module: "path".to_string(), joiner: if call.arguments.args.iter().any(Expr::is_starred_expr) { @@ -175,7 +175,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { }, range, ), - ["os", "sep", "join"] => Diagnostic::new( + ["os", "sep", "join"] => checker.report_diagnostic_if_enabled( OsPathJoin { module: "sep".to_string(), joiner: if call.arguments.args.iter().any(Expr::is_starred_expr) { @@ -187,21 +187,21 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { range, ), // PTH119 - ["os", "path", "basename"] => Diagnostic::new(OsPathBasename, range), + ["os", "path", "basename"] => checker.report_diagnostic_if_enabled(OsPathBasename, range), // PTH120 - ["os", "path", "dirname"] => Diagnostic::new(OsPathDirname, range), + ["os", "path", "dirname"] => checker.report_diagnostic_if_enabled(OsPathDirname, range), // PTH121 - ["os", "path", "samefile"] => Diagnostic::new(OsPathSamefile, range), + ["os", "path", "samefile"] => checker.report_diagnostic_if_enabled(OsPathSamefile, range), // PTH122 - ["os", "path", "splitext"] => Diagnostic::new(OsPathSplitext, range), + ["os", "path", "splitext"] => checker.report_diagnostic_if_enabled(OsPathSplitext, range), // PTH202 - ["os", "path", "getsize"] => Diagnostic::new(OsPathGetsize, range), + ["os", "path", "getsize"] => checker.report_diagnostic_if_enabled(OsPathGetsize, range), // PTH203 - ["os", "path", "getatime"] => Diagnostic::new(OsPathGetatime, range), + ["os", "path", "getatime"] => checker.report_diagnostic_if_enabled(OsPathGetatime, range), // PTH204 - ["os", "path", "getmtime"] => Diagnostic::new(OsPathGetmtime, range), + ["os", "path", "getmtime"] => checker.report_diagnostic_if_enabled(OsPathGetmtime, range), // PTH205 - ["os", "path", "getctime"] => Diagnostic::new(OsPathGetctime, range), + ["os", "path", "getctime"] => checker.report_diagnostic_if_enabled(OsPathGetctime, range), // PTH211 ["os", "symlink"] => { // `dir_fd` is not supported by pathlib, so check if there are non-default values. @@ -213,7 +213,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { return; } - Diagnostic::new(OsSymlink, range) + checker.report_diagnostic_if_enabled(OsSymlink, range) } // PTH123 @@ -250,10 +250,10 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { { return; } - Diagnostic::new(BuiltinOpen, range) + checker.report_diagnostic_if_enabled(BuiltinOpen, range) } // PTH124 - ["py", "path", "local"] => Diagnostic::new(PyPath, range), + ["py", "path", "local"] => checker.report_diagnostic_if_enabled(PyPath, range), // PTH207 ["glob", "glob"] => { // `dir_fd` is not supported by pathlib, so check if it's set to non-default values. @@ -266,7 +266,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { return; } - Diagnostic::new( + checker.report_diagnostic_if_enabled( Glob { function: "glob".to_string(), }, @@ -285,7 +285,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { return; } - Diagnostic::new( + checker.report_diagnostic_if_enabled( Glob { function: "iglob".to_string(), }, @@ -304,7 +304,7 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") { return; } - Diagnostic::new(OsReadlink, range) + checker.report_diagnostic_if_enabled(OsReadlink, range) } // PTH208 ["os", "listdir"] => { @@ -315,15 +315,11 @@ pub(crate) fn replaceable_by_pathlib(checker: &Checker, call: &ExprCall) { { return; } - Diagnostic::new(OsListdir, range) + checker.report_diagnostic_if_enabled(OsListdir, range) } _ => return, }; - - if checker.enabled(diagnostic.rule()) { - checker.report_diagnostic(diagnostic); - } } /// Returns `true` if the given expression looks like a file descriptor, i.e., if it is an integer. diff --git a/crates/ruff_linter/src/rules/flynt/rules/static_join_to_fstring.rs b/crates/ruff_linter/src/rules/flynt/rules/static_join_to_fstring.rs index 28f98da0b6..1af7fc68d9 100644 --- a/crates/ruff_linter/src/rules/flynt/rules/static_join_to_fstring.rs +++ b/crates/ruff_linter/src/rules/flynt/rules/static_join_to_fstring.rs @@ -2,7 +2,7 @@ use ast::FStringFlags; use itertools::Itertools; use crate::fix::edits::pad; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr}; use ruff_text_size::{Ranged, TextRange}; @@ -152,7 +152,7 @@ pub(crate) fn static_join_to_fstring(checker: &Checker, expr: &Expr, joiner: &st let contents = checker.generator().expr(&new_expr); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( StaticJoinToFString { expression: SourceCodeSnippet::new(contents.clone()), }, @@ -162,5 +162,4 @@ pub(crate) fn static_join_to_fstring(checker: &Checker, expr: &Expr, joiner: &st pad(contents, expr.range(), checker.locator()), expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs b/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs index ec5f371db7..b5c7ddd46a 100644 --- a/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs +++ b/crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs @@ -1,9 +1,11 @@ use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for functions with a high `McCabe` complexity. /// @@ -153,23 +155,22 @@ fn get_complexity_number(stmts: &[Stmt]) -> usize { } pub(crate) fn function_is_too_complex( + checker: &Checker, stmt: &Stmt, name: &str, body: &[Stmt], max_complexity: usize, -) -> Option { +) { let complexity = get_complexity_number(body) + 1; if complexity > max_complexity { - Some(Diagnostic::new( + checker.report_diagnostic( ComplexStructure { name: name.to_string(), complexity, max_complexity, }, stmt.identifier(), - )) - } else { - None + ); } } diff --git a/crates/ruff_linter/src/rules/numpy/rules/deprecated_function.rs b/crates/ruff_linter/src/rules/numpy/rules/deprecated_function.rs index 70a37fa4cc..03343ae61e 100644 --- a/crates/ruff_linter/src/rules/numpy/rules/deprecated_function.rs +++ b/crates/ruff_linter/src/rules/numpy/rules/deprecated_function.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::Modules; @@ -73,7 +73,7 @@ pub(crate) fn deprecated_function(checker: &Checker, expr: &Expr) { _ => None, }) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NumpyDeprecatedFunction { existing: existing.to_string(), replacement: replacement.to_string(), @@ -89,6 +89,5 @@ pub(crate) fn deprecated_function(checker: &Checker, expr: &Expr) { let replacement_edit = Edit::range_replacement(binding, expr.range()); Ok(Fix::safe_edits(import_edit, [replacement_edit])) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/numpy/rules/deprecated_type_alias.rs b/crates/ruff_linter/src/rules/numpy/rules/deprecated_type_alias.rs index f1b527fa5c..1b4225d185 100644 --- a/crates/ruff_linter/src/rules/numpy/rules/deprecated_type_alias.rs +++ b/crates/ruff_linter/src/rules/numpy/rules/deprecated_type_alias.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::Modules; @@ -74,7 +74,7 @@ pub(crate) fn deprecated_type_alias(checker: &Checker, expr: &Expr) { } }) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NumpyDeprecatedTypeAlias { type_name: type_name.to_string(), }, @@ -93,6 +93,5 @@ pub(crate) fn deprecated_type_alias(checker: &Checker, expr: &Expr) { let binding_edit = Edit::range_replacement(binding, expr.range()); Ok(Fix::safe_edits(binding_edit, import_edit)) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/numpy/rules/legacy_random.rs b/crates/ruff_linter/src/rules/numpy/rules/legacy_random.rs index f32f617c72..5317c3c2c7 100644 --- a/crates/ruff_linter/src/rules/numpy/rules/legacy_random.rs +++ b/crates/ruff_linter/src/rules/numpy/rules/legacy_random.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -137,11 +137,11 @@ pub(crate) fn legacy_random(checker: &Checker, expr: &Expr) { } }) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NumpyLegacyRandom { method_name: method_name.to_string(), }, expr.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/numpy/rules/numpy_2_0_deprecation.rs b/crates/ruff_linter/src/rules/numpy/rules/numpy_2_0_deprecation.rs index 6b74f97d72..254fdba264 100644 --- a/crates/ruff_linter/src/rules/numpy/rules/numpy_2_0_deprecation.rs +++ b/crates/ruff_linter/src/rules/numpy/rules/numpy_2_0_deprecation.rs @@ -1,5 +1,5 @@ use crate::rules::numpy::helpers::{AttributeSearcher, ImportSearcher}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedNameBuilder; use ruff_python_ast::statement_visitor::StatementVisitor; @@ -667,7 +667,7 @@ pub(crate) fn numpy_2_0_deprecation(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( Numpy2Deprecation { existing: replacement.existing.to_string(), migration_guide: replacement.details.guideline(), @@ -701,7 +701,6 @@ pub(crate) fn numpy_2_0_deprecation(checker: &Checker, expr: &Expr) { )), Details::Manual { guideline: _ } => {} } - checker.report_diagnostic(diagnostic); } /// Ignore attempts to access a `numpy` member via its deprecated name diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/assignment_to_df.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/assignment_to_df.rs index 2d8e63f3c4..c179fcb392 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/assignment_to_df.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/assignment_to_df.rs @@ -1,9 +1,11 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for assignments to the variable `df`. /// @@ -38,15 +40,15 @@ impl Violation for PandasDfVariableName { } /// PD901 -pub(crate) fn assignment_to_df(targets: &[Expr]) -> Option { +pub(crate) fn assignment_to_df(checker: &Checker, targets: &[Expr]) { let [target] = targets else { - return None; + return; }; let Expr::Name(ast::ExprName { id, .. }) = target else { - return None; + return; }; if id != "df" { - return None; + return; } - Some(Diagnostic::new(PandasDfVariableName, target.range())) + checker.report_diagnostic(PandasDfVariableName, target.range()); } diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/attr.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/attr.rs index dc63d78a32..7c95a0ca56 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/attr.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/attr.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; @@ -77,5 +77,5 @@ pub(crate) fn attr(checker: &Checker, attribute: &ast::ExprAttribute) { return; } - checker.report_diagnostic(Diagnostic::new(PandasUseOfDotValues, attribute.range())); + checker.report_diagnostic(PandasUseOfDotValues, attribute.range()); } 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 894fdf2b2c..86c5e600c9 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/call.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/call.rs @@ -1,6 +1,5 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -172,28 +171,6 @@ pub(crate) fn call(checker: &Checker, func: &Expr) { return; }; - let range = func.range(); - let diagnostic = match attr.as_str() { - "isnull" if checker.settings.rules.enabled(Rule::PandasUseOfDotIsNull) => { - Diagnostic::new(PandasUseOfDotIsNull, range) - } - "notnull" if checker.settings.rules.enabled(Rule::PandasUseOfDotNotNull) => { - Diagnostic::new(PandasUseOfDotNotNull, range) - } - "pivot" | "unstack" - if checker - .settings - .rules - .enabled(Rule::PandasUseOfDotPivotOrUnstack) => - { - Diagnostic::new(PandasUseOfDotPivotOrUnstack, range) - } - "stack" if checker.settings.rules.enabled(Rule::PandasUseOfDotStack) => { - Diagnostic::new(PandasUseOfDotStack, range) - } - _ => return, - }; - // Ignore irrelevant bindings (like imports). if !matches!( test_expression(value, checker.semantic()), @@ -202,5 +179,25 @@ pub(crate) fn call(checker: &Checker, func: &Expr) { return; } - checker.report_diagnostic(diagnostic); + let range = func.range(); + match attr.as_str() { + "isnull" if checker.settings.rules.enabled(Rule::PandasUseOfDotIsNull) => { + checker.report_diagnostic(PandasUseOfDotIsNull, range); + } + "notnull" if checker.settings.rules.enabled(Rule::PandasUseOfDotNotNull) => { + checker.report_diagnostic(PandasUseOfDotNotNull, range); + } + "pivot" | "unstack" + if checker + .settings + .rules + .enabled(Rule::PandasUseOfDotPivotOrUnstack) => + { + checker.report_diagnostic(PandasUseOfDotPivotOrUnstack, range); + } + "stack" if checker.settings.rules.enabled(Rule::PandasUseOfDotStack) => { + checker.report_diagnostic(PandasUseOfDotStack, range); + } + _ => {} + } } diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/inplace_argument.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/inplace_argument.rs index 9afc5818a9..46f74c79e8 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/inplace_argument.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/inplace_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::parenthesize::parenthesized_range; @@ -78,7 +78,8 @@ pub(crate) fn inplace_argument(checker: &Checker, call: &ast::ExprCall) { }; if arg == "inplace" { if is_const_true(&keyword.value) { - let mut diagnostic = Diagnostic::new(PandasUseOfInplaceArgument, keyword.range()); + let mut diagnostic = + checker.report_diagnostic(PandasUseOfInplaceArgument, keyword.range()); // Avoid applying the fix if: // 1. The keyword argument is followed by a star argument (we can't be certain that // the star argument _doesn't_ contain an override). @@ -99,8 +100,6 @@ pub(crate) fn inplace_argument(checker: &Checker, call: &ast::ExprCall) { diagnostic.set_fix(fix); } } - - checker.report_diagnostic(diagnostic); } // Duplicate keywords is a syntax error, so we can stop here. diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/nunique_constant_series_check.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/nunique_constant_series_check.rs index fefe0ed4a7..57e4ea7efb 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/nunique_constant_series_check.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/nunique_constant_series_check.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr, Int}; @@ -114,8 +113,5 @@ pub(crate) fn nunique_constant_series_check( return; } - checker.report_diagnostic(Diagnostic::new( - PandasNuniqueConstantSeriesCheck, - expr.range(), - )); + checker.report_diagnostic(PandasNuniqueConstantSeriesCheck, expr.range()); } diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/pd_merge.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/pd_merge.rs index e7cf969c38..569378888d 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/pd_merge.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/pd_merge.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr}; use crate::checkers::ast::Checker; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -63,7 +63,7 @@ pub(crate) fn use_of_pd_merge(checker: &Checker, func: &Expr) { if let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func { if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() { if id == "pd" && attr == "merge" { - checker.report_diagnostic(Diagnostic::new(PandasUseOfPdMerge, func.range())); + checker.report_diagnostic(PandasUseOfPdMerge, func.range()); } } } diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/read_table.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/read_table.rs index 29c1c9bef2..4353b58ae0 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/read_table.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/read_table.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::Expr; @@ -62,8 +62,7 @@ pub(crate) fn use_of_read_table(checker: &Checker, call: &ast::ExprCall) { .map(|keyword| &keyword.value) { if value == "," { - checker - .report_diagnostic(Diagnostic::new(PandasUseOfDotReadTable, call.func.range())); + checker.report_diagnostic(PandasUseOfDotReadTable, call.func.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 11fa079ade..efef6e806c 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs @@ -1,6 +1,5 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; @@ -152,21 +151,6 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, expr: &Expr) { return; }; - let range = expr.range(); - - let diagnostic = match attr.as_str() { - "ix" if checker.settings.rules.enabled(Rule::PandasUseOfDotIx) => { - Diagnostic::new(PandasUseOfDotIx, range) - } - "at" if checker.settings.rules.enabled(Rule::PandasUseOfDotAt) => { - Diagnostic::new(PandasUseOfDotAt, range) - } - "iat" if checker.settings.rules.enabled(Rule::PandasUseOfDotIat) => { - Diagnostic::new(PandasUseOfDotIat, range) - } - _ => return, - }; - // Avoid flagging on non-DataFrames (e.g., `{"a": 1}.at[0]`), and on irrelevant bindings // (like imports). if !matches!( @@ -176,5 +160,18 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, expr: &Expr) { return; } - checker.report_diagnostic(diagnostic); + let range = expr.range(); + + match attr.as_str() { + "ix" if checker.settings.rules.enabled(Rule::PandasUseOfDotIx) => { + checker.report_diagnostic(PandasUseOfDotIx, range) + } + "at" if checker.settings.rules.enabled(Rule::PandasUseOfDotAt) => { + checker.report_diagnostic(PandasUseOfDotAt, range) + } + "iat" if checker.settings.rules.enabled(Rule::PandasUseOfDotIat) => { + checker.report_diagnostic(PandasUseOfDotIat, range) + } + _ => return, + }; } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs index 6029af4f92..fe34a67ef3 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Alias, Stmt}; use ruff_python_stdlib::str::{self}; @@ -62,7 +62,7 @@ pub(crate) fn camelcase_imported_as_acronym( alias: &Alias, stmt: &Stmt, checker: &Checker, -) -> Option { +) { if helpers::is_camelcase(name) && !str::is_cased_lowercase(asname) && str::is_cased_uppercase(asname) @@ -72,15 +72,15 @@ pub(crate) fn camelcase_imported_as_acronym( // Ignore any explicitly-allowed names. if ignore_names.matches(name) || ignore_names.matches(asname) { - return None; + return; } // Ignore names that follow a community-agreed import convention. if is_ignored_because_of_import_convention(asname, stmt, alias, checker) { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CamelcaseImportedAsAcronym { name: name.to_string(), asname: asname.to_string(), @@ -88,9 +88,7 @@ pub(crate) fn camelcase_imported_as_acronym( alias.range(), ); diagnostic.set_parent(stmt.start()); - return Some(diagnostic); } - None } fn is_ignored_because_of_import_convention( diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs index afdfbfc307..0f6eff6425 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs @@ -1,10 +1,11 @@ use ruff_python_ast::{Alias, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_stdlib::str::{self}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; use crate::rules::pep8_naming::helpers; use crate::rules::pep8_naming::settings::IgnoreNames; @@ -65,14 +66,17 @@ impl Violation for CamelcaseImportedAsConstant { /// N814 pub(crate) fn camelcase_imported_as_constant( + checker: &Checker, name: &str, asname: &str, alias: &Alias, stmt: &Stmt, ignore_names: &IgnoreNames, -) -> Option { +) { // Single-character names are ambiguous. It could be a class or a constant. - asname.chars().nth(1)?; + if asname.chars().nth(1).is_none() { + return; + } if helpers::is_camelcase(name) && !str::is_cased_lowercase(asname) @@ -81,9 +85,9 @@ pub(crate) fn camelcase_imported_as_constant( { // Ignore any explicitly-allowed names. if ignore_names.matches(name) || ignore_names.matches(asname) { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CamelcaseImportedAsConstant { name: name.to_string(), asname: asname.to_string(), @@ -91,7 +95,5 @@ pub(crate) fn camelcase_imported_as_constant( alias.range(), ); diagnostic.set_parent(stmt.start()); - return Some(diagnostic); } - None } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs index f914183157..289e22755f 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs @@ -1,9 +1,10 @@ use ruff_python_ast::{Alias, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; use crate::rules::pep8_naming::helpers; use crate::rules::pep8_naming::settings::IgnoreNames; @@ -50,18 +51,19 @@ impl Violation for CamelcaseImportedAsLowercase { /// N813 pub(crate) fn camelcase_imported_as_lowercase( + checker: &Checker, name: &str, asname: &str, alias: &Alias, stmt: &Stmt, ignore_names: &IgnoreNames, -) -> Option { +) { if helpers::is_camelcase(name) && ruff_python_stdlib::str::is_cased_lowercase(asname) { // Ignore any explicitly-allowed names. if ignore_names.matches(name) || ignore_names.matches(asname) { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CamelcaseImportedAsLowercase { name: name.to_string(), asname: asname.to_string(), @@ -69,7 +71,5 @@ pub(crate) fn camelcase_imported_as_lowercase( alias.range(), ); diagnostic.set_parent(stmt.start()); - return Some(diagnostic); } - None } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs index d4eb7ee32f..df667f3ef5 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs @@ -1,10 +1,13 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Alias, Stmt}; use ruff_python_stdlib::str; use ruff_text_size::Ranged; -use crate::rules::pep8_naming::{helpers, settings::IgnoreNames}; +use crate::{ + checkers::ast::Checker, + rules::pep8_naming::{helpers, settings::IgnoreNames}, +}; /// ## What it does /// Checks for constant imports that are aliased to non-constant-style @@ -63,12 +66,13 @@ impl Violation for ConstantImportedAsNonConstant { /// N811 pub(crate) fn constant_imported_as_non_constant( + checker: &Checker, name: &str, asname: &str, alias: &Alias, stmt: &Stmt, ignore_names: &IgnoreNames, -) -> Option { +) { if str::is_cased_uppercase(name) && !(str::is_cased_uppercase(asname) // Single-character names are ambiguous. @@ -78,9 +82,9 @@ pub(crate) fn constant_imported_as_non_constant( { // Ignore any explicitly-allowed names. if ignore_names.matches(name) || ignore_names.matches(asname) { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ConstantImportedAsNonConstant { name: name.to_string(), asname: asname.to_string(), @@ -88,7 +92,5 @@ pub(crate) fn constant_imported_as_non_constant( alias.range(), ); diagnostic.set_parent(stmt.start()); - return Some(diagnostic); } - None } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/dunder_function_name.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/dunder_function_name.rs index 37748188fd..6ee2bc8af0 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/dunder_function_name.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/dunder_function_name.rs @@ -1,11 +1,12 @@ use ruff_python_ast::Stmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility; use ruff_python_semantic::{Scope, ScopeKind}; +use crate::checkers::ast::Checker; use crate::rules::pep8_naming::settings::IgnoreNames; /// ## What it does @@ -48,24 +49,25 @@ impl Violation for DunderFunctionName { /// N807 pub(crate) fn dunder_function_name( + checker: &Checker, scope: &Scope, stmt: &Stmt, name: &str, ignore_names: &IgnoreNames, -) -> Option { +) { if matches!(scope.kind, ScopeKind::Class(_)) { - return None; + return; } if !visibility::is_magic(name) { - return None; + return; } // Allowed under PEP 562 (https://peps.python.org/pep-0562/). if matches!(scope.kind, ScopeKind::Module) && (name == "__getattr__" || name == "__dir__") { - return None; + return; } // Ignore any explicitly-allowed names. if ignore_names.matches(name) { - return None; + return; } - Some(Diagnostic::new(DunderFunctionName, stmt.identifier())) + checker.report_diagnostic(DunderFunctionName, stmt.identifier()); } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs index 52b46b4636..2d8c4669e2 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs @@ -1,10 +1,10 @@ use ruff_python_ast::{self as ast, Arguments, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; -use crate::rules::pep8_naming::settings::IgnoreNames; +use crate::{checkers::ast::Checker, rules::pep8_naming::settings::IgnoreNames}; /// ## What it does /// Checks for custom exception definitions that omit the `Error` suffix. @@ -48,13 +48,14 @@ impl Violation for ErrorSuffixOnExceptionName { /// N818 pub(crate) fn error_suffix_on_exception_name( + checker: &Checker, class_def: &Stmt, arguments: Option<&Arguments>, name: &str, ignore_names: &IgnoreNames, -) -> Option { +) { if name.ends_with("Error") { - return None; + return; } if !arguments.is_some_and(|arguments| { @@ -66,18 +67,18 @@ pub(crate) fn error_suffix_on_exception_name( } }) }) { - return None; + return; } // Ignore any explicitly-allowed names. if ignore_names.matches(name) { - return None; + return; } - Some(Diagnostic::new( + checker.report_diagnostic( ErrorSuffixOnExceptionName { name: name.to_string(), }, class_def.identifier(), - )) + ); } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_argument_name.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_argument_name.rs index 31b5fe7195..604234982a 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_argument_name.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_argument_name.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ExprLambda, Parameters, StmtFunctionDef}; use ruff_python_semantic::ScopeKind; @@ -94,13 +94,11 @@ fn invalid_argument_name(checker: &Checker, parameters: &Parameters) { continue; } - let diagnostic = Diagnostic::new( + checker.report_diagnostic( InvalidArgumentName { name: name.to_string(), }, parameter.range(), ); - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_class_name.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_class_name.rs index 5db5bf0942..61d7ff3988 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_class_name.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_class_name.rs @@ -1,10 +1,10 @@ use ruff_python_ast::Stmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; -use crate::rules::pep8_naming::settings::IgnoreNames; +use crate::{checkers::ast::Checker, rules::pep8_naming::settings::IgnoreNames}; /// ## What it does /// Checks for class names that do not follow the `CamelCase` convention. @@ -54,22 +54,22 @@ impl Violation for InvalidClassName { /// N801 pub(crate) fn invalid_class_name( + checker: &Checker, class_def: &Stmt, name: &str, ignore_names: &IgnoreNames, -) -> Option { +) { let stripped = name.trim_start_matches('_'); if !stripped.chars().next().is_some_and(char::is_uppercase) || stripped.contains('_') { // Ignore any explicitly-allowed names. if ignore_names.matches(name) { - return None; + return; } - return Some(Diagnostic::new( + checker.report_diagnostic( InvalidClassName { name: name.to_string(), }, class_def.identifier(), - )); + ); } - None } 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 e8f42a9190..10a622de1e 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 @@ -1,6 +1,6 @@ use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Fix, Violation}; +use ruff_diagnostics::{Fix, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::ParameterWithDefault; @@ -10,7 +10,7 @@ use ruff_python_semantic::analyze::function_type; use ruff_python_semantic::{Scope, ScopeKind, SemanticModel}; use ruff_text_size::{Ranged, TextRange}; -use crate::checkers::ast::Checker; +use crate::checkers::ast::{Checker, DiagnosticGuard}; use crate::registry::Rule; use crate::renamer::Renamer; @@ -167,12 +167,16 @@ enum FunctionType { } impl FunctionType { - fn diagnostic_kind(self, argument_name: String, range: TextRange) -> Diagnostic { + fn diagnostic_kind<'a, 'b>( + self, + checker: &'a Checker<'b>, + argument_name: String, + range: TextRange, + ) -> DiagnosticGuard<'a, 'b> { match self { - Self::Method => { - Diagnostic::new(InvalidFirstArgumentNameForMethod { argument_name }, range) - } - Self::ClassMethod => Diagnostic::new( + Self::Method => checker + .report_diagnostic(InvalidFirstArgumentNameForMethod { argument_name }, range), + Self::ClassMethod => checker.report_diagnostic( InvalidFirstArgumentNameForClassMethod { argument_name, is_new: false, @@ -267,7 +271,7 @@ pub(crate) fn invalid_first_argument_name(checker: &Checker, scope: &Scope) { } let mut diagnostic = - function_type.diagnostic_kind(self_or_cls.name.to_string(), self_or_cls.range()); + function_type.diagnostic_kind(checker, self_or_cls.name.to_string(), self_or_cls.range()); diagnostic.try_set_optional_fix(|| { rename_parameter( scope, @@ -278,7 +282,6 @@ pub(crate) fn invalid_first_argument_name(checker: &Checker, scope: &Scope) { checker.stylist(), ) }); - checker.report_diagnostic(diagnostic); } /// Rename the first parameter to `self` or `cls`, if no other parameter has the target name. diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_function_name.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_function_name.rs index d50b986634..6618cbe3c8 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_function_name.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_function_name.rs @@ -1,12 +1,13 @@ use ruff_python_ast::{Decorator, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::visibility; use ruff_python_stdlib::str; +use crate::checkers::ast::Checker; use crate::rules::pep8_naming::settings::IgnoreNames; /// ## What it does @@ -57,15 +58,16 @@ impl Violation for InvalidFunctionName { /// N802 pub(crate) fn invalid_function_name( + checker: &Checker, stmt: &Stmt, name: &str, decorator_list: &[Decorator], ignore_names: &IgnoreNames, semantic: &SemanticModel, -) -> Option { +) { // Ignore any function names that are already lowercase. if str::is_lowercase(name) { - return None; + return; } // Ignore any functions that are explicitly `@override` or `@overload`. @@ -74,18 +76,18 @@ pub(crate) fn invalid_function_name( if visibility::is_override(decorator_list, semantic) || visibility::is_overload(decorator_list, semantic) { - return None; + return; } // Ignore any explicitly-allowed names. if ignore_names.matches(name) { - return None; + return; } - Some(Diagnostic::new( + checker.report_diagnostic( InvalidFunctionName { name: name.to_string(), }, stmt.identifier(), - )) + ); } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs index d1372dfe03..ad838b0bc5 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs @@ -1,10 +1,10 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Alias, Stmt}; use ruff_python_stdlib::str; use ruff_text_size::Ranged; -use crate::rules::pep8_naming::settings::IgnoreNames; +use crate::{checkers::ast::Checker, rules::pep8_naming::settings::IgnoreNames}; /// ## What it does /// Checks for lowercase imports that are aliased to non-lowercase names. @@ -49,19 +49,20 @@ impl Violation for LowercaseImportedAsNonLowercase { /// N812 pub(crate) fn lowercase_imported_as_non_lowercase( + checker: &Checker, name: &str, asname: &str, alias: &Alias, stmt: &Stmt, ignore_names: &IgnoreNames, -) -> Option { +) { if !str::is_cased_uppercase(name) && str::is_cased_lowercase(name) && !str::is_lowercase(asname) { // Ignore any explicitly-allowed names. if ignore_names.matches(name) || ignore_names.matches(asname) { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( LowercaseImportedAsNonLowercase { name: name.to_string(), asname: asname.to_string(), @@ -69,7 +70,5 @@ pub(crate) fn lowercase_imported_as_non_lowercase( alias.range(), ); diagnostic.set_parent(stmt.start()); - return Some(diagnostic); } - None } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs index a1ebfac616..8380762b5d 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -76,10 +76,10 @@ pub(crate) fn mixed_case_variable_in_class_scope( return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( MixedCaseVariableInClassScope { name: name.to_string(), }, expr.range(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs index fa2ee853ad..670e3fadbc 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -79,10 +79,10 @@ pub(crate) fn mixed_case_variable_in_global_scope(checker: &Checker, expr: &Expr return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( MixedCaseVariableInGlobalScope { name: name.to_string(), }, expr.range(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs index a0c495be27..efcf590837 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_stdlib::str; use ruff_text_size::Ranged; @@ -81,10 +81,10 @@ pub(crate) fn non_lowercase_variable_in_function(checker: &Checker, expr: &Expr, return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NonLowercaseVariableInFunction { name: name.to_string(), }, expr.range(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/perflint/rules/incorrect_dict_iterator.rs b/crates/ruff_linter/src/rules/perflint/rules/incorrect_dict_iterator.rs index 5343a0416b..ed7710ffb6 100644 --- a/crates/ruff_linter/src/rules/perflint/rules/incorrect_dict_iterator.rs +++ b/crates/ruff_linter/src/rules/perflint/rules/incorrect_dict_iterator.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::{Arguments, Expr}; @@ -99,7 +99,7 @@ pub(crate) fn incorrect_dict_iterator(checker: &Checker, stmt_for: &ast::StmtFor } (true, false) => { // The key is unused, so replace with `dict.values()`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IncorrectDictIterator { subset: DictSubset::Values, }, @@ -115,11 +115,10 @@ pub(crate) fn incorrect_dict_iterator(checker: &Checker, stmt_for: &ast::StmtFor stmt_for.target.range(), ); diagnostic.set_fix(Fix::unsafe_edits(replace_attribute, [replace_target])); - checker.report_diagnostic(diagnostic); } (false, true) => { // The value is unused, so replace with `dict.keys()`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IncorrectDictIterator { subset: DictSubset::Keys, }, @@ -135,7 +134,6 @@ pub(crate) fn incorrect_dict_iterator(checker: &Checker, stmt_for: &ast::StmtFor stmt_for.target.range(), ); diagnostic.set_fix(Fix::unsafe_edits(replace_attribute, [replace_target])); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/perflint/rules/manual_dict_comprehension.rs b/crates/ruff_linter/src/rules/perflint/rules/manual_dict_comprehension.rs index ed0a9fd101..c3b17b2d16 100644 --- a/crates/ruff_linter/src/rules/perflint/rules/manual_dict_comprehension.rs +++ b/crates/ruff_linter/src/rules/perflint/rules/manual_dict_comprehension.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ self as ast, Expr, Stmt, comparable::ComparableExpr, helpers::any_over_expr, @@ -296,7 +296,7 @@ pub(crate) fn manual_dict_comprehension(checker: &Checker, for_stmt: &ast::StmtF DictComprehensionType::Update }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ManualDictComprehension { fix_type, is_async: for_stmt.is_async, @@ -314,16 +314,14 @@ pub(crate) fn manual_dict_comprehension(checker: &Checker, for_stmt: &ast::StmtF checker, )) }); - - checker.report_diagnostic(diagnostic); } else { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( ManualDictComprehension { fix_type: DictComprehensionType::Comprehension, is_async: for_stmt.is_async, }, *range, - )); + ); } } diff --git a/crates/ruff_linter/src/rules/perflint/rules/manual_list_comprehension.rs b/crates/ruff_linter/src/rules/perflint/rules/manual_list_comprehension.rs index 590628c39f..461092bb97 100644 --- a/crates/ruff_linter/src/rules/perflint/rules/manual_list_comprehension.rs +++ b/crates/ruff_linter/src/rules/perflint/rules/manual_list_comprehension.rs @@ -5,7 +5,7 @@ use crate::{ rules::perflint::helpers::statement_deletion_range, }; use anyhow::{Result, anyhow}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use crate::rules::perflint::helpers::comment_strings_in_range; use ruff_macros::{ViolationMetadata, derive_message_formats}; @@ -331,7 +331,7 @@ pub(crate) fn manual_list_comprehension(checker: &Checker, for_stmt: &ast::StmtF ComprehensionType::Extend }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ManualListComprehension { is_async: for_stmt.is_async, comprehension_type: Some(comprehension_type), @@ -352,8 +352,6 @@ pub(crate) fn manual_list_comprehension(checker: &Checker, for_stmt: &ast::StmtF ) }); } - - checker.report_diagnostic(diagnostic); } fn convert_to_list_extend( diff --git a/crates/ruff_linter/src/rules/perflint/rules/manual_list_copy.rs b/crates/ruff_linter/src/rules/perflint/rules/manual_list_copy.rs index d42d78d0f6..dc8fe2a646 100644 --- a/crates/ruff_linter/src/rules/perflint/rules/manual_list_copy.rs +++ b/crates/ruff_linter/src/rules/perflint/rules/manual_list_copy.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; use ruff_python_ast::{self as ast, Arguments, Expr, Stmt}; @@ -119,5 +119,5 @@ pub(crate) fn manual_list_copy(checker: &Checker, for_stmt: &ast::StmtFor) { return; } - checker.report_diagnostic(Diagnostic::new(ManualListCopy, *range)); + checker.report_diagnostic(ManualListCopy, *range); } diff --git a/crates/ruff_linter/src/rules/perflint/rules/try_except_in_loop.rs b/crates/ruff_linter/src/rules/perflint/rules/try_except_in_loop.rs index 49c4a29c63..ee1fae0b14 100644 --- a/crates/ruff_linter/src/rules/perflint/rules/try_except_in_loop.rs +++ b/crates/ruff_linter/src/rules/perflint/rules/try_except_in_loop.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; use ruff_python_ast::{self as ast, Stmt}; @@ -107,7 +107,7 @@ pub(crate) fn try_except_in_loop(checker: &Checker, body: &[Stmt]) { return; } - checker.report_diagnostic(Diagnostic::new(TryExceptInLoop, handler.range())); + checker.report_diagnostic(TryExceptInLoop, handler.range()); } /// Returns `true` if a `break` or `continue` statement is present in `body`. diff --git a/crates/ruff_linter/src/rules/perflint/rules/unnecessary_list_cast.rs b/crates/ruff_linter/src/rules/perflint/rules/unnecessary_list_cast.rs index 19b2c0b08a..72a6d75303 100644 --- a/crates/ruff_linter/src/rules/perflint/rules/unnecessary_list_cast.rs +++ b/crates/ruff_linter/src/rules/perflint/rules/unnecessary_list_cast.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; use ruff_python_ast::{self as ast, Arguments, Expr, Stmt}; @@ -86,9 +86,8 @@ pub(crate) fn unnecessary_list_cast(checker: &Checker, iter: &Expr, body: &[Stmt range: iterable_range, .. }) => { - let mut diagnostic = Diagnostic::new(UnnecessaryListCast, *list_range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListCast, *list_range); diagnostic.set_fix(remove_cast(*list_range, *iterable_range)); - checker.report_diagnostic(diagnostic); } Expr::Name(ast::ExprName { id, @@ -114,9 +113,8 @@ pub(crate) fn unnecessary_list_cast(checker: &Checker, iter: &Expr, body: &[Stmt return; } - let mut diagnostic = Diagnostic::new(UnnecessaryListCast, *list_range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListCast, *list_range); diagnostic.set_fix(remove_cast(*list_range, *iterable_range)); - checker.report_diagnostic(diagnostic); } } _ => {} diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_class_name.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_class_name.rs index b7648a50e4..11af69e0aa 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_class_name.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_class_name.rs @@ -1,10 +1,10 @@ use ruff_python_ast::Identifier; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; -use crate::rules::pycodestyle::helpers::is_ambiguous_name; +use crate::{checkers::ast::Checker, rules::pycodestyle::helpers::is_ambiguous_name}; /// ## What it does /// Checks for the use of the characters 'l', 'O', or 'I' as class names. @@ -36,13 +36,8 @@ impl Violation for AmbiguousClassName { } /// E742 -pub(crate) fn ambiguous_class_name(name: &Identifier) -> Option { +pub(crate) fn ambiguous_class_name(checker: &Checker, name: &Identifier) { if is_ambiguous_name(name) { - Some(Diagnostic::new( - AmbiguousClassName(name.to_string()), - name.range(), - )) - } else { - None + checker.report_diagnostic(AmbiguousClassName(name.to_string()), name.range()); } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_function_name.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_function_name.rs index 15f276d9fc..6d74c79d39 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_function_name.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_function_name.rs @@ -1,10 +1,10 @@ use ruff_python_ast::Identifier; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; -use crate::rules::pycodestyle::helpers::is_ambiguous_name; +use crate::{checkers::ast::Checker, rules::pycodestyle::helpers::is_ambiguous_name}; /// ## What it does /// Checks for the use of the characters 'l', 'O', or 'I' as function names. @@ -36,13 +36,8 @@ impl Violation for AmbiguousFunctionName { } /// E743 -pub(crate) fn ambiguous_function_name(name: &Identifier) -> Option { +pub(crate) fn ambiguous_function_name(checker: &Checker, name: &Identifier) { if is_ambiguous_name(name) { - Some(Diagnostic::new( - AmbiguousFunctionName(name.to_string()), - name.range(), - )) - } else { - None + checker.report_diagnostic(AmbiguousFunctionName(name.to_string()), name.range()); } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_variable_name.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_variable_name.rs index 553fed76de..1f4a6f5683 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_variable_name.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/ambiguous_variable_name.rs @@ -1,6 +1,6 @@ use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -50,9 +50,6 @@ pub(crate) fn ambiguous_variable_name(checker: &Checker, name: &str, range: Text return; } if is_ambiguous_name(name) { - checker.report_diagnostic(Diagnostic::new( - AmbiguousVariableName(name.to_string()), - range, - )); + checker.report_diagnostic(AmbiguousVariableName(name.to_string()), range); } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/bare_except.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/bare_except.rs index a7f92225b3..571d327ccf 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/bare_except.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/bare_except.rs @@ -1,9 +1,9 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::except; use ruff_python_ast::{self as ast, ExceptHandler, Expr, Stmt}; -use crate::Locator; +use crate::checkers::ast::Checker; /// ## What it does /// Checks for bare `except` catches in `try`-`except` statements. @@ -56,21 +56,16 @@ impl Violation for BareExcept { /// E722 pub(crate) fn bare_except( + checker: &Checker, type_: Option<&Expr>, body: &[Stmt], handler: &ExceptHandler, - locator: &Locator, -) -> Option { +) { if type_.is_none() && !body .iter() .any(|stmt| matches!(stmt, Stmt::Raise(ast::StmtRaise { exc: None, .. }))) { - Some(Diagnostic::new( - BareExcept, - except(handler, locator.contents()), - )) - } else { - None + checker.report_diagnostic(BareExcept, except(handler, checker.locator().contents())); } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/invalid_escape_sequence.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/invalid_escape_sequence.rs index 5ee72ffae1..8968a32827 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/invalid_escape_sequence.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/invalid_escape_sequence.rs @@ -1,6 +1,6 @@ use memchr::memchr_iter; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{AnyStringFlags, FStringElement, StringLike, StringLikePart}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; @@ -252,7 +252,7 @@ fn check( if contains_valid_escape_sequence { // Escape with backslash. for invalid_escape_char in &invalid_escape_chars { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( InvalidEscapeSequence { ch: invalid_escape_char.ch, fix_title: FixTitle::AddBackslash, @@ -263,12 +263,11 @@ fn check( r"\".to_string(), invalid_escape_char.start() + TextSize::from(1), ))); - checker.report_diagnostic(diagnostic); } } else { // Turn into raw string. for invalid_escape_char in &invalid_escape_chars { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( InvalidEscapeSequence { ch: invalid_escape_char.ch, fix_title: FixTitle::UseRawStringLiteral, @@ -295,8 +294,6 @@ fn check( )), ); } - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/lambda_assignment.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/lambda_assignment.rs index 0d252c1bc0..eb8f153741 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/lambda_assignment.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/lambda_assignment.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{ @@ -70,7 +70,16 @@ pub(crate) fn lambda_assignment( return; }; - let mut diagnostic = Diagnostic::new( + // If the assignment is a class attribute (with an annotation), ignore it. + // + // This is most common for, e.g., dataclasses and Pydantic models. Those libraries will + // treat the lambda as an assignable field, and the use of a lambda is almost certainly + // intentional. + if annotation.is_some() && checker.semantic().current_scope().kind.is_class() { + return; + } + + let mut diagnostic = checker.report_diagnostic( LambdaAssignment { name: id.to_string(), }, @@ -96,15 +105,6 @@ pub(crate) fn lambda_assignment( } } - // If the assignment is a class attribute (with an annotation), ignore it. - // - // This is most common for, e.g., dataclasses and Pydantic models. Those libraries will - // treat the lambda as an assignable field, and the use of a lambda is almost certainly - // intentional. - if annotation.is_some() && checker.semantic().current_scope().kind.is_class() { - return; - } - // Otherwise, if the assignment is in a class body, flag it, but use a display-only fix. // Rewriting safely would require making this a static method. // @@ -129,8 +129,6 @@ pub(crate) fn lambda_assignment( ))); } } - - checker.report_diagnostic(diagnostic); } /// Extract the argument types and return type from a `Callable` annotation. 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 ef175cd810..7e26184138 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/literal_comparisons.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/literal_comparisons.rs @@ -1,7 +1,7 @@ use ruff_python_ast::parenthesize::parenthesized_range; use rustc_hash::FxHashMap; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::{self, generate_comparison}; use ruff_python_ast::{self as ast, CmpOp, Expr}; @@ -209,7 +209,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) // then replace the entire expression at the end with one "real" fix, to // avoid conflicts. let mut bad_ops: FxHashMap = FxHashMap::default(); - let mut diagnostics: Vec = vec![]; + let mut diagnostics = vec![]; // Check `left`. let mut comparator = compare.left.as_ref(); @@ -225,12 +225,14 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) if checker.enabled(Rule::NoneComparison) && comparator.is_none_literal_expr() { match op { EqCmpOp::Eq => { - let diagnostic = Diagnostic::new(NoneComparison(op), comparator.range()); + let diagnostic = + checker.report_diagnostic(NoneComparison(op), comparator.range()); bad_ops.insert(0, CmpOp::Is); diagnostics.push(diagnostic); } EqCmpOp::NotEq => { - let diagnostic = Diagnostic::new(NoneComparison(op), comparator.range()); + let diagnostic = + checker.report_diagnostic(NoneComparison(op), comparator.range()); bad_ops.insert(0, CmpOp::IsNot); diagnostics.push(diagnostic); } @@ -246,7 +248,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } else { None }; - let diagnostic = Diagnostic::new( + let diagnostic = checker.report_diagnostic( TrueFalseComparison { value: *value, op, @@ -263,7 +265,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } else { None }; - let diagnostic = Diagnostic::new( + let diagnostic = checker.report_diagnostic( TrueFalseComparison { value: *value, op, @@ -291,12 +293,14 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) if checker.enabled(Rule::NoneComparison) && next.is_none_literal_expr() { match op { EqCmpOp::Eq => { - let diagnostic = Diagnostic::new(NoneComparison(op), next.range()); + let diagnostic = + checker.report_diagnostic(NoneComparison(op), next.range()); bad_ops.insert(index, CmpOp::Is); diagnostics.push(diagnostic); } EqCmpOp::NotEq => { - let diagnostic = Diagnostic::new(NoneComparison(op), next.range()); + let diagnostic = + checker.report_diagnostic(NoneComparison(op), next.range()); bad_ops.insert(index, CmpOp::IsNot); diagnostics.push(diagnostic); } @@ -324,7 +328,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } else { None }; - let diagnostic = Diagnostic::new( + let diagnostic = checker.report_diagnostic( TrueFalseComparison { value: *value, op, @@ -343,7 +347,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } else { None }; - let diagnostic = Diagnostic::new( + let diagnostic = checker.report_diagnostic( TrueFalseComparison { value: *value, op, @@ -426,8 +430,4 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) ))); } } - - for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); - } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/module_import_not_at_top_of_file.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/module_import_not_at_top_of_file.rs index 17d7a830ae..307549e3f1 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/module_import_not_at_top_of_file.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/module_import_not_at_top_of_file.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{PySourceType, Stmt}; use ruff_text_size::Ranged; @@ -58,11 +58,11 @@ impl Violation for ModuleImportNotAtTopOfFile { /// E402 pub(crate) fn module_import_not_at_top_of_file(checker: &Checker, stmt: &Stmt) { if checker.semantic().seen_import_boundary() && checker.semantic().at_top_level() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( ModuleImportNotAtTopOfFile { source_type: checker.source_type, }, stmt.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/multiple_imports_on_one_line.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/multiple_imports_on_one_line.rs index 625b082e8b..fa9bfe5949 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/multiple_imports_on_one_line.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/multiple_imports_on_one_line.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Alias, Stmt}; use ruff_python_codegen::Stylist; @@ -49,7 +49,7 @@ impl Violation for MultipleImportsOnOneLine { /// E401 pub(crate) fn multiple_imports_on_one_line(checker: &Checker, stmt: &Stmt, names: &[Alias]) { if names.len() > 1 { - let mut diagnostic = Diagnostic::new(MultipleImportsOnOneLine, stmt.range()); + let mut diagnostic = checker.report_diagnostic(MultipleImportsOnOneLine, stmt.range()); diagnostic.set_fix(split_imports( stmt, names, @@ -57,7 +57,6 @@ pub(crate) fn multiple_imports_on_one_line(checker: &Checker, stmt: &Stmt, names checker.indexer(), checker.stylist(), )); - checker.report_diagnostic(diagnostic); } } 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 60668db001..90eb83f9ec 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/not_tests.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/not_tests.rs @@ -1,5 +1,5 @@ use crate::fix::edits::pad; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::generate_comparison; use ruff_python_ast::{self as ast, CmpOp, Expr}; @@ -96,7 +96,7 @@ pub(crate) fn not_tests(checker: &Checker, unary_op: &ast::ExprUnaryOp) { match &**ops { [CmpOp::In] => { if checker.enabled(Rule::NotInTest) { - let mut diagnostic = Diagnostic::new(NotInTest, unary_op.operand.range()); + let mut diagnostic = checker.report_diagnostic(NotInTest, unary_op.operand.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( pad( generate_comparison( @@ -112,12 +112,11 @@ pub(crate) fn not_tests(checker: &Checker, unary_op: &ast::ExprUnaryOp) { ), unary_op.range(), ))); - checker.report_diagnostic(diagnostic); } } [CmpOp::Is] => { if checker.enabled(Rule::NotIsTest) { - let mut diagnostic = Diagnostic::new(NotIsTest, unary_op.operand.range()); + let mut diagnostic = checker.report_diagnostic(NotIsTest, unary_op.operand.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( pad( generate_comparison( @@ -133,7 +132,6 @@ pub(crate) fn not_tests(checker: &Checker, unary_op: &ast::ExprUnaryOp) { ), unary_op.range(), ))); - checker.report_diagnostic(diagnostic); } } _ => {} diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/type_comparison.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/type_comparison.rs index 97440863b7..296271d6c8 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/type_comparison.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/type_comparison.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr}; @@ -76,7 +76,7 @@ pub(crate) fn type_comparison(checker: &Checker, compare: &ast::ExprCompare) { } // Disallow the comparison. - checker.report_diagnostic(Diagnostic::new(TypeComparison, compare.range())); + checker.report_diagnostic(TypeComparison, compare.range()); } } } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/whitespace_after_decorator.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/whitespace_after_decorator.rs index efb3ed22dc..b142253f77 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/whitespace_after_decorator.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/whitespace_after_decorator.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Decorator; use ruff_python_trivia::is_python_whitespace; @@ -62,9 +62,8 @@ pub(crate) fn whitespace_after_decorator(checker: &Checker, decorator_list: &[De let end = start + TextSize::try_from(end).unwrap(); let range = TextRange::new(start, end); - let mut diagnostic = Diagnostic::new(WhitespaceAfterDecorator, range); + let mut diagnostic = checker.report_diagnostic(WhitespaceAfterDecorator, range); diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(range))); - checker.report_diagnostic(diagnostic); } } } 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 83acd9cde1..4bb9865a17 100644 --- a/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs +++ b/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs @@ -1,5 +1,4 @@ use itertools::Itertools; -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; @@ -925,10 +924,8 @@ pub(crate) fn check_docstring( semantic, ) { - checker.report_diagnostic(Diagnostic::new( - DocstringMissingReturns, - docstring.range(), - )); + checker + .report_diagnostic(DocstringMissingReturns, docstring.range()); } } None if body_entries @@ -936,10 +933,7 @@ pub(crate) fn check_docstring( .iter() .any(|entry| !entry.is_none_return()) => { - checker.report_diagnostic(Diagnostic::new( - DocstringMissingReturns, - docstring.range(), - )); + checker.report_diagnostic(DocstringMissingReturns, docstring.range()); } _ => {} } @@ -958,16 +952,10 @@ pub(crate) fn check_docstring( |arguments| arguments.first().is_none_or(Expr::is_none_literal_expr), ) => { - checker.report_diagnostic(Diagnostic::new( - DocstringMissingYields, - docstring.range(), - )); + checker.report_diagnostic(DocstringMissingYields, docstring.range()); } None if body_entries.yields.iter().any(|entry| !entry.is_none_yield) => { - checker.report_diagnostic(Diagnostic::new( - DocstringMissingYields, - docstring.range(), - )); + checker.report_diagnostic(DocstringMissingYields, docstring.range()); } _ => {} } @@ -994,13 +982,12 @@ pub(crate) fn check_docstring( .ends_with(exception.segments()) }) }) { - let diagnostic = Diagnostic::new( + checker.report_diagnostic( DocstringMissingException { id: (*name).to_string(), }, docstring.range(), ); - checker.report_diagnostic(diagnostic); } } } @@ -1014,8 +1001,7 @@ pub(crate) fn check_docstring( if body_entries.returns.is_empty() || body_entries.returns.iter().all(ReturnEntry::is_implicit) { - let diagnostic = Diagnostic::new(DocstringExtraneousReturns, docstring.range()); - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(DocstringExtraneousReturns, docstring.range()); } } } @@ -1024,8 +1010,7 @@ pub(crate) fn check_docstring( if checker.enabled(Rule::DocstringExtraneousYields) { if docstring_sections.yields.is_some() { if body_entries.yields.is_empty() { - let diagnostic = Diagnostic::new(DocstringExtraneousYields, docstring.range()); - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(DocstringExtraneousYields, docstring.range()); } } } @@ -1045,13 +1030,12 @@ pub(crate) fn check_docstring( } } if !extraneous_exceptions.is_empty() { - let diagnostic = Diagnostic::new( + checker.report_diagnostic( DocstringExtraneousException { ids: extraneous_exceptions, }, docstring.range(), ); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/backslashes.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/backslashes.rs index 9c322699a1..fb8e75f2e1 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/backslashes.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/backslashes.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -96,7 +96,8 @@ pub(crate) fn backslashes(checker: &Checker, docstring: &Docstring) { // Only allow continuations (backslashes followed by newlines) and Unicode escapes. if !matches!(*escaped_char, '\r' | '\n' | 'u' | 'U' | 'N') { - let mut diagnostic = Diagnostic::new(EscapeSequenceInDocstring, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(EscapeSequenceInDocstring, docstring.range()); if !docstring.is_u_string() { diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( @@ -105,7 +106,6 @@ pub(crate) fn backslashes(checker: &Checker, docstring: &Docstring) { ))); } - checker.report_diagnostic(diagnostic); break; } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/blank_after_summary.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/blank_after_summary.rs index c39977a46e..371d0a7ed7 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/blank_after_summary.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/blank_after_summary.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::{UniversalNewlineIterator, UniversalNewlines}; use ruff_text_size::Ranged; @@ -84,7 +84,7 @@ pub(crate) fn blank_after_summary(checker: &Checker, docstring: &Docstring) { } } if lines_count > 1 && blanks_count != 1 { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingBlankLineAfterSummary { num_lines: blanks_count, }, @@ -118,6 +118,5 @@ pub(crate) fn blank_after_summary(checker: &Checker, docstring: &Docstring) { blank_end, ))); } - checker.report_diagnostic(diagnostic); } } 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 b2a1d5ac45..6e31de5655 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_trivia::{PythonWhitespace, indentation_at_offset}; use ruff_source_file::{Line, LineRanges, UniversalNewlineIterator}; @@ -193,26 +193,25 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) if checker.enabled(Rule::BlankLineBeforeClass) { if blank_lines_before != 0 { - let mut diagnostic = Diagnostic::new(BlankLineBeforeClass, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(BlankLineBeforeClass, docstring.range()); // Delete the blank line before the class. diagnostic.set_fix(Fix::safe_edit(Edit::deletion( blank_lines_start, docstring.line_start(), ))); - checker.report_diagnostic(diagnostic); } } if checker.enabled(Rule::IncorrectBlankLineBeforeClass) { if blank_lines_before != 1 { let mut diagnostic = - Diagnostic::new(IncorrectBlankLineBeforeClass, docstring.range()); + checker.report_diagnostic(IncorrectBlankLineBeforeClass, docstring.range()); // Insert one blank line before the class. diagnostic.set_fix(Fix::safe_edit(Edit::replacement( checker.stylist().line_ending().to_string(), blank_lines_start, docstring.line_start(), ))); - checker.report_diagnostic(diagnostic); } } } @@ -245,7 +244,7 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) let indentation = indentation_at_offset(docstring.start(), checker.source()) .expect("Own line docstring must have indentation"); let mut diagnostic = - Diagnostic::new(IncorrectBlankLineAfterClass, docstring.range()); + checker.report_diagnostic(IncorrectBlankLineAfterClass, docstring.range()); let line_ending = checker.stylist().line_ending().as_str(); // We have to trim the whitespace twice, once before the semicolon above and // once after the semicolon here, or we get invalid indents: @@ -259,7 +258,7 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) replacement_start, first_line.end(), ))); - checker.report_diagnostic(diagnostic); + return; } else if trailing.starts_with('#') { // Keep the end-of-line comment, start counting empty lines after it @@ -280,14 +279,14 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) } if blank_lines_after != 1 { - let mut diagnostic = Diagnostic::new(IncorrectBlankLineAfterClass, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(IncorrectBlankLineAfterClass, docstring.range()); // Insert a blank line before the class (replacing any existing lines). diagnostic.set_fix(Fix::safe_edit(Edit::replacement( checker.stylist().line_ending().to_string(), replacement_start, blank_lines_end, ))); - checker.report_diagnostic(diagnostic); } } } 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 a5f0d10cbb..0d3ae7a3fd 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 @@ -1,7 +1,7 @@ use regex::Regex; use std::sync::LazyLock; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_trivia::PythonWhitespace; use ruff_source_file::{UniversalNewlineIterator, UniversalNewlines}; @@ -126,7 +126,7 @@ pub(crate) fn blank_before_after_function(checker: &Checker, docstring: &Docstri } if blank_lines_before != 0 { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BlankLineBeforeFunction { num_lines: blank_lines_before, }, @@ -137,7 +137,6 @@ pub(crate) fn blank_before_after_function(checker: &Checker, docstring: &Docstri blank_lines_start, docstring.line_start(), ))); - checker.report_diagnostic(diagnostic); } } @@ -180,7 +179,7 @@ pub(crate) fn blank_before_after_function(checker: &Checker, docstring: &Docstri } if blank_lines_after != 0 { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BlankLineAfterFunction { num_lines: blank_lines_after, }, @@ -191,7 +190,6 @@ pub(crate) fn blank_before_after_function(checker: &Checker, docstring: &Docstri first_line_end, blank_lines_end, ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/capitalized.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/capitalized.rs index b8144df8c5..5448705c06 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/capitalized.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/capitalized.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use ruff_text_size::{TextLen, TextRange}; @@ -90,7 +90,7 @@ pub(crate) fn capitalized(checker: &Checker, docstring: &Docstring) { let leading_whitespace_len = body.text_len() - trim_start_body.text_len(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( FirstWordUncapitalized { first_word: first_word.to_string(), capitalized_word: capitalized_word.to_string(), @@ -102,6 +102,4 @@ pub(crate) fn capitalized(checker: &Checker, docstring: &Docstring) { capitalized_word, TextRange::at(body.start() + leading_whitespace_len, first_word.text_len()), ))); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_period.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_period.rs index 8e7ab735df..173ad2552d 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_period.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_period.rs @@ -1,7 +1,7 @@ use ruff_text_size::TextLen; use strum::IntoEnumIterator; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::{UniversalNewlineIterator, UniversalNewlines}; use ruff_text_size::Ranged; @@ -106,7 +106,8 @@ pub(crate) fn ends_with_period(checker: &Checker, docstring: &Docstring) { } if !trimmed.ends_with('.') { - let mut diagnostic = Diagnostic::new(MissingTrailingPeriod, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(MissingTrailingPeriod, docstring.range()); // Best-effort fix: avoid adding a period after other punctuation marks. if !trimmed.ends_with([':', ';', '?', '!']) { diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( @@ -114,7 +115,6 @@ pub(crate) fn ends_with_period(checker: &Checker, docstring: &Docstring) { line.start() + trimmed.text_len(), ))); } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_punctuation.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_punctuation.rs index 2ed5734c45..070bd61103 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_punctuation.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/ends_with_punctuation.rs @@ -1,7 +1,7 @@ use ruff_text_size::TextLen; use strum::IntoEnumIterator; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::{UniversalNewlineIterator, UniversalNewlines}; use ruff_text_size::Ranged; @@ -105,7 +105,8 @@ pub(crate) fn ends_with_punctuation(checker: &Checker, docstring: &Docstring) { } if !trimmed.ends_with(['.', '!', '?']) { - let mut diagnostic = Diagnostic::new(MissingTerminalPunctuation, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(MissingTerminalPunctuation, docstring.range()); // Best-effort fix: avoid adding a period after other punctuation marks. if !trimmed.ends_with([':', ';']) { diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( @@ -113,7 +114,6 @@ pub(crate) fn ends_with_punctuation(checker: &Checker, docstring: &Docstring) { line.start() + trimmed.text_len(), ))); } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/if_needed.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/if_needed.rs index 2fb93a1f20..d9f528fe14 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/if_needed.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/if_needed.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility::is_overload; @@ -82,9 +82,6 @@ pub(crate) fn if_needed(checker: &Checker, docstring: &Docstring) { return; }; if is_overload(&function.decorator_list, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( - OverloadWithDocstring, - function.identifier(), - )); + checker.report_diagnostic(OverloadWithDocstring, function.identifier()); } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs index c2796b71d7..a6f044b2c5 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs @@ -1,5 +1,5 @@ use ruff_diagnostics::{AlwaysFixableViolation, Violation}; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::docstrings::{clean_space, leading_space}; use ruff_source_file::{Line, NewlineWithTrailingNewline}; @@ -225,12 +225,11 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { // fix. if (is_last || !is_blank) && line_indent_size < docstring_indent_size { let mut diagnostic = - Diagnostic::new(UnderIndentation, TextRange::empty(line.start())); + checker.report_diagnostic(UnderIndentation, TextRange::empty(line.start())); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( clean_space(docstring_indentation), TextRange::at(line.start(), line_indent.text_len()), ))); - checker.report_diagnostic(diagnostic); } } @@ -267,7 +266,7 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { if checker.enabled(Rule::DocstringTabIndentation) { if has_seen_tab { - checker.report_diagnostic(Diagnostic::new(DocstringTabIndentation, docstring.range())); + checker.report_diagnostic(DocstringTabIndentation, docstring.range()); } } @@ -281,7 +280,7 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { // We report over-indentation on every line. This isn't great, but // enables the fix capability. let mut diagnostic = - Diagnostic::new(OverIndentation, TextRange::empty(line.start())); + checker.report_diagnostic(OverIndentation, TextRange::empty(line.start())); let edit = if indent.is_empty() { // Delete the entire indent. @@ -311,7 +310,6 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { Edit::range_replacement(indent, range) }; diagnostic.set_fix(Fix::safe_edit(edit)); - checker.report_diagnostic(diagnostic); } } @@ -324,7 +322,7 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { let is_indent_only = line_indent.len() == last.len(); if last_line_over_indent > 0 && is_indent_only { let mut diagnostic = - Diagnostic::new(OverIndentation, TextRange::empty(last.start())); + checker.report_diagnostic(OverIndentation, TextRange::empty(last.start())); let indent = clean_space(docstring_indentation); let range = TextRange::at(last.start(), line_indent.text_len()); let edit = if indent.is_empty() { @@ -333,7 +331,6 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { Edit::range_replacement(indent, range) }; diagnostic.set_fix(Fix::safe_edit(edit)); - checker.report_diagnostic(diagnostic); } } } 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 764fa36827..5d2e127010 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 @@ -1,6 +1,6 @@ use std::borrow::Cow; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::str::is_triple_quote; use ruff_python_semantic::Definition; @@ -156,7 +156,8 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring) if is_triple_quote(&first_line) { if checker.enabled(Rule::MultiLineSummaryFirstLine) { - let mut diagnostic = Diagnostic::new(MultiLineSummaryFirstLine, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(MultiLineSummaryFirstLine, docstring.range()); // Delete until first non-whitespace char. for line in content_lines { if let Some(end_column) = line.find(|c: char| !c.is_whitespace()) { @@ -167,7 +168,6 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring) break; } } - checker.report_diagnostic(diagnostic); } } else if first_line.as_str().ends_with('\\') { // Ignore the edge case whether a single quoted string is multiple lines through an @@ -180,7 +180,8 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring) return; } else { if checker.enabled(Rule::MultiLineSummarySecondLine) { - let mut diagnostic = Diagnostic::new(MultiLineSummarySecondLine, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(MultiLineSummarySecondLine, docstring.range()); let mut indentation = Cow::Borrowed(docstring.compute_indentation()); let mut fixable = true; if !indentation.chars().all(char::is_whitespace) { @@ -223,7 +224,6 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring) first_line.end(), ))); } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs index 1da0e6b83c..da56dbe1ae 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs @@ -1,6 +1,6 @@ use ruff_text_size::{TextLen, TextSize}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::docstrings::clean_space; use ruff_source_file::{NewlineWithTrailingNewline, UniversalNewlines}; @@ -79,7 +79,7 @@ pub(crate) fn newline_after_last_paragraph(checker: &Checker, docstring: &Docstr { if last_line != "\"\"\"" && last_line != "'''" { let mut diagnostic = - Diagnostic::new(NewLineAfterLastParagraph, docstring.range()); + checker.report_diagnostic(NewLineAfterLastParagraph, docstring.range()); // Insert a newline just before the end-quote(s). let num_trailing_quotes = "'''".text_len(); let num_trailing_spaces: TextSize = last_line @@ -99,7 +99,6 @@ pub(crate) fn newline_after_last_paragraph(checker: &Checker, docstring: &Docstr docstring.end() - num_trailing_quotes - num_trailing_spaces, docstring.end() - num_trailing_quotes, ))); - checker.report_diagnostic(diagnostic); } } return; diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/no_signature.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/no_signature.rs index 87d6c96d00..2ca5cd7cab 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/no_signature.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/no_signature.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::UniversalNewlines; use ruff_text_size::Ranged; @@ -86,6 +86,6 @@ pub(crate) fn no_signature(checker: &Checker, docstring: &Docstring) { true }) { - checker.report_diagnostic(Diagnostic::new(SignatureInDocstring, docstring.range())); + checker.report_diagnostic(SignatureInDocstring, docstring.range()); } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs index 91d24db52a..be8da37b62 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::NewlineWithTrailingNewline; use ruff_text_size::Ranged; @@ -62,7 +62,7 @@ pub(crate) fn no_surrounding_whitespace(checker: &Checker, docstring: &Docstring if line == trimmed { return; } - let mut diagnostic = Diagnostic::new(SurroundingWhitespace, docstring.range()); + let mut diagnostic = checker.report_diagnostic(SurroundingWhitespace, docstring.range()); let quote = docstring.quote_style().as_char(); // If removing whitespace would lead to an invalid string of quote // characters, avoid applying the fix. @@ -72,5 +72,4 @@ pub(crate) fn no_surrounding_whitespace(checker: &Checker, docstring: &Docstring TextRange::at(body.start(), line.text_len()), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/non_imperative_mood.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/non_imperative_mood.rs index e5c88bfb36..6a138f49b0 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/non_imperative_mood.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/non_imperative_mood.rs @@ -2,7 +2,7 @@ use std::sync::LazyLock; use imperative::Mood; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::visibility::{is_property, is_test}; use ruff_source_file::UniversalNewlines; @@ -99,11 +99,11 @@ pub(crate) fn non_imperative_mood(checker: &Checker, docstring: &Docstring, sett } if matches!(MOOD.is_imperative(&first_word_norm), Some(false)) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NonImperativeMood { first_line: first_line.to_string(), }, docstring.range(), - )); + ); } } 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 05dd97fac5..ef92f1ede4 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/not_empty.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/not_empty.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -46,7 +46,7 @@ pub(crate) fn not_empty(checker: &Checker, docstring: &Docstring) -> bool { } if checker.enabled(Rule::EmptyDocstring) { - checker.report_diagnostic(Diagnostic::new(EmptyDocstring, docstring.range())); + 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 5d941ab82a..e243e946da 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/not_missing.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/not_missing.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility::{ @@ -552,10 +552,7 @@ pub(crate) fn not_missing( return true; } if checker.enabled(Rule::UndocumentedPublicModule) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicModule, - TextRange::default(), - )); + checker.report_diagnostic(UndocumentedPublicModule, TextRange::default()); } false } @@ -564,10 +561,7 @@ pub(crate) fn not_missing( .. }) => { if checker.enabled(Rule::UndocumentedPublicPackage) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicPackage, - TextRange::default(), - )); + checker.report_diagnostic(UndocumentedPublicPackage, TextRange::default()); } false } @@ -576,10 +570,7 @@ pub(crate) fn not_missing( .. }) => { if checker.enabled(Rule::UndocumentedPublicClass) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicClass, - class.identifier(), - )); + checker.report_diagnostic(UndocumentedPublicClass, class.identifier()); } false } @@ -588,10 +579,7 @@ pub(crate) fn not_missing( .. }) => { if checker.enabled(Rule::UndocumentedPublicNestedClass) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicNestedClass, - function.identifier(), - )); + checker.report_diagnostic(UndocumentedPublicNestedClass, function.identifier()); } false } @@ -603,10 +591,7 @@ pub(crate) fn not_missing( true } else { if checker.enabled(Rule::UndocumentedPublicFunction) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicFunction, - function.identifier(), - )); + checker.report_diagnostic(UndocumentedPublicFunction, function.identifier()); } false } @@ -621,34 +606,22 @@ pub(crate) fn not_missing( true } else if is_init(&function.name) { if checker.enabled(Rule::UndocumentedPublicInit) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicInit, - function.identifier(), - )); + checker.report_diagnostic(UndocumentedPublicInit, function.identifier()); } true } else if is_new(&function.name) || is_call(&function.name) { if checker.enabled(Rule::UndocumentedPublicMethod) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicMethod, - function.identifier(), - )); + checker.report_diagnostic(UndocumentedPublicMethod, function.identifier()); } true } else if is_magic(&function.name) { if checker.enabled(Rule::UndocumentedMagicMethod) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedMagicMethod, - function.identifier(), - )); + checker.report_diagnostic(UndocumentedMagicMethod, function.identifier()); } true } else { if checker.enabled(Rule::UndocumentedPublicMethod) { - checker.report_diagnostic(Diagnostic::new( - UndocumentedPublicMethod, - function.identifier(), - )); + checker.report_diagnostic(UndocumentedPublicMethod, function.identifier()); } true } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/one_liner.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/one_liner.rs index ebfb81b73d..1dafa14cac 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/one_liner.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/one_liner.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::NewlineWithTrailingNewline; use ruff_text_size::Ranged; @@ -67,7 +67,8 @@ pub(crate) fn one_liner(checker: &Checker, docstring: &Docstring) { } if non_empty_line_count == 1 && line_count > 1 { - let mut diagnostic = Diagnostic::new(UnnecessaryMultilineDocstring, docstring.range()); + let mut diagnostic = + checker.report_diagnostic(UnnecessaryMultilineDocstring, docstring.range()); // If removing whitespace would lead to an invalid string of quote // characters, avoid applying the fix. @@ -87,7 +88,5 @@ pub(crate) fn one_liner(checker: &Checker, docstring: &Docstring) { docstring.range(), ))); } - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs index 050a455f5d..b59492c483 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs @@ -4,7 +4,7 @@ use rustc_hash::FxHashSet; use std::sync::LazyLock; use ruff_diagnostics::{AlwaysFixableViolation, Violation}; -use ruff_diagnostics::{Diagnostic, Edit, Fix}; +use ruff_diagnostics::{Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::docstrings::{clean_space, leading_space}; use ruff_python_ast::identifier::Identifier; @@ -1362,7 +1362,7 @@ fn blanks_and_section_underline( if let Some(dashed_line) = find_underline(&non_blank_line, '-') { if num_blank_lines_after_header > 0 { if checker.enabled(Rule::MissingSectionUnderlineAfterName) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingSectionUnderlineAfterName { name: context.section_name().to_string(), }, @@ -1374,14 +1374,12 @@ fn blanks_and_section_underline( context.following_range().start(), blank_lines_end, ))); - - checker.report_diagnostic(diagnostic); } } if dashed_line.len().to_usize() != context.section_name().len() { if checker.enabled(Rule::MismatchedSectionUnderlineLength) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MismatchedSectionUnderlineLength { name: context.section_name().to_string(), }, @@ -1393,8 +1391,6 @@ fn blanks_and_section_underline( "-".repeat(context.section_name().len()), dashed_line, ))); - - checker.report_diagnostic(diagnostic); } } @@ -1402,7 +1398,7 @@ fn blanks_and_section_underline( let leading_space = leading_space(&non_blank_line); let docstring_indentation = docstring.compute_indentation(); if leading_space.len() > docstring_indentation.len() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( OverindentedSectionUnderline { name: context.section_name().to_string(), }, @@ -1420,8 +1416,6 @@ fn blanks_and_section_underline( } else { Edit::range_replacement(contents, range) })); - - checker.report_diagnostic(diagnostic); } } @@ -1441,12 +1435,12 @@ fn blanks_and_section_underline( if following_lines.peek().is_none() { if checker.enabled(Rule::EmptyDocstringSection) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( EmptyDocstringSection { name: context.section_name().to_string(), }, context.section_name_range(), - )); + ); } } else if checker.enabled(Rule::BlankLinesBetweenHeaderAndContent) { // If the section is followed by exactly one line, and then a @@ -1472,7 +1466,7 @@ fn blanks_and_section_underline( if is_sphinx { if num_blank_lines_dashes_end > 1 { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BlankLinesBetweenHeaderAndContent { name: context.section_name().to_string(), }, @@ -1484,10 +1478,9 @@ fn blanks_and_section_underline( line_after_dashes.start(), blank_lines_after_dashes_end, ))); - checker.report_diagnostic(diagnostic); } } else { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BlankLinesBetweenHeaderAndContent { name: context.section_name().to_string(), }, @@ -1498,24 +1491,23 @@ fn blanks_and_section_underline( line_after_dashes.start(), blank_lines_after_dashes_end, ))); - checker.report_diagnostic(diagnostic); } } } } else { if checker.enabled(Rule::EmptyDocstringSection) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( EmptyDocstringSection { name: context.section_name().to_string(), }, context.section_name_range(), - )); + ); } } } else { if style.is_numpy() && checker.enabled(Rule::MissingDashedUnderlineAfterSection) { if let Some(equal_line) = find_underline(&non_blank_line, '=') { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingDashedUnderlineAfterSection { name: context.section_name().to_string(), }, @@ -1528,10 +1520,8 @@ fn blanks_and_section_underline( "-".repeat(context.section_name().len()), equal_line, ))); - - checker.report_diagnostic(diagnostic); } else { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingDashedUnderlineAfterSection { name: context.section_name().to_string(), }, @@ -1549,8 +1539,6 @@ fn blanks_and_section_underline( content, context.summary_range().end(), ))); - - checker.report_diagnostic(diagnostic); } } if num_blank_lines_after_header > 0 { @@ -1577,7 +1565,7 @@ fn blanks_and_section_underline( if is_sphinx { if num_blank_lines_after_header > 1 { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BlankLinesBetweenHeaderAndContent { name: context.section_name().to_string(), }, @@ -1590,10 +1578,9 @@ fn blanks_and_section_underline( context.following_range().start(), blank_lines_end, ))); - checker.report_diagnostic(diagnostic); } } else { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BlankLinesBetweenHeaderAndContent { name: context.section_name().to_string(), }, @@ -1604,7 +1591,6 @@ fn blanks_and_section_underline( TextRange::new(context.following_range().start(), blank_lines_end); // Delete any blank lines between the header and content. diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(range))); - checker.report_diagnostic(diagnostic); } } } @@ -1612,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) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingDashedUnderlineAfterSection { name: context.section_name().to_string(), }, @@ -1630,16 +1616,14 @@ fn blanks_and_section_underline( content, context.summary_range().end(), ))); - - checker.report_diagnostic(diagnostic); } if checker.enabled(Rule::EmptyDocstringSection) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( EmptyDocstringSection { name: context.section_name().to_string(), }, context.section_name_range(), - )); + ); } } } @@ -1655,7 +1639,7 @@ fn common_section( let capitalized_section_name = context.kind().as_str(); if context.section_name() != capitalized_section_name { let section_range = context.section_name_range(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NonCapitalizedSectionName { name: context.section_name().to_string(), }, @@ -1667,7 +1651,6 @@ fn common_section( capitalized_section_name.to_string(), section_range, ))); - checker.report_diagnostic(diagnostic); } } @@ -1676,7 +1659,7 @@ fn common_section( let docstring_indentation = docstring.compute_indentation(); if leading_space.len() > docstring_indentation.len() { let section_range = context.section_name_range(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( OverindentedSection { name: context.section_name().to_string(), }, @@ -1691,7 +1674,6 @@ fn common_section( } else { Edit::range_replacement(content, fix_range) })); - checker.report_diagnostic(diagnostic); } } @@ -1706,7 +1688,7 @@ fn common_section( .count(); if num_blank_lines < 2 { let section_range = context.section_name_range(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NoBlankLineAfterSection { name: context.section_name().to_string(), }, @@ -1717,7 +1699,6 @@ fn common_section( line_end.to_string(), next.start(), ))); - checker.report_diagnostic(diagnostic); } } } else { @@ -1748,14 +1729,13 @@ fn common_section( ); let section_range = context.section_name_range(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingBlankLineAfterLastSection { name: context.section_name().to_string(), }, section_range, ); diagnostic.set_fix(Fix::safe_edit(edit)); - checker.report_diagnostic(diagnostic); } } } @@ -1766,7 +1746,7 @@ fn common_section( .is_some_and(|line| line.trim().is_empty()) { let section_range = context.section_name_range(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NoBlankLineBeforeSection { name: context.section_name().to_string(), }, @@ -1777,7 +1757,6 @@ fn common_section( line_end.to_string(), context.start(), ))); - checker.report_diagnostic(diagnostic); } } @@ -1835,13 +1814,13 @@ fn missing_args(checker: &Checker, docstring: &Docstring, docstrings_args: &FxHa if !missing_arg_names.is_empty() { if let Some(definition) = docstring.definition.name() { let names = missing_arg_names.into_iter().sorted().collect(); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UndocumentedParam { definition: definition.to_string(), names, }, function.identifier(), - )); + ); } } } @@ -1955,7 +1934,7 @@ fn numpy_section( let suffix = context.summary_after_section_name(); if !suffix.is_empty() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingNewLineAfterSectionName { name: context.section_name().to_string(), }, @@ -1966,8 +1945,6 @@ fn numpy_section( section_range.end(), suffix.text_len(), )))); - - checker.report_diagnostic(diagnostic); } } @@ -1989,7 +1966,7 @@ fn google_section( if checker.enabled(Rule::MissingSectionNameColon) { let suffix = context.summary_after_section_name(); if suffix != ":" { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MissingSectionNameColon { name: context.section_name().to_string(), }, @@ -2001,7 +1978,6 @@ fn google_section( ":".to_string(), TextRange::at(section_name_range.end(), suffix.text_len()), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/starts_with_this.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/starts_with_this.rs index 47274f7888..a405786043 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/starts_with_this.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/starts_with_this.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -64,5 +64,5 @@ pub(crate) fn starts_with_this(checker: &Checker, docstring: &Docstring) { if normalize_word(first_word) != "this" { return; } - checker.report_diagnostic(Diagnostic::new(DocstringStartsWithThis, docstring.range())); + checker.report_diagnostic(DocstringStartsWithThis, docstring.range()); } diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/triple_quotes.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/triple_quotes.rs index 8bd77b9b73..ef428f8e01 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/triple_quotes.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/triple_quotes.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::str::Quote; use ruff_text_size::Ranged; @@ -79,8 +79,8 @@ pub(crate) fn triple_quotes(checker: &Checker, docstring: &Docstring) { match expected_quote { Quote::Single => { if !opener.ends_with("'''") { - let mut diagnostic = - Diagnostic::new(TripleSingleQuotes { expected_quote }, docstring.range()); + let mut diagnostic = checker + .report_diagnostic(TripleSingleQuotes { expected_quote }, docstring.range()); let body = docstring.body().as_str(); if !body.ends_with('\'') { @@ -89,14 +89,12 @@ pub(crate) fn triple_quotes(checker: &Checker, docstring: &Docstring) { docstring.range(), ))); } - - checker.report_diagnostic(diagnostic); } } Quote::Double => { if !opener.ends_with("\"\"\"") { - let mut diagnostic = - Diagnostic::new(TripleSingleQuotes { expected_quote }, docstring.range()); + let mut diagnostic = checker + .report_diagnostic(TripleSingleQuotes { expected_quote }, docstring.range()); let body = docstring.body().as_str(); if !body.ends_with('"') { @@ -105,8 +103,6 @@ pub(crate) fn triple_quotes(checker: &Checker, docstring: &Docstring) { docstring.range(), ))); } - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/assert_tuple.rs b/crates/ruff_linter/src/rules/pyflakes/rules/assert_tuple.rs index a25322fb0f..d1cd8a7404 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/assert_tuple.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/assert_tuple.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -41,7 +41,7 @@ impl Violation for AssertTuple { pub(crate) fn assert_tuple(checker: &Checker, stmt: &Stmt, test: &Expr) { if let Expr::Tuple(tuple) = &test { if !tuple.is_empty() { - checker.report_diagnostic(Diagnostic::new(AssertTuple, stmt.range())); + checker.report_diagnostic(AssertTuple, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/break_outside_loop.rs b/crates/ruff_linter/src/rules/pyflakes/rules/break_outside_loop.rs index ba0e7b99ab..dc77d7bd07 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/break_outside_loop.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/break_outside_loop.rs @@ -1,9 +1,11 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for `break` statements outside of loops. /// @@ -31,15 +33,16 @@ impl Violation for BreakOutsideLoop { /// F701 pub(crate) fn break_outside_loop<'a>( + checker: &Checker, stmt: &'a Stmt, parents: &mut impl Iterator, -) -> Option { +) { let mut child = stmt; for parent in parents { match parent { Stmt::For(ast::StmtFor { orelse, .. }) | Stmt::While(ast::StmtWhile { orelse, .. }) => { if !orelse.contains(child) { - return None; + return; } } Stmt::FunctionDef(_) | Stmt::ClassDef(_) => { @@ -50,5 +53,5 @@ pub(crate) fn break_outside_loop<'a>( child = parent; } - Some(Diagnostic::new(BreakOutsideLoop, stmt.range())) + checker.report_diagnostic(BreakOutsideLoop, stmt.range()); } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/continue_outside_loop.rs b/crates/ruff_linter/src/rules/pyflakes/rules/continue_outside_loop.rs index dc4b842241..d91863daf6 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/continue_outside_loop.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/continue_outside_loop.rs @@ -1,9 +1,11 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for `continue` statements outside of loops. /// @@ -31,15 +33,16 @@ impl Violation for ContinueOutsideLoop { /// F702 pub(crate) fn continue_outside_loop<'a>( + checker: &Checker, stmt: &'a Stmt, parents: &mut impl Iterator, -) -> Option { +) { let mut child = stmt; for parent in parents { match parent { Stmt::For(ast::StmtFor { orelse, .. }) | Stmt::While(ast::StmtWhile { orelse, .. }) => { if !orelse.contains(child) { - return None; + return; } } Stmt::FunctionDef(_) | Stmt::ClassDef(_) => { @@ -50,5 +53,5 @@ pub(crate) fn continue_outside_loop<'a>( child = parent; } - Some(Diagnostic::new(ContinueOutsideLoop, stmt.range())) + checker.report_diagnostic(ContinueOutsideLoop, stmt.range()); } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/default_except_not_last.rs b/crates/ruff_linter/src/rules/pyflakes/rules/default_except_not_last.rs index a9bf5919e4..fe97acddc0 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/default_except_not_last.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/default_except_not_last.rs @@ -1,9 +1,10 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::except; use ruff_python_ast::{self as ast, ExceptHandler}; use crate::Locator; +use crate::checkers::ast::Checker; /// ## What it does /// Checks for `except` blocks that handle all exceptions, but are not the last @@ -55,18 +56,14 @@ impl Violation for DefaultExceptNotLast { /// F707 pub(crate) fn default_except_not_last( + checker: &Checker, handlers: &[ExceptHandler], locator: &Locator, -) -> Option { +) { for (idx, handler) in handlers.iter().enumerate() { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_, .. }) = handler; if type_.is_none() && idx < handlers.len() - 1 { - return Some(Diagnostic::new( - DefaultExceptNotLast, - except(handler, locator.contents()), - )); + checker.report_diagnostic(DefaultExceptNotLast, except(handler, locator.contents())); } } - - None } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/f_string_missing_placeholders.rs b/crates/ruff_linter/src/rules/pyflakes/rules/f_string_missing_placeholders.rs index df0a6d3b11..f15694b427 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/f_string_missing_placeholders.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/f_string_missing_placeholders.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::{Ranged, TextRange, TextSize}; @@ -91,13 +91,13 @@ pub(crate) fn f_string_missing_placeholders(checker: &Checker, expr: &ast::ExprF TextSize::new(1), ); - let mut diagnostic = Diagnostic::new(FStringMissingPlaceholders, f_string.range()); + let mut diagnostic = + checker.report_diagnostic(FStringMissingPlaceholders, f_string.range()); diagnostic.set_fix(convert_f_string_to_regular_string( prefix_range, f_string.range(), checker.locator(), )); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/future_feature_not_defined.rs b/crates/ruff_linter/src/rules/pyflakes/rules/future_feature_not_defined.rs index 7c4adce1d4..3589e78746 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/future_feature_not_defined.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/future_feature_not_defined.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Alias; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_stdlib::future::is_feature_name; use ruff_text_size::Ranged; @@ -35,10 +35,10 @@ pub(crate) fn future_feature_not_defined(checker: &Checker, alias: &Alias) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( FutureFeatureNotDefined { name: alias.name.to_string(), }, alias.range(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/if_tuple.rs b/crates/ruff_linter/src/rules/pyflakes/rules/if_tuple.rs index c6c74f978d..f0f874bb39 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/if_tuple.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/if_tuple.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, StmtIf}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::stmt_if::if_elif_branches; use ruff_text_size::Ranged; @@ -47,6 +47,6 @@ pub(crate) fn if_tuple(checker: &Checker, stmt_if: &StmtIf) { if tuple.is_empty() { continue; } - checker.report_diagnostic(Diagnostic::new(IfTuple, branch.test.range())); + checker.report_diagnostic(IfTuple, branch.test.range()); } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/invalid_literal_comparisons.rs b/crates/ruff_linter/src/rules/pyflakes/rules/invalid_literal_comparisons.rs index 5a0417a157..15b6c97467 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/invalid_literal_comparisons.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/invalid_literal_comparisons.rs @@ -1,6 +1,6 @@ use anyhow::{Error, bail}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers; use ruff_python_ast::{CmpOp, Expr}; @@ -90,7 +90,8 @@ pub(crate) fn invalid_literal_comparison( || helpers::is_mutable_iterable_initializer(left) || helpers::is_mutable_iterable_initializer(right)) { - let mut diagnostic = Diagnostic::new(IsLiteral { cmp_op: op.into() }, expr.range()); + let mut diagnostic = + checker.report_diagnostic(IsLiteral { cmp_op: op.into() }, expr.range()); if lazy_located.is_none() { lazy_located = Some(locate_cmp_ops(expr, checker.tokens())); } @@ -117,7 +118,6 @@ pub(crate) fn invalid_literal_comparison( bail!("Failed to fix invalid comparison due to missing op") } }); - checker.report_diagnostic(diagnostic); } left = right; } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/invalid_print_syntax.rs b/crates/ruff_linter/src/rules/pyflakes/rules/invalid_print_syntax.rs index ea5e0d3e79..ef2faac12b 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/invalid_print_syntax.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/invalid_print_syntax.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_text_size::Ranged; @@ -59,6 +59,6 @@ impl Violation for InvalidPrintSyntax { /// F633 pub(crate) fn invalid_print_syntax(checker: &Checker, left: &Expr) { if checker.semantic().match_builtin_expr(left, "print") { - checker.report_diagnostic(Diagnostic::new(InvalidPrintSyntax, left.range())); + checker.report_diagnostic(InvalidPrintSyntax, left.range()); } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/raise_not_implemented.rs b/crates/ruff_linter/src/rules/pyflakes/rules/raise_not_implemented.rs index 84fd99decc..a66ebda003 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/raise_not_implemented.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/raise_not_implemented.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -74,7 +74,7 @@ pub(crate) fn raise_not_implemented(checker: &Checker, expr: &Expr) { let Some(expr) = match_not_implemented(expr) else { return; }; - let mut diagnostic = Diagnostic::new(RaiseNotImplemented, expr.range()); + let mut diagnostic = checker.report_diagnostic(RaiseNotImplemented, expr.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol( "NotImplementedError", @@ -86,5 +86,4 @@ pub(crate) fn raise_not_implemented(checker: &Checker, expr: &Expr) { import_edit, )) }); - checker.report_diagnostic(diagnostic); } 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 0beeb7293f..a0e22fcc15 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/repeated_keys.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/repeated_keys.rs @@ -1,7 +1,7 @@ use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet}; use std::collections::hash_map::Entry; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::{ComparableExpr, HashableExpr}; use ruff_python_ast::parenthesize::parenthesized_range; @@ -177,7 +177,7 @@ pub(crate) fn repeated_keys(checker: &Checker, dict: &ast::ExprDict) { | Expr::Tuple(_) | Expr::FString(_) => { if checker.enabled(Rule::MultiValueRepeatedKeyLiteral) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MultiValueRepeatedKeyLiteral { name: SourceCodeSnippet::from_str(checker.locator().slice(key)), existing: SourceCodeSnippet::from_str( @@ -206,12 +206,11 @@ pub(crate) fn repeated_keys(checker: &Checker, dict: &ast::ExprDict) { .end(), ))); } - checker.report_diagnostic(diagnostic); } } Expr::Name(_) => { if checker.enabled(Rule::MultiValueRepeatedKeyVariable) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MultiValueRepeatedKeyVariable { name: SourceCodeSnippet::from_str(checker.locator().slice(key)), }, @@ -238,7 +237,6 @@ pub(crate) fn repeated_keys(checker: &Checker, dict: &ast::ExprDict) { .end(), ))); } - checker.report_diagnostic(diagnostic); } } _ => {} diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/starred_expressions.rs b/crates/ruff_linter/src/rules/pyflakes/rules/starred_expressions.rs index fb7e04f20b..d9db11fc8f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/starred_expressions.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/starred_expressions.rs @@ -1,9 +1,11 @@ use ruff_python_ast::Expr; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for the use of too many expressions in starred assignment statements. /// @@ -54,17 +56,19 @@ impl Violation for MultipleStarredExpressions { /// F621, F622 pub(crate) fn starred_expressions( + checker: &Checker, elts: &[Expr], check_too_many_expressions: bool, check_two_starred_expressions: bool, location: TextRange, -) -> Option { +) { let mut has_starred: bool = false; let mut starred_index: Option = None; for (index, elt) in elts.iter().enumerate() { if elt.is_starred_expr() { if has_starred && check_two_starred_expressions { - return Some(Diagnostic::new(MultipleStarredExpressions, location)); + checker.report_diagnostic(MultipleStarredExpressions, location); + return; } has_starred = true; starred_index = Some(index); @@ -74,10 +78,8 @@ pub(crate) fn starred_expressions( if check_too_many_expressions { if let Some(starred_index) = starred_index { if starred_index >= 1 << 8 || elts.len() - starred_index > 1 << 24 { - return Some(Diagnostic::new(ExpressionsInStarAssignment, location)); + checker.report_diagnostic(ExpressionsInStarAssignment, location); } } } - - None } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/strings.rs b/crates/ruff_linter/src/rules/pyflakes/rules/strings.rs index 4dde25b703..ad50e058ec 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/strings.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/strings.rs @@ -2,7 +2,7 @@ use std::string::ToString; use rustc_hash::FxHashSet; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr, Keyword}; @@ -539,7 +539,7 @@ pub(crate) fn percent_format_expected_mapping( | Expr::ListComp(_) | Expr::SetComp(_) | Expr::Generator(_) => { - checker.report_diagnostic(Diagnostic::new(PercentFormatExpectedMapping, location)); + checker.report_diagnostic(PercentFormatExpectedMapping, location); } _ => {} } @@ -554,7 +554,7 @@ pub(crate) fn percent_format_expected_sequence( location: TextRange, ) { if summary.num_positional > 1 && matches!(right, Expr::Dict(_) | Expr::DictComp(_)) { - checker.report_diagnostic(Diagnostic::new(PercentFormatExpectedSequence, location)); + checker.report_diagnostic(PercentFormatExpectedSequence, location); } } @@ -599,7 +599,7 @@ pub(crate) fn percent_format_extra_named_arguments( .iter() .map(|(_, name)| (*name).to_string()) .collect(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PercentFormatExtraNamedArguments { missing: names }, location, ); @@ -613,7 +613,6 @@ pub(crate) fn percent_format_extra_named_arguments( )?; Ok(Fix::safe_edit(edit)) }); - checker.report_diagnostic(diagnostic); } /// F505 @@ -654,12 +653,12 @@ pub(crate) fn percent_format_missing_arguments( .collect(); if !missing.is_empty() { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PercentFormatMissingArgument { missing: missing.iter().map(|&s| s.clone()).collect(), }, location, - )); + ); } } @@ -670,10 +669,7 @@ pub(crate) fn percent_format_mixed_positional_and_named( location: TextRange, ) { if !(summary.num_positional == 0 || summary.keywords.is_empty()) { - checker.report_diagnostic(Diagnostic::new( - PercentFormatMixedPositionalAndNamed, - location, - )); + checker.report_diagnostic(PercentFormatMixedPositionalAndNamed, location); } } @@ -698,13 +694,13 @@ pub(crate) fn percent_format_positional_count_mismatch( } if found != summary.num_positional { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( PercentFormatPositionalCountMismatch { wanted: summary.num_positional, got: found, }, location, - )); + ); } } } @@ -718,8 +714,9 @@ pub(crate) fn percent_format_star_requires_sequence( ) { if summary.starred { match right { - Expr::Dict(_) | Expr::DictComp(_) => checker - .report_diagnostic(Diagnostic::new(PercentFormatStarRequiresSequence, location)), + Expr::Dict(_) | Expr::DictComp(_) => { + checker.report_diagnostic(PercentFormatStarRequiresSequence, location); + } _ => {} } } @@ -757,7 +754,7 @@ pub(crate) fn string_dot_format_extra_named_arguments( } let names: Vec = missing.iter().map(|(_, name)| (*name).clone()).collect(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( StringDotFormatExtraNamedArguments { missing: names }, call.range(), ); @@ -771,7 +768,6 @@ pub(crate) fn string_dot_format_extra_named_arguments( )?; Ok(Fix::safe_edit(edit)) }); - checker.report_diagnostic(diagnostic); } /// F523 @@ -819,7 +815,7 @@ pub(crate) fn string_dot_format_extra_positional_arguments( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( StringDotFormatExtraPositionalArguments { missing: missing .iter() @@ -840,8 +836,6 @@ pub(crate) fn string_dot_format_extra_positional_arguments( Ok(Fix::safe_edit(edit)) }); } - - checker.report_diagnostic(diagnostic); } /// F524 @@ -880,10 +874,7 @@ pub(crate) fn string_dot_format_missing_argument( .collect(); if !missing.is_empty() { - checker.report_diagnostic(Diagnostic::new( - StringDotFormatMissingArguments { missing }, - call.range(), - )); + checker.report_diagnostic(StringDotFormatMissingArguments { missing }, call.range()); } } @@ -894,9 +885,6 @@ pub(crate) fn string_dot_format_mixing_automatic( summary: &FormatSummary, ) { if !(summary.autos.is_empty() || summary.indices.is_empty()) { - checker.report_diagnostic(Diagnostic::new( - StringDotFormatMixingAutomatic, - call.range(), - )); + checker.report_diagnostic(StringDotFormatMixingAutomatic, call.range()); } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/undefined_local.rs b/crates/ruff_linter/src/rules/pyflakes/rules/undefined_local.rs index 7a01716e90..9b37ba4b8f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/undefined_local.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/undefined_local.rs @@ -1,6 +1,6 @@ use std::string::ToString; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Scope, ScopeId}; use ruff_text_size::Ranged; @@ -62,12 +62,12 @@ pub(crate) fn undefined_local(checker: &Checker, scope_id: ScopeId, scope: &Scop } }) { // Then it's probably an error. - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UndefinedLocal { name: name.to_string(), }, range, - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/unused_annotation.rs b/crates/ruff_linter/src/rules/pyflakes/rules/unused_annotation.rs index 1494650747..b37175a02c 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/unused_annotation.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/unused_annotation.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Scope; use ruff_text_size::Ranged; @@ -46,6 +46,6 @@ pub(crate) fn unused_annotation(checker: &Checker, scope: &Scope) { None } }) { - checker.report_diagnostic(Diagnostic::new(UnusedAnnotation { name }, range)); + checker.report_diagnostic(UnusedAnnotation { name }, range); } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/unused_import.rs b/crates/ruff_linter/src/rules/pyflakes/rules/unused_import.rs index d996fdedc6..ff0c15a2af 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/unused_import.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/unused_import.rs @@ -4,7 +4,7 @@ use std::iter; use anyhow::{Result, anyhow, bail}; use std::collections::BTreeMap; -use ruff_diagnostics::{Applicability, Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Stmt}; @@ -425,7 +425,7 @@ pub(crate) fn unused_import(checker: &Checker, scope: &Scope) { iter::zip(to_remove, iter::repeat(fix_remove)), iter::zip(to_reexport, iter::repeat(fix_reexport)), ) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnusedImport { name: binding.import.qualified_name().to_string(), module: binding.import.member_name().to_string(), @@ -444,14 +444,13 @@ pub(crate) fn unused_import(checker: &Checker, scope: &Scope) { diagnostic.set_fix(fix.clone()); } } - checker.report_diagnostic(diagnostic); } } // Separately, generate a diagnostic for every _ignored_ import, to ensure that the // suppression comments aren't marked as unused. for binding in ignored.into_values().flatten() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnusedImport { name: binding.import.qualified_name().to_string(), module: binding.import.member_name().to_string(), @@ -465,7 +464,6 @@ pub(crate) fn unused_import(checker: &Checker, scope: &Scope) { if let Some(range) = binding.parent_range { diagnostic.set_parent(range.start()); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/unused_variable.rs b/crates/ruff_linter/src/rules/pyflakes/rules/unused_variable.rs index 2305eaf043..16c1c69b11 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/unused_variable.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/unused_variable.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::contains_effect; use ruff_python_ast::parenthesize::parenthesized_range; @@ -256,7 +256,7 @@ pub(crate) fn unused_variable(checker: &Checker, name: &str, binding: &Binding) return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnusedVariable { name: name.to_string(), }, @@ -265,5 +265,4 @@ pub(crate) fn unused_variable(checker: &Checker, name: &str, binding: &Binding) if let Some(fix) = remove_unused_variable(binding, checker) { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pygrep_hooks/rules/invalid_mock_access.rs b/crates/ruff_linter/src/rules/pygrep_hooks/rules/invalid_mock_access.rs index 79527c586f..ca1ec153c4 100644 --- a/crates/ruff_linter/src/rules/pygrep_hooks/rules/invalid_mock_access.rs +++ b/crates/ruff_linter/src/rules/pygrep_hooks/rules/invalid_mock_access.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -61,12 +61,12 @@ pub(crate) fn uncalled_mock_method(checker: &Checker, expr: &Expr) { | "assert_has_calls" | "assert_not_called" ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( InvalidMockAccess { reason: Reason::UncalledMethod(attr.to_string()), }, expr.range(), - )); + ); } } } @@ -90,11 +90,11 @@ pub(crate) fn non_existent_mock_method(checker: &Checker, test: &Expr) { | "has_calls" | "not_called" ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( InvalidMockAccess { reason: Reason::NonExistentMethod(attr.to_string()), }, test.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/assert_on_string_literal.rs b/crates/ruff_linter/src/rules/pylint/rules/assert_on_string_literal.rs index 2673a57bae..648d535f9d 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/assert_on_string_literal.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/assert_on_string_literal.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -49,7 +49,7 @@ impl Violation for AssertOnStringLiteral { pub(crate) fn assert_on_string_literal(checker: &Checker, test: &Expr) { match test { Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( AssertOnStringLiteral { kind: if value.is_empty() { Kind::Empty @@ -58,10 +58,10 @@ pub(crate) fn assert_on_string_literal(checker: &Checker, test: &Expr) { }, }, test.range(), - )); + ); } Expr::BytesLiteral(ast::ExprBytesLiteral { value, .. }) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( AssertOnStringLiteral { kind: if value.is_empty() { Kind::Empty @@ -70,7 +70,7 @@ pub(crate) fn assert_on_string_literal(checker: &Checker, test: &Expr) { }, }, test.range(), - )); + ); } Expr::FString(ast::ExprFString { value, .. }) => { let kind = if value.iter().all(|f_string_part| match f_string_part { @@ -100,10 +100,7 @@ pub(crate) fn assert_on_string_literal(checker: &Checker, test: &Expr) { } else { Kind::Unknown }; - checker.report_diagnostic(Diagnostic::new( - AssertOnStringLiteral { kind }, - test.range(), - )); + checker.report_diagnostic(AssertOnStringLiteral { kind }, test.range()); } _ => {} } diff --git a/crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs b/crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs index e833be1c7d..1c9c613cad 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; @@ -82,10 +82,10 @@ pub(crate) fn bad_dunder_method_name(checker: &Checker, method: &ast::StmtFuncti return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadDunderMethodName { name: method.name.to_string(), }, method.identifier(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/bad_open_mode.rs b/crates/ruff_linter/src/rules/pylint/rules/bad_open_mode.rs index d9900cea2a..75d0e47fd5 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/bad_open_mode.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/bad_open_mode.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; @@ -66,12 +66,12 @@ pub(crate) fn bad_open_mode(checker: &Checker, call: &ast::ExprCall) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadOpenMode { mode: value.to_string(), }, mode.range(), - )); + ); } #[derive(Debug, Copy, Clone)] diff --git a/crates/ruff_linter/src/rules/pylint/rules/bad_staticmethod_argument.rs b/crates/ruff_linter/src/rules/pylint/rules/bad_staticmethod_argument.rs index 937b5846ea..f2abd808ff 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/bad_staticmethod_argument.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/bad_staticmethod_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::ParameterWithDefault; @@ -101,10 +101,10 @@ pub(crate) fn bad_staticmethod_argument(checker: &Checker, scope: &Scope) { _ => return, } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadStaticmethodArgument { argument_name: self_or_cls.name.to_string(), }, self_or_cls.range(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/bad_str_strip_call.rs b/crates/ruff_linter/src/rules/pylint/rules/bad_str_strip_call.rs index 94e700223e..7ce68b0af3 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/bad_str_strip_call.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/bad_str_strip_call.rs @@ -3,7 +3,7 @@ use std::fmt; use ruff_python_ast::{self as ast, Expr}; use rustc_hash::FxHashSet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::typing; @@ -211,7 +211,5 @@ pub(crate) fn bad_str_strip_call(checker: &Checker, call: &ast::ExprCall) { None }; - let diagnostic = Diagnostic::new(BadStrStripCall { strip, removal }, arg.range()); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(BadStrStripCall { strip, removal }, arg.range()); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_character.rs b/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_character.rs index 6d853115ca..a31731b4f9 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_character.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_character.rs @@ -1,6 +1,6 @@ use std::str::FromStr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprStringLiteral, StringFlags, StringLiteral}; use ruff_python_literal::{ @@ -50,7 +50,7 @@ pub(crate) fn call(checker: &Checker, string: &str, range: TextRange) { match FormatSpec::parse(format_spec) { Err(FormatSpecError::InvalidFormatType) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadStringFormatCharacter { // The format type character is always the last one. // More info in the official spec: @@ -58,7 +58,7 @@ pub(crate) fn call(checker: &Checker, string: &str, range: TextRange) { format_char: format_spec.chars().last().unwrap(), }, range, - )); + ); } Err(_) => {} Ok(FormatSpec::Static(_)) => {} @@ -70,7 +70,7 @@ pub(crate) fn call(checker: &Checker, string: &str, range: TextRange) { if let Err(FormatSpecError::InvalidFormatType) = FormatSpec::parse(&format_spec) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( BadStringFormatCharacter { // The format type character is always the last one. // More info in the official spec: @@ -78,7 +78,7 @@ pub(crate) fn call(checker: &Checker, string: &str, range: TextRange) { format_char: format_spec.chars().last().unwrap(), }, range, - )); + ); } } } @@ -103,10 +103,7 @@ pub(crate) fn percent(checker: &Checker, expr: &Expr, format_string: &ExprString // Parse the format string (e.g. `"%s"`) into a list of `PercentFormat`. if let Err(format_error) = CFormatString::from_str(string) { if let CFormatErrorType::UnsupportedFormatChar(format_char) = format_error.typ { - checker.report_diagnostic(Diagnostic::new( - BadStringFormatCharacter { format_char }, - expr.range(), - )); + checker.report_diagnostic(BadStringFormatCharacter { format_char }, expr.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs b/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs index e11c9e7f4f..e61c796945 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs @@ -5,7 +5,7 @@ use ruff_python_literal::cformat::{CFormatPart, CFormatSpec, CFormatStrOrBytes, use ruff_text_size::Ranged; use rustc_hash::FxHashMap; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; @@ -240,6 +240,6 @@ pub(crate) fn bad_string_format_type( _ => is_valid_constant(&format_strings, &bin_op.right), }; if !is_valid { - checker.report_diagnostic(Diagnostic::new(BadStringFormatType, bin_op.range())); + checker.report_diagnostic(BadStringFormatType, bin_op.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/binary_op_exception.rs b/crates/ruff_linter/src/rules/pylint/rules/binary_op_exception.rs index 1b1ad85c10..f7b074c9a8 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/binary_op_exception.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/binary_op_exception.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -76,8 +76,5 @@ pub(crate) fn binary_op_exception(checker: &Checker, except_handler: &ExceptHand return; }; - checker.report_diagnostic(Diagnostic::new( - BinaryOpException { op: op.into() }, - type_.range(), - )); + checker.report_diagnostic(BinaryOpException { op: op.into() }, type_.range()); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/boolean_chained_comparison.rs b/crates/ruff_linter/src/rules/pylint/rules/boolean_chained_comparison.rs index f3affe97f7..ca6ae6ab94 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/boolean_chained_comparison.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/boolean_chained_comparison.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ BoolOp, CmpOp, Expr, ExprBoolOp, ExprCompare, @@ -69,97 +69,92 @@ pub(crate) fn boolean_chained_comparison(checker: &Checker, expr_bool_op: &ExprB .iter() .map(|expr| expr.as_compare_expr().unwrap()); - let diagnostics = compare_expressions - .tuple_windows() - .filter(|(left_compare, right_compare)| { - are_compare_expr_simplifiable(left_compare, right_compare) - }) - .filter_map(|(left_compare, right_compare)| { - let Expr::Name(left_compare_right) = left_compare.comparators.last()? else { - return None; - }; + for (left_compare, right_compare) in + compare_expressions + .tuple_windows() + .filter(|(left_compare, right_compare)| { + are_compare_expr_simplifiable(left_compare, right_compare) + }) + { + let Some(Expr::Name(left_compare_right)) = left_compare.comparators.last() else { + continue; + }; - let Expr::Name(right_compare_left) = &*right_compare.left else { - return None; - }; + let Expr::Name(right_compare_left) = &*right_compare.left else { + continue; + }; - if left_compare_right.id() != right_compare_left.id() { - return None; + if left_compare_right.id() != right_compare_left.id() { + continue; + } + + let left_paren_count = parentheses_iterator( + left_compare.into(), + Some(expr_bool_op.into()), + comment_ranges, + locator.contents(), + ) + .count(); + + let right_paren_count = parentheses_iterator( + right_compare.into(), + Some(expr_bool_op.into()), + comment_ranges, + locator.contents(), + ) + .count(); + + // Create the edit that removes the comparison operator + + // In `a<(b) and ((b)) { + let balance_parens_edit = Edit::insertion( + "(".repeat(right_paren_count - left_paren_count), + left_compare.start(), + ); + Fix::safe_edits(edit, [balance_parens_edit]) } + std::cmp::Ordering::Equal => Fix::safe_edit(edit), + std::cmp::Ordering::Greater => { + let balance_parens_edit = Edit::insertion( + ")".repeat(left_paren_count - right_paren_count), + right_compare.end(), + ); + Fix::safe_edits(edit, [balance_parens_edit]) + } + }; - let left_paren_count = parentheses_iterator( - left_compare.into(), - Some(expr_bool_op.into()), - comment_ranges, - locator.contents(), - ) - .count(); + let mut diagnostic = checker.report_diagnostic( + BooleanChainedComparison, + TextRange::new(left_compare.start(), right_compare.end()), + ); - let right_paren_count = parentheses_iterator( - right_compare.into(), - Some(expr_bool_op.into()), - comment_ranges, - locator.contents(), - ) - .count(); - - // Create the edit that removes the comparison operator - - // In `a<(b) and ((b)) { - let balance_parens_edit = Edit::insertion( - "(".repeat(right_paren_count - left_paren_count), - left_compare.start(), - ); - Fix::safe_edits(edit, [balance_parens_edit]) - } - std::cmp::Ordering::Equal => Fix::safe_edit(edit), - std::cmp::Ordering::Greater => { - let balance_parens_edit = Edit::insertion( - ")".repeat(left_paren_count - right_paren_count), - right_compare.end(), - ); - Fix::safe_edits(edit, [balance_parens_edit]) - } - }; - - let mut diagnostic = Diagnostic::new( - BooleanChainedComparison, - TextRange::new(left_compare.start(), right_compare.end()), - ); - - diagnostic.set_fix(fix); - - Some(diagnostic) - }); - - for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); + diagnostic.set_fix(fix); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/collapsible_else_if.rs b/crates/ruff_linter/src/rules/pylint/rules/collapsible_else_if.rs index aab8ae7935..2a356816a5 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/collapsible_else_if.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/collapsible_else_if.rs @@ -1,7 +1,7 @@ use anyhow::Result; use ast::whitespace::indentation; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, ElifElseClause, Stmt}; use ruff_python_codegen::Stylist; @@ -82,7 +82,7 @@ pub(crate) fn collapsible_else_if(checker: &Checker, stmt: &Stmt) { return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CollapsibleElseIf, TextRange::new(else_clause.start(), first.start()), ); @@ -95,7 +95,6 @@ pub(crate) fn collapsible_else_if(checker: &Checker, stmt: &Stmt) { checker.stylist(), ) }); - checker.report_diagnostic(diagnostic); } /// Generate [`Fix`] to convert an `else` block to an `elif` block. diff --git a/crates/ruff_linter/src/rules/pylint/rules/compare_to_empty_string.rs b/crates/ruff_linter/src/rules/pylint/rules/compare_to_empty_string.rs index 2dc495ff90..d880f8033a 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/compare_to_empty_string.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/compare_to_empty_string.rs @@ -2,7 +2,7 @@ use anyhow::bail; use itertools::Itertools; use ruff_python_ast::{self as ast, CmpOp, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -89,13 +89,13 @@ pub(crate) fn compare_to_empty_string( let expr = checker.generator().expr(rhs); let existing = format!("{literal} {op} {expr}"); let replacement = format!("{}{expr}", op.into_unary()); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( CompareToEmptyString { existing, replacement, }, lhs.range(), - )); + ); } } } @@ -107,13 +107,13 @@ pub(crate) fn compare_to_empty_string( let literal = checker.generator().expr(rhs); let existing = format!("{expr} {op} {literal}"); let replacement = format!("{}{expr}", op.into_unary()); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( CompareToEmptyString { existing, replacement, }, rhs.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/comparison_of_constant.rs b/crates/ruff_linter/src/rules/pylint/rules/comparison_of_constant.rs index 2d3662e04a..7d01f9ba8c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/comparison_of_constant.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/comparison_of_constant.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use ruff_python_ast::{CmpOp, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -62,7 +62,7 @@ pub(crate) fn comparison_of_constant( .zip(ops) { if left.is_literal_expr() && right.is_literal_expr() { - let diagnostic = Diagnostic::new( + checker.report_diagnostic( ComparisonOfConstant { left_constant: checker.generator().expr(left), op: *op, @@ -70,8 +70,6 @@ pub(crate) fn comparison_of_constant( }, left.range(), ); - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/comparison_with_itself.rs b/crates/ruff_linter/src/rules/pylint/rules/comparison_with_itself.rs index 24538dcd51..a5b3f01f03 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/comparison_with_itself.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/comparison_with_itself.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use crate::fix::snippet::SourceCodeSnippet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{CmpOp, Expr}; use ruff_text_size::Ranged; @@ -67,12 +67,12 @@ pub(crate) fn comparison_with_itself( op, checker.locator().slice(right) ); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( ComparisonWithItself { actual: SourceCodeSnippet::new(actual), }, left_name.range(), - )); + ); } // Ex) `id(foo) == id(foo)` (Expr::Call(left_call), Expr::Call(right_call)) => { @@ -115,12 +115,12 @@ pub(crate) fn comparison_with_itself( op, checker.locator().slice(right) ); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( ComparisonWithItself { actual: SourceCodeSnippet::new(actual), }, left_call.range(), - )); + ); } } _ => {} diff --git a/crates/ruff_linter/src/rules/pylint/rules/continue_in_finally.rs b/crates/ruff_linter/src/rules/pylint/rules/continue_in_finally.rs index 67637df202..f71970f7db 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/continue_in_finally.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/continue_in_finally.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -49,7 +49,7 @@ impl Violation for ContinueInFinally { fn traverse_body(checker: &Checker, body: &[Stmt]) { for stmt in body { if stmt.is_continue_stmt() { - checker.report_diagnostic(Diagnostic::new(ContinueInFinally, stmt.range())); + checker.report_diagnostic(ContinueInFinally, stmt.range()); } match stmt { diff --git a/crates/ruff_linter/src/rules/pylint/rules/dict_index_missing_items.rs b/crates/ruff_linter/src/rules/pylint/rules/dict_index_missing_items.rs index 0f6eb1150e..54039e19c4 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/dict_index_missing_items.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/dict_index_missing_items.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::{ @@ -86,8 +86,7 @@ pub(crate) fn dict_index_missing_items(checker: &Checker, stmt_for: &ast::StmtFo }; if has_violation { - let diagnostic = Diagnostic::new(DictIndexMissingItems, stmt_for.range()); - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(DictIndexMissingItems, stmt_for.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/dict_iter_missing_items.rs b/crates/ruff_linter/src/rules/pylint/rules/dict_iter_missing_items.rs index ce1deda042..4ea558f94b 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/dict_iter_missing_items.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/dict_iter_missing_items.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, Stmt}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::typing::is_dict; use ruff_python_semantic::{Binding, SemanticModel}; @@ -94,12 +94,11 @@ pub(crate) fn dict_iter_missing_items(checker: &Checker, target: &Expr, iter: &E return; } - let mut diagnostic = Diagnostic::new(DictIterMissingItems, iter.range()); + let mut diagnostic = checker.report_diagnostic(DictIterMissingItems, iter.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("{}.items()", name.id), iter.range(), ))); - checker.report_diagnostic(diagnostic); } /// Returns true if the binding is a dictionary where each key is a tuple with two elements. diff --git a/crates/ruff_linter/src/rules/pylint/rules/duplicate_bases.rs b/crates/ruff_linter/src/rules/pylint/rules/duplicate_bases.rs index 22f456723e..721be4d36e 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/duplicate_bases.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/duplicate_bases.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Arguments, Expr}; use rustc_hash::{FxBuildHasher, FxHashSet}; -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -67,7 +67,7 @@ pub(crate) fn duplicate_bases(checker: &Checker, name: &str, arguments: Option<& for base in bases { if let Expr::Name(ast::ExprName { id, .. }) = base { if !seen.insert(id) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DuplicateBases { base: id.to_string(), class: name.to_string(), @@ -83,7 +83,6 @@ pub(crate) fn duplicate_bases(checker: &Checker, name: &str, arguments: Option<& ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/eq_without_hash.rs b/crates/ruff_linter/src/rules/pylint/rules/eq_without_hash.rs index 48627534e8..4a50be69c2 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/eq_without_hash.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/eq_without_hash.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ Expr, ExprName, Identifier, StmtAnnAssign, StmtAssign, StmtClassDef, StmtFunctionDef, @@ -122,8 +122,7 @@ pub(crate) fn object_without_hash_method(checker: &Checker, class: &StmtClassDef hash: HasMethod::No } ) { - let diagnostic = Diagnostic::new(EqWithoutHash, class.name.range()); - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(EqWithoutHash, class.name.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/global_at_module_level.rs b/crates/ruff_linter/src/rules/pylint/rules/global_at_module_level.rs index 0a897c16f0..4c3d6304b6 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/global_at_module_level.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/global_at_module_level.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; @@ -27,6 +27,6 @@ impl Violation for GlobalAtModuleLevel { /// PLW0604 pub(crate) fn global_at_module_level(checker: &Checker, stmt: &Stmt) { if checker.semantic().current_scope().kind.is_module() { - checker.report_diagnostic(Diagnostic::new(GlobalAtModuleLevel, stmt.range())); + checker.report_diagnostic(GlobalAtModuleLevel, stmt.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/global_statement.rs b/crates/ruff_linter/src/rules/pylint/rules/global_statement.rs index 11d7d5e41e..6ef6a8c97a 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/global_statement.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/global_statement.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -55,13 +55,13 @@ impl Violation for GlobalStatement { /// PLW0603 pub(crate) fn global_statement(checker: &Checker, name: &str) { if let Some(range) = checker.semantic().global(name) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( GlobalStatement { name: name.to_string(), }, // Match Pylint's behavior by reporting on the `global` statement`, rather // than the variable usage. range, - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/if_stmt_min_max.rs b/crates/ruff_linter/src/rules/pylint/rules/if_stmt_min_max.rs index a47be005e0..dae0f80732 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/if_stmt_min_max.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/if_stmt_min_max.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::parenthesize::parenthesized_range; @@ -176,7 +176,7 @@ pub(crate) fn if_stmt_min_max(checker: &Checker, stmt_if: &ast::StmtIf) { checker.locator().slice(arg2), ); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfStmtMinMax { min_max, replacement: SourceCodeSnippet::from_str(replacement.as_str()), @@ -197,8 +197,6 @@ pub(crate) fn if_stmt_min_max(checker: &Checker, stmt_if: &ast::StmtIf) { applicability, )); } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] 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 a5dbffb420..f0d96e724f 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; @@ -84,7 +84,7 @@ pub(crate) fn import_outside_top_level(checker: &Checker, stmt: &Stmt) { } // Emit the diagnostic - checker.report_diagnostic(Diagnostic::new(ImportOutsideTopLevel, stmt.range())); + checker.report_diagnostic(ImportOutsideTopLevel, stmt.range()); } fn is_banned_module_level_import(policy: &NameMatchPolicy, checker: &Checker) -> bool { diff --git a/crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs b/crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs index b465fdd54b..f70d744c1b 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use itertools::Itertools; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_semantic::{FromImport, Import, Imported, ResolvedReference, Scope}; @@ -136,10 +136,7 @@ pub(crate) fn import_private_name(checker: &Checker, scope: &Scope) { } else { None }; - checker.report_diagnostic(Diagnostic::new( - ImportPrivateName { name, module }, - binding.range(), - )); + checker.report_diagnostic(ImportPrivateName { name, module }, binding.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/import_self.rs b/crates/ruff_linter/src/rules/pylint/rules/import_self.rs index c20b16c20c..1897f237f4 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/import_self.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/import_self.rs @@ -1,10 +1,12 @@ use ruff_python_ast::Alias; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::resolve_imported_module_path; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for import statements that import the current module. /// @@ -35,30 +37,36 @@ impl Violation for ImportSelf { } /// PLW0406 -pub(crate) fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Option { - let module_path = module_path?; +pub(crate) fn import_self(checker: &Checker, alias: &Alias, module_path: Option<&[String]>) { + let Some(module_path) = module_path else { + return; + }; if alias.name.split('.').eq(module_path) { - return Some(Diagnostic::new( + checker.report_diagnostic( ImportSelf { name: alias.name.to_string(), }, alias.range(), - )); + ); } - - None } /// PLW0406 pub(crate) fn import_from_self( + checker: &Checker, level: u32, module: Option<&str>, names: &[Alias], module_path: Option<&[String]>, -) -> Option { - let module_path = module_path?; - let imported_module_path = resolve_imported_module_path(level, module, Some(module_path))?; +) { + let Some(module_path) = module_path else { + return; + }; + let Some(imported_module_path) = resolve_imported_module_path(level, module, Some(module_path)) + else { + return; + }; if imported_module_path .split('.') @@ -68,14 +76,12 @@ pub(crate) fn import_from_self( .iter() .find(|alias| alias.name == module_path[module_path.len() - 1]) { - return Some(Diagnostic::new( + checker.report_diagnostic( ImportSelf { name: format!("{}.{}", imported_module_path, alias.name), }, alias.range(), - )); + ); } } - - None } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_all_format.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_all_format.rs index a5a364f8ac..78a1095fdd 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_all_format.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_all_format.rs @@ -1,8 +1,10 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Binding; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for invalid assignments to `__all__`. /// @@ -36,10 +38,8 @@ impl Violation for InvalidAllFormat { } /// PLE0605 -pub(crate) fn invalid_all_format(binding: &Binding) -> Option { +pub(crate) fn invalid_all_format(checker: &Checker, binding: &Binding) { if binding.is_invalid_all_format() { - Some(Diagnostic::new(InvalidAllFormat, binding.range())) - } else { - None + checker.report_diagnostic(InvalidAllFormat, binding.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_all_object.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_all_object.rs index 40536e2602..3e77db9956 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_all_object.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_all_object.rs @@ -1,8 +1,10 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Binding; use ruff_text_size::Ranged; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for the inclusion of invalid objects in `__all__`. /// @@ -36,10 +38,8 @@ impl Violation for InvalidAllObject { } /// PLE0604 -pub(crate) fn invalid_all_object(binding: &Binding) -> Option { +pub(crate) fn invalid_all_object(checker: &Checker, binding: &Binding) { if binding.is_invalid_all_object() { - Some(Diagnostic::new(InvalidAllObject, binding.range())) - } else { - None + checker.report_diagnostic(InvalidAllObject, binding.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_bool_return.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_bool_return.rs index 4f0d0442eb..967c41394a 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_bool_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_bool_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -68,10 +68,7 @@ pub(crate) fn invalid_bool_return(checker: &Checker, function_def: &ast::StmtFun // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { - checker.report_diagnostic(Diagnostic::new( - InvalidBoolReturnType, - function_def.identifier(), - )); + checker.report_diagnostic(InvalidBoolReturnType, function_def.identifier()); return; } @@ -88,11 +85,11 @@ pub(crate) fn invalid_bool_return(checker: &Checker, function_def: &ast::StmtFun ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Bool)) ) { - checker.report_diagnostic(Diagnostic::new(InvalidBoolReturnType, value.range())); + checker.report_diagnostic(InvalidBoolReturnType, value.range()); } } else { // Disallow implicit `None`. - checker.report_diagnostic(Diagnostic::new(InvalidBoolReturnType, stmt.range())); + checker.report_diagnostic(InvalidBoolReturnType, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_bytes_return.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_bytes_return.rs index deb5d58cdc..2b57f30983 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_bytes_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_bytes_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -68,10 +68,7 @@ pub(crate) fn invalid_bytes_return(checker: &Checker, function_def: &ast::StmtFu // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { - checker.report_diagnostic(Diagnostic::new( - InvalidBytesReturnType, - function_def.identifier(), - )); + checker.report_diagnostic(InvalidBytesReturnType, function_def.identifier()); return; } @@ -87,11 +84,11 @@ pub(crate) fn invalid_bytes_return(checker: &Checker, function_def: &ast::StmtFu ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Bytes) ) { - checker.report_diagnostic(Diagnostic::new(InvalidBytesReturnType, value.range())); + checker.report_diagnostic(InvalidBytesReturnType, value.range()); } } else { // Disallow implicit `None`. - checker.report_diagnostic(Diagnostic::new(InvalidBytesReturnType, stmt.range())); + checker.report_diagnostic(InvalidBytesReturnType, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_default.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_default.rs index a6984b817f..66ab20d2b5 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_default.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_default.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; @@ -70,6 +70,6 @@ pub(crate) fn invalid_envvar_default(checker: &Checker, call: &ast::ExprCall) { ) { return; } - checker.report_diagnostic(Diagnostic::new(InvalidEnvvarDefault, expr.range())); + checker.report_diagnostic(InvalidEnvvarDefault, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_value.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_value.rs index 68d2999270..52dfa3365d 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_value.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_value.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; @@ -58,6 +58,6 @@ pub(crate) fn invalid_envvar_value(checker: &Checker, call: &ast::ExprCall) { return; } - checker.report_diagnostic(Diagnostic::new(InvalidEnvvarValue, expr.range())); + checker.report_diagnostic(InvalidEnvvarValue, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs index 89fff4d2bb..ca88a11b67 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -72,10 +72,7 @@ pub(crate) fn invalid_hash_return(checker: &Checker, function_def: &ast::StmtFun // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { - checker.report_diagnostic(Diagnostic::new( - InvalidHashReturnType, - function_def.identifier(), - )); + checker.report_diagnostic(InvalidHashReturnType, function_def.identifier()); return; } @@ -92,11 +89,11 @@ pub(crate) fn invalid_hash_return(checker: &Checker, function_def: &ast::StmtFun ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ) { - checker.report_diagnostic(Diagnostic::new(InvalidHashReturnType, value.range())); + checker.report_diagnostic(InvalidHashReturnType, value.range()); } } else { // Disallow implicit `None`. - checker.report_diagnostic(Diagnostic::new(InvalidHashReturnType, stmt.range())); + checker.report_diagnostic(InvalidHashReturnType, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_index_return.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_index_return.rs index cd3f64a16b..edc3ebd166 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_index_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_index_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -74,10 +74,7 @@ pub(crate) fn invalid_index_return(checker: &Checker, function_def: &ast::StmtFu // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { - checker.report_diagnostic(Diagnostic::new( - InvalidIndexReturnType, - function_def.identifier(), - )); + checker.report_diagnostic(InvalidIndexReturnType, function_def.identifier()); return; } @@ -94,11 +91,11 @@ pub(crate) fn invalid_index_return(checker: &Checker, function_def: &ast::StmtFu ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ) { - checker.report_diagnostic(Diagnostic::new(InvalidIndexReturnType, value.range())); + checker.report_diagnostic(InvalidIndexReturnType, value.range()); } } else { // Disallow implicit `None`. - checker.report_diagnostic(Diagnostic::new(InvalidIndexReturnType, stmt.range())); + checker.report_diagnostic(InvalidIndexReturnType, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_length_return.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_length_return.rs index bfe11d45e6..cc5ca4c402 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_length_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_length_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -73,10 +73,7 @@ pub(crate) fn invalid_length_return(checker: &Checker, function_def: &ast::StmtF // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { - checker.report_diagnostic(Diagnostic::new( - InvalidLengthReturnType, - function_def.identifier(), - )); + checker.report_diagnostic(InvalidLengthReturnType, function_def.identifier()); return; } @@ -95,11 +92,11 @@ pub(crate) fn invalid_length_return(checker: &Checker, function_def: &ast::StmtF | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ) { - checker.report_diagnostic(Diagnostic::new(InvalidLengthReturnType, value.range())); + checker.report_diagnostic(InvalidLengthReturnType, value.range()); } } else { // Disallow implicit `None`. - checker.report_diagnostic(Diagnostic::new(InvalidLengthReturnType, stmt.range())); + checker.report_diagnostic(InvalidLengthReturnType, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/invalid_str_return.rs b/crates/ruff_linter/src/rules/pylint/rules/invalid_str_return.rs index 5e07f2bfd7..f102d5305b 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/invalid_str_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/invalid_str_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; @@ -68,10 +68,7 @@ pub(crate) fn invalid_str_return(checker: &Checker, function_def: &ast::StmtFunc // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { - checker.report_diagnostic(Diagnostic::new( - InvalidStrReturnType, - function_def.identifier(), - )); + checker.report_diagnostic(InvalidStrReturnType, function_def.identifier()); return; } @@ -87,11 +84,11 @@ pub(crate) fn invalid_str_return(checker: &Checker, function_def: &ast::StmtFunc ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::String) ) { - checker.report_diagnostic(Diagnostic::new(InvalidStrReturnType, value.range())); + checker.report_diagnostic(InvalidStrReturnType, value.range()); } } else { // Disallow implicit `None`. - checker.report_diagnostic(Diagnostic::new(InvalidStrReturnType, stmt.range())); + checker.report_diagnostic(InvalidStrReturnType, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs b/crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs index f3511e25b1..96a8ff2040 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs @@ -1,6 +1,6 @@ use rustc_hash::{FxBuildHasher, FxHashSet}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_ast::comparable::HashableExpr; @@ -63,7 +63,7 @@ pub(crate) fn iteration_over_set(checker: &Checker, expr: &Expr) { } } - let mut diagnostic = Diagnostic::new(IterationOverSet, expr.range()); + let mut diagnostic = checker.report_diagnostic(IterationOverSet, expr.range()); let tuple = if let [elt] = set.elts.as_slice() { let elt = checker.locator().slice(elt); @@ -73,6 +73,4 @@ pub(crate) fn iteration_over_set(checker: &Checker, expr: &Expr) { format!("({})", &set[1..set.len() - 1]) }; diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(tuple, expr.range()))); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/len_test.rs b/crates/ruff_linter/src/rules/pylint/rules/len_test.rs index 9aaa1177de..f1e586b8a6 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/len_test.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/len_test.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::fix::snippet::SourceCodeSnippet; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall}; use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType}; @@ -90,18 +90,17 @@ pub(crate) fn len_test(checker: &Checker, call: &ExprCall) { let replacement = checker.locator().slice(argument.range()).to_string(); - checker.report_diagnostic( - Diagnostic::new( + checker + .report_diagnostic( LenTest { expression: SourceCodeSnippet::new(replacement.clone()), }, call.range(), ) - .with_fix(Fix::safe_edit(Edit::range_replacement( + .set_fix(Fix::safe_edit(Edit::range_replacement( replacement, call.range(), - ))), - ); + ))); } fn is_indirect_sequence(expr: &Expr, semantic: &SemanticModel) -> bool { diff --git a/crates/ruff_linter/src/rules/pylint/rules/literal_membership.rs b/crates/ruff_linter/src/rules/pylint/rules/literal_membership.rs index 10777dbd12..9d398694da 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/literal_membership.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/literal_membership.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr}; use ruff_python_semantic::analyze::typing; @@ -101,7 +101,7 @@ pub(crate) fn literal_membership(checker: &Checker, compare: &ast::ExprCompare) return; } - let mut diagnostic = Diagnostic::new(LiteralMembership, right.range()); + let mut diagnostic = checker.report_diagnostic(LiteralMembership, right.range()); let literal = checker.locator().slice(right); let set = format!("{{{}}}", &literal[1..literal.len() - 1]); @@ -109,6 +109,4 @@ pub(crate) fn literal_membership(checker: &Checker, compare: &ast::ExprCompare) set, right.range(), ))); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/logging.rs b/crates/ruff_linter/src/rules/pylint/rules/logging.rs index 80ba1fdddd..326ca4a073 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/logging.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/logging.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::analyze::logging; @@ -154,13 +154,13 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { if checker.enabled(Rule::LoggingTooManyArgs) { if summary.num_positional < num_message_args { - checker.report_diagnostic(Diagnostic::new(LoggingTooManyArgs, call.func.range())); + checker.report_diagnostic(LoggingTooManyArgs, call.func.range()); } } if checker.enabled(Rule::LoggingTooFewArgs) { if num_message_args > 0 && num_keywords == 0 && summary.num_positional > num_message_args { - checker.report_diagnostic(Diagnostic::new(LoggingTooFewArgs, call.func.range())); + checker.report_diagnostic(LoggingTooFewArgs, call.func.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/magic_value_comparison.rs b/crates/ruff_linter/src/rules/pylint/rules/magic_value_comparison.rs index 96cfe2d3d3..258455bdb0 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/magic_value_comparison.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/magic_value_comparison.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use ruff_python_ast::{self as ast, Expr, Int, LiteralExpressionRef, UnaryOp}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -111,12 +111,12 @@ pub(crate) fn magic_value_comparison(checker: &Checker, left: &Expr, comparators for comparison_expr in std::iter::once(left).chain(comparators) { if let Some(value) = as_literal(comparison_expr) { if is_magic_value(value, &checker.settings.pylint.allow_magic_value_types) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( MagicValueComparison { value: checker.locator().slice(comparison_expr).to_string(), }, comparison_expr.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/manual_import_from.rs b/crates/ruff_linter/src/rules/pylint/rules/manual_import_from.rs index 0d4db4219a..0b8659aaee 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/manual_import_from.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/manual_import_from.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Alias, Identifier, Stmt}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -58,7 +58,7 @@ pub(crate) fn manual_from_import(checker: &Checker, stmt: &Stmt, alias: &Alias, return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ManualFromImport { module: module.to_string(), name: name.to_string(), @@ -81,5 +81,4 @@ pub(crate) fn manual_from_import(checker: &Checker, stmt: &Stmt, alias: &Alias, stmt.range(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/misplaced_bare_raise.rs b/crates/ruff_linter/src/rules/pylint/rules/misplaced_bare_raise.rs index 7191e4149c..99bc0483bc 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/misplaced_bare_raise.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/misplaced_bare_raise.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; @@ -64,5 +64,5 @@ pub(crate) fn misplaced_bare_raise(checker: &Checker, raise: &ast::StmtRaise) { return; } - checker.report_diagnostic(Diagnostic::new(MisplacedBareRaise, raise.range())); + checker.report_diagnostic(MisplacedBareRaise, raise.range()); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/modified_iterating_set.rs b/crates/ruff_linter/src/rules/pylint/rules/modified_iterating_set.rs index a2647678ca..10e1ad9dbb 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/modified_iterating_set.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/modified_iterating_set.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_body; use ruff_python_ast::name::Name; @@ -97,7 +97,7 @@ pub(crate) fn modified_iterating_set(checker: &Checker, for_stmt: &StmtFor) { }); if is_modified { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ModifiedIteratingSet { name: name.id.clone(), }, @@ -107,7 +107,6 @@ pub(crate) fn modified_iterating_set(checker: &Checker, for_stmt: &StmtFor) { format!("{}.copy()", checker.locator().slice(name)), name.range(), ))); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/named_expr_without_context.rs b/crates/ruff_linter/src/rules/pylint/rules/named_expr_without_context.rs index df784953ae..0c6a0361b7 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/named_expr_without_context.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/named_expr_without_context.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -37,6 +37,6 @@ impl Violation for NamedExprWithoutContext { /// PLW0131 pub(crate) fn named_expr_without_context(checker: &Checker, value: &Expr) { if let Expr::Named(ast::ExprNamed { range, .. }) = value { - checker.report_diagnostic(Diagnostic::new(NamedExprWithoutContext, *range)); + checker.report_diagnostic(NamedExprWithoutContext, *range); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs b/crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs index 31f2dceeb6..e645097a05 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; @@ -66,26 +66,17 @@ fn nan_comparison_impl<'a>(checker: &Checker, comparators: impl Iterator { - checker.report_diagnostic(Diagnostic::new( - NanComparison { nan: Nan::NumPy }, - expr.range(), - )); + checker.report_diagnostic(NanComparison { nan: Nan::NumPy }, expr.range()); } ["math", "nan"] => { - checker.report_diagnostic(Diagnostic::new( - NanComparison { nan: Nan::Math }, - expr.range(), - )); + checker.report_diagnostic(NanComparison { nan: Nan::Math }, expr.range()); } _ => continue, } } if is_nan_float(expr, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new( - NanComparison { nan: Nan::Math }, - expr.range(), - )); + checker.report_diagnostic(NanComparison { nan: Nan::Math }, expr.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/nested_min_max.rs b/crates/ruff_linter/src/rules/pylint/rules/nested_min_max.rs index b4e11ca833..e2f6f9d28e 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/nested_min_max.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/nested_min_max.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Arguments, Expr, Keyword}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::SemanticModel; @@ -169,7 +169,8 @@ pub(crate) fn nested_min_max( }; MinMax::try_from_call(func.as_ref(), keywords.as_ref(), checker.semantic()) == Some(min_max) }) { - let mut diagnostic = Diagnostic::new(NestedMinMax { func: min_max }, expr.range()); + let mut diagnostic = + checker.report_diagnostic(NestedMinMax { func: min_max }, expr.range()); if !checker .comment_ranges() .has_comments(expr, checker.source()) @@ -188,6 +189,5 @@ pub(crate) fn nested_min_max( expr.range(), ))); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs b/crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs index 6fae8631fe..bca6480e7a 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr, Stmt}; @@ -172,8 +172,10 @@ fn get_undecorated_methods(checker: &Checker, class_stmt: &Stmt, method_type: &M let range = TextRange::new(stmt.range().start(), stmt.range().start()); let mut diagnostic = match method_type { - MethodType::Classmethod => Diagnostic::new(NoClassmethodDecorator, range), - MethodType::Staticmethod => Diagnostic::new(NoStaticmethodDecorator, range), + MethodType::Classmethod => checker.report_diagnostic(NoClassmethodDecorator, range), + MethodType::Staticmethod => { + checker.report_diagnostic(NoStaticmethodDecorator, range) + } }; let indentation = indentation_at_offset(stmt.range().start(), checker.source()); @@ -192,7 +194,6 @@ fn get_undecorated_methods(checker: &Checker, class_stmt: &Stmt, method_type: &M checker.indexer(), )], )); - checker.report_diagnostic(diagnostic); } None => { continue; diff --git a/crates/ruff_linter/src/rules/pylint/rules/no_self_use.rs b/crates/ruff_linter/src/rules/pylint/rules/no_self_use.rs index e81857a6fe..c18bfd1c02 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/no_self_use.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/no_self_use.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; @@ -126,11 +126,11 @@ pub(crate) fn no_self_use(checker: &Checker, scope_id: ScopeId, scope: &Scope) { .map(|binding_id| semantic.binding(binding_id)) .is_some_and(|binding| binding.kind.is_argument() && binding.is_unused()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NoSelfUse { method_name: name.to_string(), }, func.identifier(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/non_ascii_module_import.rs b/crates/ruff_linter/src/rules/pylint/rules/non_ascii_module_import.rs index cfb983e90d..33e164d950 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/non_ascii_module_import.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/non_ascii_module_import.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Alias; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -69,24 +69,24 @@ pub(crate) fn non_ascii_module_import(checker: &Checker, alias: &Alias) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NonAsciiImportName { name: asname.to_string(), kind: Kind::Aliased, }, asname.range(), - )); + ); } else { if alias.name.as_str().is_ascii() { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NonAsciiImportName { name: alias.name.to_string(), kind: Kind::Unaliased, }, alias.name.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/non_ascii_name.rs b/crates/ruff_linter/src/rules/pylint/rules/non_ascii_name.rs index fbc6f2b14c..d1f2fd19ab 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/non_ascii_name.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/non_ascii_name.rs @@ -1,11 +1,11 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Binding, BindingKind}; use ruff_text_size::Ranged; -use crate::Locator; +use crate::checkers::ast::Checker; /// ## What it does /// Checks for the use of non-ASCII characters in variable names. @@ -44,10 +44,11 @@ impl Violation for NonAsciiName { } /// PLC2401 -pub(crate) fn non_ascii_name(binding: &Binding, locator: &Locator) -> Option { +pub(crate) fn non_ascii_name(checker: &Checker, binding: &Binding) { + let locator = checker.locator(); let name = binding.name(locator.contents()); if name.is_ascii() { - return None; + return; } let kind = match binding.kind { @@ -73,17 +74,17 @@ pub(crate) fn non_ascii_name(binding: &Binding, locator: &Locator) -> Option { - return None; + return; } }; - Some(Diagnostic::new( + checker.report_diagnostic( NonAsciiName { name: name.to_string(), kind, }, binding.range(), - )) + ); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] diff --git a/crates/ruff_linter/src/rules/pylint/rules/non_augmented_assignment.rs b/crates/ruff_linter/src/rules/pylint/rules/non_augmented_assignment.rs index 567a5b509e..d96461609e 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/non_augmented_assignment.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/non_augmented_assignment.rs @@ -1,5 +1,5 @@ use ast::Expr; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::comparable::ComparableExpr; @@ -101,7 +101,8 @@ pub(crate) fn non_augmented_assignment(checker: &Checker, assign: &ast::StmtAssi // Match, e.g., `x = x + 1`. if ComparableExpr::from(target) == ComparableExpr::from(&value.left) { - let mut diagnostic = Diagnostic::new(NonAugmentedAssignment { operator }, assign.range()); + let mut diagnostic = + checker.report_diagnostic(NonAugmentedAssignment { operator }, assign.range()); diagnostic.set_fix(Fix::unsafe_edit(augmented_assignment( checker, target, @@ -110,7 +111,7 @@ pub(crate) fn non_augmented_assignment(checker: &Checker, assign: &ast::StmtAssi value, assign.range, ))); - checker.report_diagnostic(diagnostic); + return; } @@ -120,7 +121,8 @@ pub(crate) fn non_augmented_assignment(checker: &Checker, assign: &ast::StmtAssi && (value.left.is_number_literal_expr() || value.left.is_boolean_literal_expr()) && ComparableExpr::from(target) == ComparableExpr::from(&value.right) { - let mut diagnostic = Diagnostic::new(NonAugmentedAssignment { operator }, assign.range()); + let mut diagnostic = + checker.report_diagnostic(NonAugmentedAssignment { operator }, assign.range()); diagnostic.set_fix(Fix::unsafe_edit(augmented_assignment( checker, target, @@ -129,7 +131,6 @@ pub(crate) fn non_augmented_assignment(checker: &Checker, assign: &ast::StmtAssi value, assign.range, ))); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/non_slot_assignment.rs b/crates/ruff_linter/src/rules/pylint/rules/non_slot_assignment.rs index 76a831efdf..ec75d836d3 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/non_slot_assignment.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/non_slot_assignment.rs @@ -1,6 +1,6 @@ use rustc_hash::FxHashSet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::{Ranged, TextRange}; @@ -74,12 +74,12 @@ pub(crate) fn non_slot_assignment(checker: &Checker, class_def: &ast::StmtClassD } for attribute in is_attributes_not_in_slots(&class_def.body) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NonSlotAssignment { name: attribute.name.to_string(), }, attribute.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/nonlocal_and_global.rs b/crates/ruff_linter/src/rules/pylint/rules/nonlocal_and_global.rs index 737c1fd092..060d1715e4 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/nonlocal_and_global.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/nonlocal_and_global.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; @@ -59,12 +59,12 @@ pub(crate) fn nonlocal_and_global(checker: &Checker, nonlocal: &ast::StmtNonloca // `global`. for name in &nonlocal.names { if let Some(global) = checker.semantic().global(name) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( NonlocalAndGlobal { name: name.to_string(), }, global, - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs b/crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs index 816fa6e5ca..060e3bce45 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -66,6 +66,6 @@ pub(crate) fn potential_index_error(checker: &Checker, value: &Expr, slice: &Exp // Emit a diagnostic if the index is out of bounds. If the index can't be represented as an // `i64`, but the length _can_, then the index is definitely out of bounds. if index.is_none_or(|index| index >= length || index < -length) { - checker.report_diagnostic(Diagnostic::new(PotentialIndexError, slice.range())); + checker.report_diagnostic(PotentialIndexError, slice.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/property_with_parameters.rs b/crates/ruff_linter/src/rules/pylint/rules/property_with_parameters.rs index 262fea2342..cb1d589064 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/property_with_parameters.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/property_with_parameters.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Decorator, Parameters, Stmt, identifier::Identifier}; use ruff_python_semantic::analyze::visibility::is_property; @@ -57,6 +57,6 @@ pub(crate) fn property_with_parameters( let semantic = checker.semantic(); let extra_property_decorators = checker.settings.pydocstyle.property_decorators(); if is_property(decorator_list, extra_property_decorators, semantic) { - checker.report_diagnostic(Diagnostic::new(PropertyWithParameters, stmt.identifier())); + checker.report_diagnostic(PropertyWithParameters, stmt.identifier()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/redeclared_assigned_name.rs b/crates/ruff_linter/src/rules/pylint/rules/redeclared_assigned_name.rs index d63b1a5806..64a5e1823a 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/redeclared_assigned_name.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/redeclared_assigned_name.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_text_size::Ranged; @@ -63,12 +63,12 @@ fn check_expr(checker: &Checker, expr: &Expr, names: &mut Vec) { return; } if names.contains(id) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RedeclaredAssignedName { name: id.to_string(), }, expr.range(), - )); + ); } names.push(id.clone()); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/redefined_loop_name.rs b/crates/ruff_linter/src/rules/pylint/rules/redefined_loop_name.rs index 3d46e8b768..1a55ecc21c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/redefined_loop_name.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/redefined_loop_name.rs @@ -3,7 +3,7 @@ use std::{fmt, iter}; use regex::Regex; use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Stmt, WithItem}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; @@ -385,14 +385,14 @@ pub(crate) fn redefined_loop_name(checker: &Checker, stmt: &Stmt) { if ComparableExpr::from(outer_assignment_target.expr) .eq(&(ComparableExpr::from(inner_assignment_target.expr))) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RedefinedLoopName { name: checker.generator().expr(outer_assignment_target.expr), outer_kind: outer_assignment_target.binding_kind, inner_kind: inner_assignment_target.binding_kind, }, inner_assignment_target.expr.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/redefined_slots_in_subclass.rs b/crates/ruff_linter/src/rules/pylint/rules/redefined_slots_in_subclass.rs index 675045a73d..b0273d2a4d 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/redefined_slots_in_subclass.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/redefined_slots_in_subclass.rs @@ -3,7 +3,7 @@ use std::hash::Hash; use ruff_python_semantic::analyze::class::iter_super_class; use rustc_hash::FxHashSet; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::{Ranged, TextRange}; @@ -104,13 +104,13 @@ impl Ranged for Slot<'_> { fn check_super_slots(checker: &Checker, class_def: &ast::StmtClassDef, slot: &Slot) { for super_class in iter_super_class(class_def, checker.semantic()).skip(1) { if slots_members(&super_class.body).contains(slot) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RedefinedSlotsInSubclass { base: super_class.name.to_string(), slot_name: slot.name.to_string(), }, slot.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/repeated_equality_comparison.rs b/crates/ruff_linter/src/rules/pylint/rules/repeated_equality_comparison.rs index 3a7f4c7805..61371a3607 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/repeated_equality_comparison.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/repeated_equality_comparison.rs @@ -2,7 +2,7 @@ use itertools::Itertools; use rustc_hash::{FxBuildHasher, FxHashMap}; use ast::ExprContext; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::{any_over_expr, contains_effect}; @@ -139,7 +139,7 @@ pub(crate) fn repeated_equality_comparison(checker: &Checker, bool_op: &ast::Exp .iter() .all(|comparator| comparator.is_literal_expr()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RepeatedEqualityComparison { expression: SourceCodeSnippet::new(merged_membership_test( expr, @@ -193,8 +193,6 @@ pub(crate) fn repeated_equality_comparison(checker: &Checker, bool_op: &ast::Exp })), bool_op.range(), ))); - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/repeated_keyword_argument.rs b/crates/ruff_linter/src/rules/pylint/rules/repeated_keyword_argument.rs index 80fb83c911..434b30c19c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/repeated_keyword_argument.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/repeated_keyword_argument.rs @@ -1,6 +1,6 @@ use rustc_hash::{FxBuildHasher, FxHashSet}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprCall, ExprStringLiteral}; use ruff_text_size::Ranged; @@ -44,24 +44,24 @@ pub(crate) fn repeated_keyword_argument(checker: &Checker, call: &ExprCall) { if let Some(id) = &keyword.arg { // Ex) `func(a=1, a=2)` if !seen.insert(id.as_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RepeatedKeywordArgument { duplicate_keyword: id.to_string(), }, keyword.range(), - )); + ); } } else if let Expr::Dict(dict) = &keyword.value { // Ex) `func(**{"a": 1, "a": 2})` for key in dict.iter_keys().flatten() { if let Expr::StringLiteral(ExprStringLiteral { value, .. }) = key { if !seen.insert(value.to_str()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( RepeatedKeywordArgument { duplicate_keyword: value.to_string(), }, key.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/return_in_init.rs b/crates/ruff_linter/src/rules/pylint/rules/return_in_init.rs index 11f05ca9f3..ee3398dfa4 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/return_in_init.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/return_in_init.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -59,6 +59,6 @@ pub(crate) fn return_in_init(checker: &Checker, stmt: &Stmt) { } if in_dunder_method("__init__", checker.semantic(), checker.settings) { - checker.report_diagnostic(Diagnostic::new(ReturnInInit, stmt.range())); + checker.report_diagnostic(ReturnInInit, stmt.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/self_assigning_variable.rs b/crates/ruff_linter/src/rules/pylint/rules/self_assigning_variable.rs index d5d9117bb8..9cedeae300 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/self_assigning_variable.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/self_assigning_variable.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use ruff_python_ast::{self as ast, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -79,12 +79,12 @@ fn visit_assignments(checker: &Checker, left: &Expr, right: &Expr) { Expr::Name(ast::ExprName { id: lhs_name, .. }), Expr::Name(ast::ExprName { id: rhs_name, .. }), ) if lhs_name == rhs_name => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( SelfAssigningVariable { name: lhs_name.to_string(), }, left.range(), - )); + ); } _ => {} } diff --git a/crates/ruff_linter/src/rules/pylint/rules/self_or_cls_assignment.rs b/crates/ruff_linter/src/rules/pylint/rules/self_or_cls_assignment.rs index aead8c0939..df4db639e9 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/self_or_cls_assignment.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/self_or_cls_assignment.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::ScopeKind; @@ -117,10 +117,7 @@ fn check_expr(checker: &Checker, target: &Expr, method_type: MethodType) { Expr::Name(_) => { if let Expr::Name(ast::ExprName { id, .. }) = target { if id.as_str() == method_type.arg_name() { - checker.report_diagnostic(Diagnostic::new( - SelfOrClsAssignment { method_type }, - target.range(), - )); + checker.report_diagnostic(SelfOrClsAssignment { method_type }, target.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/shallow_copy_environ.rs b/crates/ruff_linter/src/rules/pylint/rules/shallow_copy_environ.rs index 46c3b821c8..7517b651ec 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/shallow_copy_environ.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/shallow_copy_environ.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::Modules; @@ -88,10 +88,9 @@ pub(crate) fn shallow_copy_environ(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(ShallowCopyEnviron, call.range()); + let mut diagnostic = checker.report_diagnostic(ShallowCopyEnviron, call.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("{}.copy()", checker.locator().slice(arg)), call.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/single_string_slots.rs b/crates/ruff_linter/src/rules/pylint/rules/single_string_slots.rs index 83c28bc452..73265be1e0 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/single_string_slots.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/single_string_slots.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Stmt, StmtClassDef}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; @@ -66,10 +66,7 @@ pub(crate) fn single_string_slots(checker: &Checker, class: &StmtClassDef) { if let Expr::Name(ast::ExprName { id, .. }) = target { if id.as_str() == "__slots__" { if matches!(value.as_ref(), Expr::StringLiteral(_) | Expr::FString(_)) { - checker.report_diagnostic(Diagnostic::new( - SingleStringSlots, - stmt.identifier(), - )); + checker.report_diagnostic(SingleStringSlots, stmt.identifier()); } } } @@ -83,10 +80,7 @@ pub(crate) fn single_string_slots(checker: &Checker, class: &StmtClassDef) { if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() { if id.as_str() == "__slots__" { if matches!(value.as_ref(), Expr::StringLiteral(_) | Expr::FString(_)) { - checker.report_diagnostic(Diagnostic::new( - SingleStringSlots, - stmt.identifier(), - )); + checker.report_diagnostic(SingleStringSlots, stmt.identifier()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/singledispatch_method.rs b/crates/ruff_linter/src/rules/pylint/rules/singledispatch_method.rs index adf728ec82..33d0227937 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/singledispatch_method.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/singledispatch_method.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Scope; @@ -99,7 +99,7 @@ pub(crate) fn singledispatch_method(checker: &Checker, scope: &Scope) { matches!(qualified_name.segments(), ["functools", "singledispatch"]) }) { - let mut diagnostic = Diagnostic::new(SingledispatchMethod, decorator.range()); + let mut diagnostic = checker.report_diagnostic(SingledispatchMethod, decorator.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("functools", "singledispatchmethod"), @@ -111,7 +111,6 @@ pub(crate) fn singledispatch_method(checker: &Checker, scope: &Scope) { [import_edit], )) }); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/singledispatchmethod_function.rs b/crates/ruff_linter/src/rules/pylint/rules/singledispatchmethod_function.rs index c8cacdf7e5..0e740b9148 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/singledispatchmethod_function.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/singledispatchmethod_function.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Scope; @@ -95,7 +95,8 @@ pub(crate) fn singledispatchmethod_function(checker: &Checker, scope: &Scope) { ) }) { - let mut diagnostic = Diagnostic::new(SingledispatchmethodFunction, decorator.range()); + let mut diagnostic = + checker.report_diagnostic(SingledispatchmethodFunction, decorator.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("functools", "singledispatch"), @@ -107,7 +108,6 @@ pub(crate) fn singledispatchmethod_function(checker: &Checker, scope: &Scope) { [import_edit], )) }); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/subprocess_popen_preexec_fn.rs b/crates/ruff_linter/src/rules/pylint/rules/subprocess_popen_preexec_fn.rs index 3a06bac852..f3a0a0bd50 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/subprocess_popen_preexec_fn.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/subprocess_popen_preexec_fn.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; @@ -65,7 +65,7 @@ pub(crate) fn subprocess_popen_preexec_fn(checker: &Checker, call: &ast::ExprCal .find_keyword("preexec_fn") .filter(|keyword| !keyword.value.is_none_literal_expr()) { - checker.report_diagnostic(Diagnostic::new(SubprocessPopenPreexecFn, keyword.range())); + checker.report_diagnostic(SubprocessPopenPreexecFn, keyword.range()); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/subprocess_run_without_check.rs b/crates/ruff_linter/src/rules/pylint/rules/subprocess_run_without_check.rs index e3ec7b6e0a..2235997533 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/subprocess_run_without_check.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/subprocess_run_without_check.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; @@ -71,7 +71,8 @@ pub(crate) fn subprocess_run_without_check(checker: &Checker, call: &ast::ExprCa .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["subprocess", "run"])) { if call.arguments.find_keyword("check").is_none() { - let mut diagnostic = Diagnostic::new(SubprocessRunWithoutCheck, call.func.range()); + let mut diagnostic = + checker.report_diagnostic(SubprocessRunWithoutCheck, call.func.range()); diagnostic.set_fix(Fix::applicable_edit( add_argument( "check=False", @@ -91,7 +92,6 @@ pub(crate) fn subprocess_run_without_check(checker: &Checker, call: &ast::ExprCa Applicability::Safe }, )); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/super_without_brackets.rs b/crates/ruff_linter/src/rules/pylint/rules/super_without_brackets.rs index e8ca774a34..9bd206c4b8 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/super_without_brackets.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/super_without_brackets.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::{ScopeKind, analyze::function_type}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -108,12 +108,10 @@ pub(crate) fn super_without_brackets(checker: &Checker, func: &Expr) { return; } - let mut diagnostic = Diagnostic::new(SuperWithoutBrackets, value.range()); + let mut diagnostic = checker.report_diagnostic(SuperWithoutBrackets, value.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "super()".to_string(), value.range(), ))); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/sys_exit_alias.rs b/crates/ruff_linter/src/rules/pylint/rules/sys_exit_alias.rs index 997faa5314..93e6ee00dd 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/sys_exit_alias.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/sys_exit_alias.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::importer::ImportRequest; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprCall; @@ -77,7 +77,7 @@ pub(crate) fn sys_exit_alias(checker: &Checker, call: &ExprCall) { if !matches!(builtin, "exit" | "quit") { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( SysExitAlias { name: builtin.to_string(), }, @@ -91,7 +91,6 @@ pub(crate) fn sys_exit_alias(checker: &Checker, call: &ExprCall) { .any(|kwarg| kwarg.arg.is_none()); // only one optional argument allowed, and we can't convert **kwargs if call.arguments.len() > 1 || has_star_kwargs { - checker.report_diagnostic(diagnostic); return; } @@ -111,5 +110,4 @@ pub(crate) fn sys_exit_alias(checker: &Checker, call: &ExprCall) { } Ok(Fix::unsafe_edits(import_edit, edits)) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_arguments.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_arguments.rs index 8c36893561..58d4fd938e 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_arguments.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_arguments.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; @@ -108,11 +108,11 @@ pub(crate) fn too_many_arguments(checker: &Checker, function_def: &ast::StmtFunc return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyArguments { c_args: num_arguments, max_args: checker.settings.pylint.max_args, }, function_def.identifier(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_boolean_expressions.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_boolean_expressions.rs index 225d53aee6..1780b99159 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_boolean_expressions.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_boolean_expressions.rs @@ -1,5 +1,5 @@ use ast::{Expr, StmtIf}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; @@ -47,13 +47,13 @@ pub(crate) fn too_many_boolean_expressions(checker: &Checker, stmt: &StmtIf) { if let Some(bool_op) = stmt.test.as_bool_op_expr() { let expressions = count_bools(bool_op); if expressions > checker.settings.pylint.max_bool_expr { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyBooleanExpressions { expressions, max_expressions: checker.settings.pylint.max_bool_expr, }, bool_op.range(), - )); + ); } } @@ -61,13 +61,13 @@ pub(crate) fn too_many_boolean_expressions(checker: &Checker, stmt: &StmtIf) { if let Some(bool_op) = elif.test.as_ref().and_then(Expr::as_bool_op_expr) { let expressions = count_bools(bool_op); if expressions > checker.settings.pylint.max_bool_expr { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyBooleanExpressions { expressions, max_expressions: checker.settings.pylint.max_bool_expr, }, bool_op.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs index 73cddc644c..529e6fda2c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs @@ -1,9 +1,11 @@ use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for functions or methods with too many branches, including (nested) /// `if`, `elif`, and `else` branches, `for` loops, `try`-`except` clauses, and @@ -233,21 +235,20 @@ fn num_branches(stmts: &[Stmt]) -> usize { /// PLR0912 pub(crate) fn too_many_branches( + checker: &Checker, stmt: &Stmt, body: &[Stmt], max_branches: usize, -) -> Option { +) { let branches = num_branches(body); if branches > max_branches { - Some(Diagnostic::new( + checker.report_diagnostic( TooManyBranches { branches, max_branches, }, stmt.identifier(), - )) - } else { - None + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_locals.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_locals.rs index c0bdcaffff..43079c8375 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_locals.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_locals.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::{Scope, ScopeKind}; @@ -47,13 +47,13 @@ pub(crate) fn too_many_locals(checker: &Checker, scope: &Scope) { .count(); if num_locals > checker.settings.pylint.max_locals { if let ScopeKind::Function(func) = scope.kind { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyLocals { current_amount: num_locals, max_amount: checker.settings.pylint.max_locals, }, func.identifier(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_nested_blocks.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_nested_blocks.rs index e554678462..80900f84f8 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_nested_blocks.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_nested_blocks.rs @@ -1,5 +1,5 @@ use ast::ExceptHandler; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Stmt}; use ruff_text_size::Ranged; @@ -74,13 +74,13 @@ pub(crate) fn too_many_nested_blocks(checker: &Checker, stmt: &Stmt) { return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyNestedBlocks { nested_blocks: count, max_nested_blocks, }, checker.semantic().statement(root_id).range(), - )); + ); } /// Returns `true` if the given statement is a nested block. diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_positional_arguments.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_positional_arguments.rs index 79e05dae55..39b0e9dfbf 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_positional_arguments.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_positional_arguments.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, identifier::Identifier}; use ruff_python_semantic::analyze::{function_type, visibility}; @@ -112,11 +112,11 @@ pub(crate) fn too_many_positional_arguments( return; } - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyPositionalArguments { c_pos: num_positional_args, max_pos: checker.settings.pylint.max_positional_args, }, function_def.identifier(), - )); + ); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_public_methods.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_public_methods.rs index 5853ad0264..0e6a58db94 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_public_methods.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_public_methods.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::analyze::visibility::{self, Visibility::Public}; @@ -121,12 +121,12 @@ pub(crate) fn too_many_public_methods( .count(); if methods > max_methods { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TooManyPublicMethods { methods, max_methods, }, class_def.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_return_statements.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_return_statements.rs index 7c7f85d417..14e29b82a6 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_return_statements.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_return_statements.rs @@ -1,11 +1,13 @@ use ruff_python_ast::Stmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for functions or methods with too many return statements. /// @@ -77,21 +79,20 @@ fn num_returns(body: &[Stmt]) -> usize { /// PLR0911 pub(crate) fn too_many_return_statements( + checker: &Checker, stmt: &Stmt, body: &[Stmt], max_returns: usize, -) -> Option { +) { let returns = num_returns(body); if returns > max_returns { - Some(Diagnostic::new( + checker.report_diagnostic( TooManyReturnStatements { returns, max_returns, }, stmt.identifier(), - )) - } else { - None + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs b/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs index 2ec7c7b3d3..c0b0337418 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs @@ -1,9 +1,11 @@ use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; +use crate::checkers::ast::Checker; + /// ## What it does /// Checks for functions or methods with too many statements. /// @@ -137,21 +139,20 @@ fn num_statements(stmts: &[Stmt]) -> usize { /// PLR0915 pub(crate) fn too_many_statements( + checker: &Checker, stmt: &Stmt, body: &[Stmt], max_statements: usize, -) -> Option { +) { let statements = num_statements(body); if statements > max_statements { - Some(Diagnostic::new( + checker.report_diagnostic( TooManyStatements { statements, max_statements, }, stmt.identifier(), - )) - } else { - None + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/type_bivariance.rs b/crates/ruff_linter/src/rules/pylint/rules/type_bivariance.rs index 5801e86688..2a92cb9893 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/type_bivariance.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/type_bivariance.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::{self as ast, Expr}; @@ -124,13 +124,13 @@ pub(crate) fn type_bivariance(checker: &Checker, value: &Expr) { return; }; - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TypeBivariance { kind, param_name: type_param_name(arguments).map(ToString::to_string), }, func.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/type_name_incorrect_variance.rs b/crates/ruff_linter/src/rules/pylint/rules/type_name_incorrect_variance.rs index 08efd64b7d..96c63658cd 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/type_name_incorrect_variance.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/type_name_incorrect_variance.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::{self as ast, Expr}; @@ -128,7 +128,7 @@ pub(crate) fn type_name_incorrect_variance(checker: &Checker, value: &Expr) { VarVariance::Invariance => name_root.to_string(), }; - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TypeNameIncorrectVariance { kind, param_name: param_name.to_string(), @@ -136,7 +136,7 @@ pub(crate) fn type_name_incorrect_variance(checker: &Checker, value: &Expr) { replacement_name, }, func.range(), - )); + ); } /// Returns `true` if the parameter name does not match its type variance. diff --git a/crates/ruff_linter/src/rules/pylint/rules/type_param_name_mismatch.rs b/crates/ruff_linter/src/rules/pylint/rules/type_param_name_mismatch.rs index 722590a517..5dfe9f22c4 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/type_param_name_mismatch.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/type_param_name_mismatch.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -119,14 +119,14 @@ pub(crate) fn type_param_name_mismatch(checker: &Checker, value: &Expr, targets: return; }; - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( TypeParamNameMismatch { kind, var_name: var_name.to_string(), param_name: param_name.to_string(), }, value.range(), - )); + ); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] diff --git a/crates/ruff_linter/src/rules/pylint/rules/unexpected_special_method_signature.rs b/crates/ruff_linter/src/rules/pylint/rules/unexpected_special_method_signature.rs index 0dfb437aee..ba1db43a1c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unexpected_special_method_signature.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unexpected_special_method_signature.rs @@ -2,7 +2,7 @@ use std::cmp::Ordering; use ruff_python_ast::{Decorator, Parameters, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility::is_staticmethod; @@ -186,13 +186,13 @@ pub(crate) fn unexpected_special_method_signature( }; if !valid_signature { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnexpectedSpecialMethodSignature { method_name: name.to_owned(), expected_params, actual_params, }, stmt.identifier(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dict_index_lookup.rs b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dict_index_lookup.rs index 46e2485c65..aa610bb280 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dict_index_lookup.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dict_index_lookup.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, StmtFor}; @@ -59,12 +59,11 @@ pub(crate) fn unnecessary_dict_index_lookup(checker: &Checker, stmt_for: &StmtFo }; for range in ranges { - let mut diagnostic = Diagnostic::new(UnnecessaryDictIndexLookup, range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryDictIndexLookup, range); diagnostic.set_fix(Fix::safe_edits( Edit::range_replacement(value_name.id.to_string(), range), [noop(index_name), noop(value_name)], )); - checker.report_diagnostic(diagnostic); } } @@ -104,12 +103,11 @@ pub(crate) fn unnecessary_dict_index_lookup_comprehension(checker: &Checker, exp }; for range in ranges { - let mut diagnostic = Diagnostic::new(UnnecessaryDictIndexLookup, range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryDictIndexLookup, range); diagnostic.set_fix(Fix::safe_edits( Edit::range_replacement(value_name.id.to_string(), range), [noop(index_name), noop(value_name)], )); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs index bf4cb4afc1..b932c5634a 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -38,6 +38,6 @@ impl Violation for UnnecessaryDirectLambdaCall { /// PLC3002 pub(crate) fn unnecessary_direct_lambda_call(checker: &Checker, expr: &Expr, func: &Expr) { if let Expr::Lambda(_) = func { - checker.report_diagnostic(Diagnostic::new(UnnecessaryDirectLambdaCall, expr.range())); + checker.report_diagnostic(UnnecessaryDirectLambdaCall, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dunder_call.rs b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dunder_call.rs index 8295e7d6af..6d4440a4ac 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dunder_call.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dunder_call.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, OperatorPrecedence, Stmt}; use ruff_python_semantic::SemanticModel; @@ -202,7 +202,7 @@ pub(crate) fn unnecessary_dunder_call(checker: &Checker, call: &ast::ExprCall) { } } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryDunderCall { method: attr.to_string(), replacement: title, @@ -237,8 +237,6 @@ pub(crate) fn unnecessary_dunder_call(checker: &Checker, call: &ast::ExprCall) { call.range(), ))); } - - checker.report_diagnostic(diagnostic); } /// Return `true` if this is a dunder method that is allowed to be called explicitly. diff --git a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_lambda.rs b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_lambda.rs index f677f7a80f..9ecfc0801e 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_lambda.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_lambda.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, ExprLambda, Parameter, ParameterWithDefault, visitor}; @@ -207,7 +207,7 @@ pub(crate) fn unnecessary_lambda(checker: &Checker, lambda: &ExprLambda) { } } - let mut diagnostic = Diagnostic::new(UnnecessaryLambda, lambda.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryLambda, lambda.range()); diagnostic.set_fix(Fix::applicable_edit( Edit::range_replacement( checker.locator().slice(func.as_ref()).to_string(), @@ -215,7 +215,6 @@ pub(crate) fn unnecessary_lambda(checker: &Checker, lambda: &ExprLambda) { ), Applicability::Unsafe, )); - checker.report_diagnostic(diagnostic); } /// Identify all `Expr::Name` nodes in an AST. diff --git a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_list_index_lookup.rs b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_list_index_lookup.rs index 493a648b2e..414a30e820 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unnecessary_list_index_lookup.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unnecessary_list_index_lookup.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, Int, Number, StmtFor}; @@ -61,12 +61,11 @@ pub(crate) fn unnecessary_list_index_lookup(checker: &Checker, stmt_for: &StmtFo }; for range in ranges { - let mut diagnostic = Diagnostic::new(UnnecessaryListIndexLookup, range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListIndexLookup, range); diagnostic.set_fix(Fix::safe_edits( Edit::range_replacement(value_name.id.to_string(), range), [noop(index_name), noop(value_name)], )); - checker.report_diagnostic(diagnostic); } } @@ -105,12 +104,11 @@ pub(crate) fn unnecessary_list_index_lookup_comprehension(checker: &Checker, exp }; for range in ranges { - let mut diagnostic = Diagnostic::new(UnnecessaryListIndexLookup, range); + let mut diagnostic = checker.report_diagnostic(UnnecessaryListIndexLookup, range); diagnostic.set_fix(Fix::safe_edits( Edit::range_replacement(value_name.id.to_string(), range), [noop(index_name), noop(value_name)], )); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/unreachable.rs b/crates/ruff_linter/src/rules/pylint/rules/unreachable.rs index a93fec919d..b81c43d8c0 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unreachable.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unreachable.rs @@ -5,7 +5,7 @@ use ruff_python_ast::{Identifier, Stmt}; use ruff_python_semantic::cfg::graph::{BlockId, Condition, ControlFlowGraph, build_cfg}; use ruff_text_size::TextRange; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -64,12 +64,12 @@ pub(crate) fn in_function(checker: &Checker, name: &Identifier, body: &[Stmt]) { let start = cfg.range(start_block).start(); let end = cfg.range(end_block).end(); - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnreachableCode { name: name.to_string(), }, TextRange::new(start, end), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/unspecified_encoding.rs b/crates/ruff_linter/src/rules/pylint/rules/unspecified_encoding.rs index 5a114bed48..fea61bc453 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/unspecified_encoding.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/unspecified_encoding.rs @@ -1,6 +1,6 @@ use std::fmt::{Display, Formatter}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Expr}; @@ -91,7 +91,7 @@ pub(crate) fn unspecified_encoding(checker: &Checker, call: &ast::ExprCall) { return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnspecifiedEncoding { function_name, mode, @@ -99,7 +99,6 @@ pub(crate) fn unspecified_encoding(checker: &Checker, call: &ast::ExprCall) { call.func.range(), ); diagnostic.set_fix(generate_keyword_fix(checker, call)); - checker.report_diagnostic(diagnostic); } /// Represents the path of the function or method being called. diff --git a/crates/ruff_linter/src/rules/pylint/rules/useless_else_on_loop.rs b/crates/ruff_linter/src/rules/pylint/rules/useless_else_on_loop.rs index c2df2dfc61..573b3688e6 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/useless_else_on_loop.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/useless_else_on_loop.rs @@ -1,7 +1,7 @@ use anyhow::Result; use ast::whitespace::indentation; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier; use ruff_python_ast::{self as ast, ExceptHandler, MatchCase, Stmt}; @@ -70,7 +70,7 @@ pub(crate) fn useless_else_on_loop(checker: &Checker, stmt: &Stmt, body: &[Stmt] let else_range = identifier::else_(stmt, checker.locator().contents()).expect("else clause"); - let mut diagnostic = Diagnostic::new(UselessElseOnLoop, else_range); + let mut diagnostic = checker.report_diagnostic(UselessElseOnLoop, else_range); diagnostic.try_set_fix(|| { remove_else( stmt, @@ -81,7 +81,6 @@ pub(crate) fn useless_else_on_loop(checker: &Checker, stmt: &Stmt, body: &[Stmt] checker.stylist(), ) }); - checker.report_diagnostic(diagnostic); } /// Returns `true` if the given body contains a `break` statement. diff --git a/crates/ruff_linter/src/rules/pylint/rules/useless_exception_statement.rs b/crates/ruff_linter/src/rules/pylint/rules/useless_exception_statement.rs index 389628325f..e1b27dd4da 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/useless_exception_statement.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/useless_exception_statement.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; @@ -56,12 +56,11 @@ pub(crate) fn useless_exception_statement(checker: &Checker, expr: &ast::StmtExp }; if is_builtin_exception(func, checker.semantic(), checker.target_version()) { - let mut diagnostic = Diagnostic::new(UselessExceptionStatement, expr.range()); + let mut diagnostic = checker.report_diagnostic(UselessExceptionStatement, expr.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( "raise ".to_string(), expr.start(), ))); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/useless_import_alias.rs b/crates/ruff_linter/src/rules/pylint/rules/useless_import_alias.rs index 683682ba4b..b2ea23054c 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/useless_import_alias.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/useless_import_alias.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Alias; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -73,7 +73,7 @@ pub(crate) fn useless_import_alias(checker: &Checker, alias: &Alias) { .settings .isort .requires_module_import(alias.name.to_string(), Some(asname.to_string())); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UselessImportAlias { required_import_conflict, }, @@ -85,8 +85,6 @@ pub(crate) fn useless_import_alias(checker: &Checker, alias: &Alias) { alias.range(), ))); } - - checker.report_diagnostic(diagnostic); } /// PLC0414 @@ -110,7 +108,7 @@ pub(crate) fn useless_import_from_alias( Some(asname.to_string()), level, ); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UselessImportAlias { required_import_conflict, }, @@ -123,6 +121,4 @@ pub(crate) fn useless_import_from_alias( alias.range(), ))); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/useless_return.rs b/crates/ruff_linter/src/rules/pylint/rules/useless_return.rs index da0479e7de..5bec98ebf4 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/useless_return.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/useless_return.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::visitor::Visitor; @@ -94,10 +94,9 @@ pub(crate) fn useless_return( return; } - let mut diagnostic = Diagnostic::new(UselessReturn, last_stmt.range()); + let mut diagnostic = checker.report_diagnostic(UselessReturn, last_stmt.range()); let edit = fix::edits::delete_stmt(last_stmt, Some(stmt), checker.locator(), checker.indexer()); diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_id(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pylint/rules/useless_with_lock.rs b/crates/ruff_linter/src/rules/pylint/rules/useless_with_lock.rs index 98db5eb04a..fcd4d8126e 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/useless_with_lock.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/useless_with_lock.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; @@ -80,6 +80,6 @@ pub(crate) fn useless_with_lock(checker: &Checker, with: &ast::StmtWith) { return; } - checker.report_diagnostic(Diagnostic::new(UselessWithLock, call.range())); + checker.report_diagnostic(UselessWithLock, call.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/yield_from_in_async_function.rs b/crates/ruff_linter/src/rules/pylint/rules/yield_from_in_async_function.rs index ab76bb65ec..fa71e3796d 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/yield_from_in_async_function.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/yield_from_in_async_function.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::ScopeKind; @@ -43,6 +43,6 @@ pub(crate) fn yield_from_in_async_function(checker: &Checker, expr: &ast::ExprYi checker.semantic().current_scope().kind, ScopeKind::Function(ast::StmtFunctionDef { is_async: true, .. }) ) { - checker.report_diagnostic(Diagnostic::new(YieldFromInAsyncFunction, expr.range())); + checker.report_diagnostic(YieldFromInAsyncFunction, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/pylint/rules/yield_in_init.rs b/crates/ruff_linter/src/rules/pylint/rules/yield_in_init.rs index a6979c769c..f303324704 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/yield_in_init.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/yield_in_init.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -41,6 +41,6 @@ impl Violation for YieldInInit { /// PLE0100 pub(crate) fn yield_in_init(checker: &Checker, expr: &Expr) { if in_dunder_method("__init__", checker.semantic(), checker.settings) { - checker.report_diagnostic(Diagnostic::new(YieldInInit, expr.range())); + checker.report_diagnostic(YieldInInit, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs index 806caa561f..90e526a3b7 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs @@ -1,6 +1,6 @@ use log::debug; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_dunder; use ruff_python_ast::name::Name; @@ -113,7 +113,7 @@ pub(crate) fn convert_named_tuple_functional_to_class( } }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ConvertNamedTupleFunctionalToClass { name: typename.to_string(), }, @@ -130,7 +130,6 @@ pub(crate) fn convert_named_tuple_functional_to_class( checker.comment_ranges(), )); } - checker.report_diagnostic(diagnostic); } /// Return the typename, args, keywords, and base class. diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs index 5341d4d67c..73ca1f3a4d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Identifier, Keyword, Stmt}; use ruff_python_codegen::Generator; @@ -97,7 +97,7 @@ pub(crate) fn convert_typed_dict_functional_to_class( return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ConvertTypedDictFunctionalToClass { name: class_name.to_string(), }, @@ -115,7 +115,6 @@ pub(crate) fn convert_typed_dict_functional_to_class( checker.comment_ranges(), )); } - checker.report_diagnostic(diagnostic); } /// Return the class name, arguments, keywords and base class for a `TypedDict` diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/datetime_utc_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/datetime_utc_alias.rs index 18706eb0fe..daf1129dc8 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/datetime_utc_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/datetime_utc_alias.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -58,7 +58,7 @@ pub(crate) fn datetime_utc_alias(checker: &Checker, expr: &Expr) { matches!(qualified_name.segments(), ["datetime", "timezone", "utc"]) }) { - let mut diagnostic = Diagnostic::new(DatetimeTimezoneUTC, expr.range()); + let mut diagnostic = checker.report_diagnostic(DatetimeTimezoneUTC, expr.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import_from("datetime", "UTC"), @@ -68,6 +68,5 @@ pub(crate) fn datetime_utc_alias(checker: &Checker, expr: &Expr) { let reference_edit = Edit::range_replacement(binding, expr.range()); Ok(Fix::safe_edits(import_edit, [reference_edit])) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs index 8d20eb816b..4dcba36f82 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Stmt}; use ruff_text_size::Ranged; @@ -42,13 +42,12 @@ fn add_check_for_node(checker: &Checker, node: &T) where T: Ranged, { - let mut diagnostic = Diagnostic::new(DeprecatedCElementTree, node.range()); + let mut diagnostic = checker.report_diagnostic(DeprecatedCElementTree, node.range()); let contents = checker.locator().slice(node); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( contents.replacen("cElementTree", "ElementTree", 1), node.range(), ))); - checker.report_diagnostic(diagnostic); } /// UP023 diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_import.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_import.rs index 4f3f007529..2c49b252cf 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_import.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_import.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::whitespace::indentation; use ruff_python_ast::{Alias, StmtImportFrom}; @@ -726,7 +726,7 @@ pub(crate) fn deprecated_import(checker: &Checker, import_from_stmt: &StmtImport ); for (operation, fix) in fixer.without_renames() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DeprecatedImport { deprecation: Deprecation::WithoutRename(operation), }, @@ -738,16 +738,14 @@ pub(crate) fn deprecated_import(checker: &Checker, import_from_stmt: &StmtImport import_from_stmt.range(), ))); } - checker.report_diagnostic(diagnostic); } for operation in fixer.with_renames() { - let diagnostic = Diagnostic::new( + checker.report_diagnostic( DeprecatedImport { deprecation: Deprecation::WithRename(operation), }, import_from_stmt.range(), ); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_mock_import.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_mock_import.rs index 0a2a81b80a..612b10da54 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_mock_import.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_mock_import.rs @@ -5,7 +5,7 @@ use libcst_native::{ }; use log::debug; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::whitespace::indentation; @@ -258,7 +258,7 @@ pub(crate) fn deprecated_mock_attribute(checker: &Checker, attribute: &ast::Expr if UnqualifiedName::from_expr(&attribute.value) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["mock", "mock"])) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DeprecatedMockImport { reference_type: MockReference::Attribute, }, @@ -268,7 +268,6 @@ pub(crate) fn deprecated_mock_attribute(checker: &Checker, attribute: &ast::Expr "mock".to_string(), attribute.value.range(), ))); - checker.report_diagnostic(diagnostic); } } @@ -297,7 +296,7 @@ pub(crate) fn deprecated_mock_import(checker: &Checker, stmt: &Stmt) { // Add a `Diagnostic` for each `mock` import. for name in names { if &name.name == "mock" || &name.name == "mock.mock" { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DeprecatedMockImport { reference_type: MockReference::Import, }, @@ -309,7 +308,6 @@ pub(crate) fn deprecated_mock_import(checker: &Checker, stmt: &Stmt) { stmt.range(), ))); } - checker.report_diagnostic(diagnostic); } } } @@ -324,7 +322,7 @@ pub(crate) fn deprecated_mock_import(checker: &Checker, stmt: &Stmt) { } if module == "mock" { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DeprecatedMockImport { reference_type: MockReference::Import, }, @@ -337,7 +335,6 @@ pub(crate) fn deprecated_mock_import(checker: &Checker, stmt: &Stmt) { .map(Fix::safe_edit) }); } - checker.report_diagnostic(diagnostic); } } _ => (), diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs index 294f155c19..0087100134 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs @@ -2,7 +2,7 @@ use ruff_python_ast::{self as ast, Expr}; use rustc_hash::FxHashMap; use std::sync::LazyLock; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -91,7 +91,7 @@ pub(crate) fn deprecated_unittest_alias(checker: &Checker, expr: &Expr) { if id != "self" { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DeprecatedUnittestAlias { alias: attr.to_string(), target: (*target).to_string(), @@ -102,5 +102,4 @@ pub(crate) fn deprecated_unittest_alias(checker: &Checker, expr: &Expr) { format!("self.{target}"), expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs index 413672ce57..e5025566c9 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/f_strings.rs @@ -3,7 +3,7 @@ use std::borrow::Cow; use anyhow::{Context, Result}; use rustc_hash::{FxHashMap, FxHashSet}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; use ruff_python_ast::str::{leading_quote, trailing_quote}; @@ -504,7 +504,7 @@ pub(crate) fn f_strings(checker: &Checker, call: &ast::ExprCall, summary: &Forma return; } - let mut diagnostic = Diagnostic::new(FString, call.range()); + let mut diagnostic = checker.report_diagnostic(FString, call.range()); // Avoid fix if there are comments within the call: // ``` @@ -528,5 +528,4 @@ pub(crate) fn f_strings(checker: &Checker, call: &ast::ExprCall, summary: &Forma ))); } } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/format_literals.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/format_literals.rs index ed9536786e..6a3f66ab0d 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/format_literals.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/format_literals.rs @@ -4,7 +4,7 @@ use anyhow::{Result, anyhow}; use libcst_native::{Arg, Expression}; use regex::Regex; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_codegen::Stylist; @@ -112,12 +112,11 @@ pub(crate) fn format_literals(checker: &Checker, call: &ast::ExprCall, summary: Arguments::Reorder(&summary.indices) }; - let mut diagnostic = Diagnostic::new(FormatLiterals, call.range()); + let mut diagnostic = checker.report_diagnostic(FormatLiterals, call.range()); diagnostic.try_set_fix(|| { generate_call(call, arguments, checker.locator(), checker.stylist()) .map(|suggestion| Fix::unsafe_edit(Edit::range_replacement(suggestion, call.range()))) }); - checker.report_diagnostic(diagnostic); } /// Returns true if the indices are sequential. diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs index 42531ff4c5..b3f176e8eb 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, Keyword}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -87,7 +87,7 @@ pub(crate) fn lru_cache_with_maxsize_none(checker: &Checker, decorator_list: &[D range: _, } = &keywords[0]; if arg.as_ref().is_some_and(|arg| arg == "maxsize") && value.is_none_literal_expr() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( LRUCacheWithMaxsizeNone, TextRange::new(func.end(), decorator.end()), ); @@ -101,7 +101,6 @@ pub(crate) fn lru_cache_with_maxsize_none(checker: &Checker, decorator_list: &[D Edit::range_replacement(binding, decorator.expression.range()); Ok(Fix::safe_edits(import_edit, [reference_edit])) }); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs index 6fe2319a3c..70c5da0e94 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Decorator, Expr}; use ruff_text_size::{Ranged, TextRange}; @@ -74,12 +74,11 @@ pub(crate) fn lru_cache_without_parameters(checker: &Checker, decorator_list: &[ matches!(qualified_name.segments(), ["functools", "lru_cache"]) }) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( LRUCacheWithoutParameters, TextRange::new(func.end(), decorator.end()), ); diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(arguments.range()))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/native_literals.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/native_literals.rs index fbca70791f..00a69daf46 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/native_literals.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/native_literals.rs @@ -1,7 +1,7 @@ use std::fmt; use std::str::FromStr; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Int, LiteralExpressionRef, OperatorPrecedence, UnaryOp}; use ruff_source_file::find_newline; @@ -193,21 +193,21 @@ pub(crate) fn native_literals( match args.first() { None => { - let mut diagnostic = Diagnostic::new(NativeLiterals { literal_type }, call.range()); - // Do not suggest fix for attribute access on an int like `int().attribute` // Ex) `int().denominator` is valid but `0.denominator` is not if literal_type == LiteralType::Int && matches!(parent_expr, Some(Expr::Attribute(_))) { return; } + let mut diagnostic = + checker.report_diagnostic(NativeLiterals { literal_type }, call.range()); + let expr = literal_type.as_zero_value_expr(checker); let content = checker.generator().expr(&expr); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( content, call.range(), ))); - checker.report_diagnostic(diagnostic); } Some(arg) => { let (has_unary_op, literal_expr) = if let Some(literal_expr) = arg.as_literal_expr() { @@ -291,8 +291,9 @@ pub(crate) fn native_literals( let edit = Edit::range_replacement(content, call.range()); let fix = Fix::applicable_edit(edit, applicability); - let diagnostic = Diagnostic::new(NativeLiterals { literal_type }, call.range()); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(NativeLiterals { literal_type }, call.range()) + .set_fix(fix); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/non_pep646_unpack.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/non_pep646_unpack.rs index de022c51cc..f913170a1b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/non_pep646_unpack.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/non_pep646_unpack.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprSubscript, PythonVersion}; use ruff_python_semantic::SemanticModel; @@ -88,12 +88,11 @@ pub(crate) fn use_pep646_unpack(checker: &Checker, expr: &ExprSubscript) { return; } - let mut diagnostic = Diagnostic::new(NonPEP646Unpack, *range); + let mut diagnostic = checker.report_diagnostic(NonPEP646Unpack, *range); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("*{}", checker.locator().slice(slice.as_ref())), *range, ))); - checker.report_diagnostic(diagnostic); } /// Determine whether the [`ExprSubscript`] is in a subscript index (e.g., `Generic[Unpack[int]]`). diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/open_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/open_alias.rs index f67a777d24..45f997c04e 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/open_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/open_alias.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -52,7 +52,7 @@ pub(crate) fn open_alias(checker: &Checker, expr: &Expr, func: &Expr) { .resolve_qualified_name(func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["io", "open"])) { - let mut diagnostic = Diagnostic::new(OpenAlias, expr.range()); + let mut diagnostic = checker.report_diagnostic(OpenAlias, expr.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol( "open", @@ -64,6 +64,5 @@ pub(crate) fn open_alias(checker: &Checker, expr: &Expr, func: &Expr) { import_edit, )) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/os_error_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/os_error_alias.rs index bd86250758..070a13f470 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/os_error_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/os_error_alias.rs @@ -2,7 +2,7 @@ use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext}; use ruff_text_size::{Ranged, TextRange}; use crate::fix::edits::pad; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::{Name, UnqualifiedName}; use ruff_python_semantic::SemanticModel; @@ -71,7 +71,7 @@ fn is_alias(expr: &Expr, semantic: &SemanticModel) -> bool { /// Create a [`Diagnostic`] for a single target, like an [`Expr::Name`]. fn atom_diagnostic(checker: &Checker, target: &Expr) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( OSErrorAlias { name: UnqualifiedName::from_expr(target).map(|name| name.to_string()), }, @@ -88,12 +88,11 @@ fn atom_diagnostic(checker: &Checker, target: &Expr) { import_edit, )) }); - checker.report_diagnostic(diagnostic); } /// Create a [`Diagnostic`] for a tuple of expressions. fn tuple_diagnostic(checker: &Checker, tuple: &ast::ExprTuple, aliases: &[&Expr]) { - let mut diagnostic = Diagnostic::new(OSErrorAlias { name: None }, tuple.range()); + let mut diagnostic = checker.report_diagnostic(OSErrorAlias { name: None }, tuple.range()); let semantic = checker.semantic(); if semantic.has_builtin_binding("OSError") { // Filter out any `OSErrors` aliases. @@ -138,7 +137,6 @@ fn tuple_diagnostic(checker: &Checker, tuple: &ast::ExprTuple, aliases: &[&Expr] tuple.range(), ))); } - checker.report_diagnostic(diagnostic); } /// UP024 diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/outdated_version_block.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/outdated_version_block.rs index 51af61887f..f89bc74bf0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/outdated_version_block.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/outdated_version_block.rs @@ -2,7 +2,7 @@ use std::cmp::Ordering; use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::stmt_if::{BranchKind, IfElifBranch, if_elif_branches}; @@ -129,7 +129,7 @@ pub(crate) fn outdated_version_block(checker: &Checker, stmt_if: &StmtIf) { ) { Ok(false) => {} Ok(true) => { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( OutdatedVersionBlock { reason: if op.is_lt() || op.is_lt_e() { Reason::AlwaysFalse @@ -146,15 +146,14 @@ pub(crate) fn outdated_version_block(checker: &Checker, stmt_if: &StmtIf) { } { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } Err(_) => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( OutdatedVersionBlock { reason: Reason::Invalid, }, comparison.range(), - )); + ); } } } @@ -182,28 +181,30 @@ pub(crate) fn outdated_version_block(checker: &Checker, stmt_if: &StmtIf) { }; match reason { Reason::AlwaysTrue => { - let mut diagnostic = - Diagnostic::new(OutdatedVersionBlock { reason }, branch.test.range()); + let mut diagnostic = checker.report_diagnostic( + OutdatedVersionBlock { reason }, + branch.test.range(), + ); if let Some(fix) = fix_always_true_branch(checker, stmt_if, &branch) { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } Reason::AlwaysFalse => { - let mut diagnostic = - Diagnostic::new(OutdatedVersionBlock { reason }, branch.test.range()); + let mut diagnostic = checker.report_diagnostic( + OutdatedVersionBlock { reason }, + branch.test.range(), + ); if let Some(fix) = fix_always_false_branch(checker, stmt_if, &branch) { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } Reason::Invalid => { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( OutdatedVersionBlock { reason: Reason::Invalid, }, comparison.range(), - )); + ); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_class.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_class.rs index ae8b83e698..81b7b49719 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_class.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_class.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{ExprSubscript, StmtClassDef}; @@ -138,7 +138,7 @@ pub(crate) fn non_pep695_generic_class(checker: &Checker, class_def: &StmtClassD return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NonPEP695GenericClass { name: name.to_string(), }, @@ -154,7 +154,6 @@ pub(crate) fn non_pep695_generic_class(checker: &Checker, class_def: &StmtClassD // because `find_generic` also finds the *first* Generic argument, this has the additional // benefit of bailing out with a diagnostic if multiple Generic arguments are present if generic_idx != arguments.len() - 1 { - checker.report_diagnostic(diagnostic); return; } @@ -187,6 +186,7 @@ pub(crate) fn non_pep695_generic_class(checker: &Checker, class_def: &StmtClassD // just because we can't confirm that `SomethingElse` is a `TypeVar` if !visitor.any_skipped { let Some(type_vars) = check_type_vars(visitor.vars) else { + diagnostic.defuse(); return; }; @@ -209,6 +209,4 @@ pub(crate) fn non_pep695_generic_class(checker: &Checker, class_def: &StmtClassD )) }); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_function.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_function.rs index e75cea226d..39fa3eafff 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_function.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_generic_function.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StmtFunctionDef; use ruff_python_ast::visitor::Visitor; @@ -163,16 +163,15 @@ pub(crate) fn non_pep695_generic_function(checker: &Checker, function_def: &Stmt source: checker.source(), }; - checker.report_diagnostic( - Diagnostic::new( + checker + .report_diagnostic( NonPEP695GenericFunction { name: name.to_string(), }, TextRange::new(name.start(), parameters.end()), ) - .with_fix(Fix::unsafe_edit(Edit::insertion( + .set_fix(Fix::unsafe_edit(Edit::insertion( type_params.to_string(), name.end(), - ))), - ); + ))); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_type_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_type_alias.rs index 9ebe7c326c..ab3dce82ac 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_type_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/non_pep695_type_alias.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::parenthesize::parenthesized_range; @@ -172,14 +172,14 @@ pub(crate) fn non_pep695_type_alias_type(checker: &Checker, stmt: &StmtAssign) { return; }; - checker.report_diagnostic(create_diagnostic( + create_diagnostic( checker, stmt.into(), &target_name.id, value, &vars, TypeAliasKind::TypeAliasType, - )); + ); } /// UP040 @@ -231,14 +231,14 @@ pub(crate) fn non_pep695_type_alias(checker: &Checker, stmt: &StmtAnnAssign) { return; } - checker.report_diagnostic(create_diagnostic( + create_diagnostic( checker, stmt.into(), name, value, &vars, TypeAliasKind::TypeAlias, - )); + ); } /// Generate a [`Diagnostic`] for a non-PEP 695 type alias or type alias type. @@ -249,7 +249,7 @@ fn create_diagnostic( value: &Expr, type_vars: &[TypeVar], type_alias_kind: TypeAliasKind, -) -> Diagnostic { +) { let source = checker.source(); let comment_ranges = checker.comment_ranges(); @@ -287,12 +287,13 @@ fn create_diagnostic( } }; - Diagnostic::new( - NonPEP695TypeAlias { - name: name.to_string(), - type_alias_kind, - }, - stmt.range(), - ) - .with_fix(Fix::applicable_edit(edit, applicability)) + checker + .report_diagnostic( + NonPEP695TypeAlias { + name: name.to_string(), + type_alias_kind, + }, + stmt.range(), + ) + .set_fix(Fix::applicable_edit(edit, applicability)); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/private_type_parameter.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/private_type_parameter.rs index 0a5635c68d..cc1ed4460b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/private_type_parameter.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/pep695/private_type_parameter.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_python_semantic::Binding; @@ -101,43 +101,45 @@ impl Violation for PrivateTypeParameter { } /// UP049 -pub(crate) fn private_type_parameter(checker: &Checker, binding: &Binding) -> Option { +pub(crate) fn private_type_parameter(checker: &Checker, binding: &Binding) { let semantic = checker.semantic(); - let stmt = binding.statement(semantic)?; + let Some(stmt) = binding.statement(semantic) else { + return; + }; if !binding.kind.is_type_param() { - return None; + return; } let kind = match stmt { Stmt::FunctionDef(_) => ParamKind::Function, Stmt::ClassDef(_) => ParamKind::Class, - _ => return None, + _ => return, }; let old_name = binding.name(checker.source()); if !old_name.starts_with('_') { - return None; + return; } // Sunder `_T_`, dunder `__T__`, and all all-under `_` or `__` cases should all be skipped, as // these are not "private" names if old_name.ends_with('_') { - return None; + return; } - let mut diagnostic = Diagnostic::new(PrivateTypeParameter { kind }, binding.range); + let mut diagnostic = checker.report_diagnostic(PrivateTypeParameter { kind }, binding.range); let new_name = old_name.trim_start_matches('_'); // if the new name would shadow another variable, keyword, or builtin, emit a diagnostic without // a suggested fix if ShadowedKind::new(binding, new_name, checker).shadows_any() { - return Some(diagnostic); + return; } if !is_identifier(new_name) { - return Some(diagnostic); + return; } let source = checker.source(); @@ -163,6 +165,4 @@ pub(crate) fn private_type_parameter(checker: &Checker, binding: &Binding) -> Op let fix_isolation = Checker::isolation(binding.source); Ok(Fix::applicable_edits(first, rest, applicability).isolate(fix_isolation)) }); - - Some(diagnostic) } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/printf_string_formatting.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/printf_string_formatting.rs index 6f4d3a91b6..60478d7c07 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/printf_string_formatting.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/printf_string_formatting.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::fmt::Write; use std::str::FromStr; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, AnyStringFlags, Expr, StringFlags, whitespace::indentation}; use ruff_python_codegen::Stylist; @@ -385,7 +385,7 @@ pub(crate) fn printf_string_formatting( return; }; if !convertible(&format_string, right) { - checker.report_diagnostic(Diagnostic::new(PrintfStringFormatting, string_expr.range())); + checker.report_diagnostic(PrintfStringFormatting, string_expr.range()); return; } @@ -446,10 +446,7 @@ pub(crate) fn printf_string_formatting( let Some(params_string) = clean_params_dictionary(right, checker.locator(), checker.stylist()) else { - checker.report_diagnostic(Diagnostic::new( - PrintfStringFormatting, - string_expr.range(), - )); + checker.report_diagnostic(PrintfStringFormatting, string_expr.range()); return; }; Cow::Owned(params_string) @@ -504,12 +501,11 @@ pub(crate) fn printf_string_formatting( // Add the `.format` call. let _ = write!(&mut contents, ".format{params_string}"); - let mut diagnostic = Diagnostic::new(PrintfStringFormatting, bin_op.range()); + let mut diagnostic = checker.report_diagnostic(PrintfStringFormatting, bin_op.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( contents, bin_op.range(), ))); - checker.report_diagnostic(diagnostic); } #[cfg(test)] diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/quoted_annotation.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/quoted_annotation.rs index c5dcd45264..73f4976aaf 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/quoted_annotation.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/quoted_annotation.rs @@ -2,7 +2,7 @@ use ruff_python_parser::TokenKind; use ruff_text_size::{TextLen, TextRange, TextSize}; use crate::checkers::ast::Checker; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_python_semantic::SemanticModel; @@ -85,8 +85,6 @@ impl AlwaysFixableViolation for QuotedAnnotation { /// UP037 pub(crate) fn quoted_annotation(checker: &Checker, annotation: &str, range: TextRange) { - let diagnostic = Diagnostic::new(QuotedAnnotation, range); - let placeholder_range = TextRange::up_to(annotation.text_len()); let spans_multiple_lines = annotation.contains_line_break(placeholder_range); @@ -108,7 +106,9 @@ pub(crate) fn quoted_annotation(checker: &Checker, annotation: &str, range: Text let edit = Edit::range_replacement(new_content, range); let fix = Fix::safe_edit(edit); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(QuotedAnnotation, range) + .set_fix(fix); } fn in_parameter_annotation(offset: TextSize, semantic: &SemanticModel) -> bool { diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/redundant_open_modes.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/redundant_open_modes.rs index cdefd53e24..d7a6bd4126 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/redundant_open_modes.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/redundant_open_modes.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_parser::{TokenKind, Tokens}; @@ -81,17 +81,12 @@ pub(crate) fn redundant_open_modes(checker: &Checker, call: &ast::ExprCall) { }; let reduced = mode.reduce(); if reduced != mode { - checker.report_diagnostic(create_diagnostic(call, mode_arg, reduced, checker)); + create_diagnostic(call, mode_arg, reduced, checker); } } -fn create_diagnostic( - call: &ast::ExprCall, - mode_arg: &Expr, - mode: OpenMode, - checker: &Checker, -) -> Diagnostic { - let mut diagnostic = Diagnostic::new( +fn create_diagnostic(call: &ast::ExprCall, mode_arg: &Expr, mode: OpenMode, checker: &Checker) { + let mut diagnostic = checker.report_diagnostic( RedundantOpenModes { replacement: mode.to_string(), }, @@ -109,8 +104,6 @@ fn create_diagnostic( mode_arg.range(), ))); } - - diagnostic } fn create_remove_argument_fix( diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/replace_stdout_stderr.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/replace_stdout_stderr.rs index fea862a3b9..45b05fc872 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/replace_stdout_stderr.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/replace_stdout_stderr.rs @@ -1,6 +1,6 @@ use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Keyword}; use ruff_python_semantic::Modules; @@ -94,12 +94,11 @@ pub(crate) fn replace_stdout_stderr(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(ReplaceStdoutStderr, call.range()); + let mut diagnostic = checker.report_diagnostic(ReplaceStdoutStderr, call.range()); if call.arguments.find_keyword("capture_output").is_none() { diagnostic .try_set_fix(|| generate_fix(stdout, stderr, call, checker.locator().contents())); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/replace_str_enum.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/replace_str_enum.rs index bb48ba16c7..ced03bbce0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/replace_str_enum.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/replace_str_enum.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; @@ -126,7 +126,7 @@ pub(crate) fn replace_str_enum(checker: &Checker, class_def: &ast::StmtClassDef) return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ReplaceStrEnum { name: class_def.name.to_string(), }, @@ -153,6 +153,4 @@ pub(crate) fn replace_str_enum(checker: &Checker, class_def: &ast::StmtClassDef) )) }); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/replace_universal_newlines.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/replace_universal_newlines.rs index ab1a8b8281..132a562d07 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/replace_universal_newlines.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/replace_universal_newlines.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; @@ -67,7 +67,7 @@ pub(crate) fn replace_universal_newlines(checker: &Checker, call: &ast::ExprCall return; }; - let mut diagnostic = Diagnostic::new(ReplaceUniversalNewlines, arg.range()); + let mut diagnostic = checker.report_diagnostic(ReplaceUniversalNewlines, arg.range()); if call.arguments.find_keyword("text").is_some() { diagnostic.try_set_fix(|| { @@ -85,6 +85,5 @@ pub(crate) fn replace_universal_newlines(checker: &Checker, call: &ast::ExprCall arg.range(), ))); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/super_call_with_parameters.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/super_call_with_parameters.rs index a1794219ed..f87b7f5295 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/super_call_with_parameters.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/super_call_with_parameters.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::{Ranged, TextSize}; @@ -157,12 +157,11 @@ pub(crate) fn super_call_with_parameters(checker: &Checker, call: &ast::ExprCall return; } - let mut diagnostic = Diagnostic::new(SuperCallWithParameters, call.arguments.range()); + let mut diagnostic = checker.report_diagnostic(SuperCallWithParameters, call.arguments.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::deletion( call.arguments.start() + TextSize::new(1), call.arguments.end() - TextSize::new(1), ))); - checker.report_diagnostic(diagnostic); } /// Returns `true` if a call is an argumented `super` invocation. diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/timeout_error_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/timeout_error_alias.rs index e00eddf688..1b40bdd91f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/timeout_error_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/timeout_error_alias.rs @@ -2,7 +2,7 @@ use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext}; use ruff_text_size::{Ranged, TextRange}; use crate::fix::edits::pad; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::{Name, UnqualifiedName}; use ruff_python_semantic::SemanticModel; @@ -83,7 +83,7 @@ fn is_alias(expr: &Expr, semantic: &SemanticModel, target_version: PythonVersion /// Create a [`Diagnostic`] for a single target, like an [`Expr::Name`]. fn atom_diagnostic(checker: &Checker, target: &Expr) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( TimeoutErrorAlias { name: UnqualifiedName::from_expr(target).map(|name| name.to_string()), }, @@ -100,12 +100,11 @@ fn atom_diagnostic(checker: &Checker, target: &Expr) { import_edit, )) }); - checker.report_diagnostic(diagnostic); } /// Create a [`Diagnostic`] for a tuple of expressions. fn tuple_diagnostic(checker: &Checker, tuple: &ast::ExprTuple, aliases: &[&Expr]) { - let mut diagnostic = Diagnostic::new(TimeoutErrorAlias { name: None }, tuple.range()); + let mut diagnostic = checker.report_diagnostic(TimeoutErrorAlias { name: None }, tuple.range()); let semantic = checker.semantic(); if semantic.has_builtin_binding("TimeoutError") { // Filter out any `TimeoutErrors` aliases. @@ -150,7 +149,6 @@ fn tuple_diagnostic(checker: &Checker, tuple: &ast::ExprTuple, aliases: &[&Expr] tuple.range(), ))); } - checker.report_diagnostic(diagnostic); } /// UP041 diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/type_of_primitive.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/type_of_primitive.rs index 210afe3967..5792100271 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/type_of_primitive.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/type_of_primitive.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use crate::fix::edits::pad; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -65,7 +65,7 @@ pub(crate) fn type_of_primitive(checker: &Checker, expr: &Expr, func: &Expr, arg if !semantic.match_builtin_expr(func, "type") { return; } - let mut diagnostic = Diagnostic::new(TypeOfPrimitive { primitive }, expr.range()); + let mut diagnostic = checker.report_diagnostic(TypeOfPrimitive { primitive }, expr.range()); let builtin = primitive.builtin(); if semantic.has_builtin_binding(&builtin) { diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( @@ -73,5 +73,4 @@ pub(crate) fn type_of_primitive(checker: &Checker, expr: &Expr, func: &Expr, arg expr.range(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/typing_text_str_alias.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/typing_text_str_alias.rs index 37f8258bec..e932325884 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/typing_text_str_alias.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/typing_text_str_alias.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; @@ -56,7 +56,7 @@ pub(crate) fn typing_text_str_alias(checker: &Checker, expr: &Expr) { .resolve_qualified_name(expr) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["typing", "Text"])) { - let mut diagnostic = Diagnostic::new(TypingTextStrAlias, expr.range()); + let mut diagnostic = checker.report_diagnostic(TypingTextStrAlias, expr.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol( "str", @@ -68,6 +68,5 @@ pub(crate) fn typing_text_str_alias(checker: &Checker, expr: &Expr) { import_edit, )) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/unicode_kind_prefix.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/unicode_kind_prefix.rs index e3af44207b..4ed3768bac 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/unicode_kind_prefix.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/unicode_kind_prefix.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StringLiteral; use ruff_text_size::{Ranged, TextRange, TextSize}; @@ -41,11 +41,10 @@ impl AlwaysFixableViolation for UnicodeKindPrefix { /// UP025 pub(crate) fn unicode_kind_prefix(checker: &Checker, string: &StringLiteral) { if string.flags.prefix().is_unicode() { - let mut diagnostic = Diagnostic::new(UnicodeKindPrefix, string.range); + let mut diagnostic = checker.report_diagnostic(UnicodeKindPrefix, string.range); diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(TextRange::at( string.start(), TextSize::from(1), )))); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs index 7496586c70..c7bd001ac0 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use ruff_python_ast::{Alias, Stmt}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -110,7 +110,7 @@ pub(crate) fn unnecessary_builtin_import( return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryBuiltinImport { names: unused_imports .iter() @@ -138,5 +138,4 @@ pub(crate) fn unnecessary_builtin_import( checker.semantic().current_statement_parent_id(), ))) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_class_parentheses.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_class_parentheses.rs index 4896205762..e92bb79150 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_class_parentheses.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_class_parentheses.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; @@ -48,10 +48,9 @@ pub(crate) fn unnecessary_class_parentheses(checker: &Checker, class_def: &ast:: return; } - let mut diagnostic = Diagnostic::new(UnnecessaryClassParentheses, arguments.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryClassParentheses, arguments.range()); diagnostic.set_fix(Fix::safe_edit(Edit::deletion( arguments.start(), arguments.end(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_default_type_args.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_default_type_args.rs index 9e0eafe801..a5beeae74b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_default_type_args.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_default_type_args.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::{Ranged, TextRange}; @@ -102,7 +102,7 @@ pub(crate) fn unnecessary_default_type_args(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryDefaultTypeArgs, expr.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryDefaultTypeArgs, expr.range()); let applicability = if checker .comment_ranges() @@ -136,7 +136,6 @@ pub(crate) fn unnecessary_default_type_args(checker: &Checker, expr: &Expr) { ), applicability, )); - checker.report_diagnostic(diagnostic); } /// Trim trailing `None` literals from the given elements. diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs index 038ec25871..cd9f895381 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs @@ -1,6 +1,6 @@ use std::fmt::Write as _; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr, Keyword}; use ruff_python_parser::{TokenKind, Tokens}; @@ -161,7 +161,7 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { if let Some(encoding_arg) = match_encoding_arg(&call.arguments) { if literal.to_str().is_ascii() { // Ex) Convert `"foo".encode()` to `b"foo"`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEncodeUTF8 { reason: Reason::BytesLiteral, }, @@ -172,11 +172,10 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { call, checker.tokens(), )); - checker.report_diagnostic(diagnostic); } else if let EncodingArg::Keyword(kwarg) = encoding_arg { // Ex) Convert `"unicode text©".encode(encoding="utf-8")` to // `"unicode text©".encode()`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEncodeUTF8 { reason: Reason::DefaultArgument, }, @@ -191,10 +190,9 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } else if let EncodingArg::Positional(arg) = encoding_arg { // Ex) Convert `"unicode text©".encode("utf-8")` to `"unicode text©".encode()`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEncodeUTF8 { reason: Reason::DefaultArgument, }, @@ -209,7 +207,6 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } } } @@ -219,7 +216,7 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { if let EncodingArg::Keyword(kwarg) = encoding_arg { // Ex) Convert `f"unicode text©".encode(encoding="utf-8")` to // `f"unicode text©".encode()`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEncodeUTF8 { reason: Reason::DefaultArgument, }, @@ -234,10 +231,9 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } else if let EncodingArg::Positional(arg) = encoding_arg { // Ex) Convert `f"unicode text©".encode("utf-8")` to `f"unicode text©".encode()`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEncodeUTF8 { reason: Reason::DefaultArgument, }, @@ -252,7 +248,6 @@ pub(crate) fn unnecessary_encode_utf8(checker: &Checker, call: &ast::ExprCall) { ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_future_import.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_future_import.rs index 8a220f7b8c..205dea2593 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_future_import.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/unnecessary_future_import.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use ruff_python_ast::{Alias, Stmt}; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -98,7 +98,7 @@ pub(crate) fn unnecessary_future_import(checker: &Checker, stmt: &Stmt, names: & if unused_imports.is_empty() { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryFutureImport { names: unused_imports .iter() @@ -137,5 +137,4 @@ pub(crate) fn unnecessary_future_import(checker: &Checker, stmt: &Stmt, names: & )), ) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep585_annotation.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep585_annotation.rs index e2a0cea9f7..bdf78ab588 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep585_annotation.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep585_annotation.rs @@ -1,6 +1,6 @@ use ruff_python_ast::Expr; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::UnqualifiedName; use ruff_python_semantic::analyze::typing::ModuleMember; @@ -80,7 +80,7 @@ pub(crate) fn use_pep585_annotation(checker: &Checker, expr: &Expr, replacement: let Some(from) = UnqualifiedName::from_expr(expr) else { return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NonPEP585Annotation { from: from.to_string(), to: replacement.to_string(), @@ -132,5 +132,4 @@ pub(crate) fn use_pep585_annotation(checker: &Checker, expr: &Expr, replacement: } } } - checker.report_diagnostic(diagnostic); } 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 7f5071badb..c017a568df 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 @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::PythonVersion; use ruff_python_ast::helpers::{pep_604_optional, pep_604_union}; @@ -148,21 +148,15 @@ pub(crate) fn non_pep604_annotation( match operator { Pep604Operator::Optional => { - let (rule, mut diagnostic) = if is_defer_optional_to_up045_enabled(checker.settings) { - ( - Rule::NonPEP604AnnotationOptional, - Diagnostic::new(NonPEP604AnnotationOptional, expr.range()), - ) + let guard = if is_defer_optional_to_up045_enabled(checker.settings) { + checker.report_diagnostic_if_enabled(NonPEP604AnnotationOptional, expr.range()) } else { - ( - Rule::NonPEP604AnnotationUnion, - Diagnostic::new(NonPEP604AnnotationUnion, expr.range()), - ) + checker.report_diagnostic_if_enabled(NonPEP604AnnotationUnion, expr.range()) }; - if !checker.enabled(rule) { + let Some(mut diagnostic) = guard else { return; - } + }; if fixable { match slice { @@ -184,14 +178,13 @@ pub(crate) fn non_pep604_annotation( } } } - checker.report_diagnostic(diagnostic); } Pep604Operator::Union => { if !checker.enabled(Rule::NonPEP604AnnotationUnion) { return; } - let mut diagnostic = Diagnostic::new(NonPEP604AnnotationUnion, expr.range()); + let mut diagnostic = checker.report_diagnostic(NonPEP604AnnotationUnion, expr.range()); if fixable { match slice { Expr::Slice(_) => { @@ -226,7 +219,6 @@ pub(crate) fn non_pep604_annotation( } } } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_isinstance.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_isinstance.rs index 4060deccda..8e40da041b 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_isinstance.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_isinstance.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_ast::helpers::pep_604_union; @@ -109,12 +109,10 @@ pub(crate) fn use_pep604_isinstance(checker: &Checker, expr: &Expr, func: &Expr, let Some(kind) = CallKind::from_name(builtin_function_name) else { return; }; - checker.report_diagnostic( - Diagnostic::new(NonPEP604Isinstance { kind }, expr.range()).with_fix(Fix::unsafe_edit( - Edit::range_replacement( - checker.generator().expr(&pep_604_union(&tuple.elts)), - types.range(), - ), - )), - ); + checker + .report_diagnostic(NonPEP604Isinstance { kind }, expr.range()) + .set_fix(Fix::unsafe_edit(Edit::range_replacement( + checker.generator().expr(&pep_604_union(&tuple.elts)), + types.range(), + ))); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/useless_class_metaclass_type.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/useless_class_metaclass_type.rs index c4b26a2a84..0fe0fafd3f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/useless_class_metaclass_type.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/useless_class_metaclass_type.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::fix::edits::{Parentheses, remove_argument}; -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StmtClassDef; use ruff_text_size::Ranged; @@ -55,7 +55,7 @@ pub(crate) fn useless_class_metaclass_type(checker: &Checker, class_def: &StmtCl for keyword in &arguments.keywords { if let (Some("metaclass"), expr) = (keyword.arg.as_deref(), &keyword.value) { if checker.semantic().match_builtin_expr(expr, "type") { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UselessClassMetaclassType { name: class_def.name.to_string(), }, @@ -71,8 +71,6 @@ pub(crate) fn useless_class_metaclass_type(checker: &Checker, class_def: &StmtCl ) .map(Fix::safe_edit) }); - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/useless_metaclass_type.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/useless_metaclass_type.rs index eae3cd4389..608daee95f 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/useless_metaclass_type.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/useless_metaclass_type.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Stmt}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -62,12 +62,11 @@ pub(crate) fn useless_metaclass_type( return; } - let mut diagnostic = Diagnostic::new(UselessMetaclassType, stmt.range()); + let mut diagnostic = checker.report_diagnostic(UselessMetaclassType, stmt.range()); let stmt = checker.semantic().current_statement(); let parent = checker.semantic().current_statement_parent(); let edit = fix::edits::delete_stmt(stmt, parent, checker.locator(), checker.indexer()); diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_parent_id(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/useless_object_inheritance.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/useless_object_inheritance.rs index ecc0defe39..96454e2efe 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/useless_object_inheritance.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/useless_object_inheritance.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; @@ -55,7 +55,7 @@ pub(crate) fn useless_object_inheritance(checker: &Checker, class_def: &ast::Stm continue; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UselessObjectInheritance { name: class_def.name.to_string(), }, @@ -70,6 +70,5 @@ pub(crate) fn useless_object_inheritance(checker: &Checker, class_def: &ast::Stm ) .map(Fix::safe_edit) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/yield_in_for_loop.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/yield_in_for_loop.rs index 46c7ef8e2b..8d7a628d18 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/yield_in_for_loop.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/yield_in_for_loop.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{self as ast, Expr, Stmt}; @@ -126,7 +126,7 @@ pub(crate) fn yield_in_for_loop(checker: &Checker, stmt_for: &ast::StmtFor) { return; } - let mut diagnostic = Diagnostic::new(YieldInForLoop, stmt_for.range()); + let mut diagnostic = checker.report_diagnostic(YieldInForLoop, stmt_for.range()); let contents = checker.locator().slice( parenthesized_range( @@ -158,8 +158,6 @@ pub(crate) fn yield_in_for_loop(checker: &Checker, stmt_for: &ast::StmtFor) { stmt_for.range(), ))); } - - checker.report_diagnostic(diagnostic); } /// Return `true` if the two expressions are equivalent, and both consistent solely diff --git a/crates/ruff_linter/src/rules/refurb/rules/bit_count.rs b/crates/ruff_linter/src/rules/refurb/rules/bit_count.rs index 04a112ab89..affce99705 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/bit_count.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/bit_count.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::PythonVersion; use ruff_python_ast::{self as ast, Expr, ExprAttribute, ExprCall}; @@ -183,7 +183,7 @@ pub(crate) fn bit_count(checker: &Checker, call: &ExprCall) { format!("{literal_text}.bit_count()") }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( BitCount { existing: SourceCodeSnippet::from_str(literal_text), replacement: SourceCodeSnippet::new(replacement.to_string()), @@ -194,6 +194,4 @@ pub(crate) fn bit_count(checker: &Checker, call: &ExprCall) { Edit::range_replacement(replacement, call.range()), applicability, )); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/check_and_remove_from_set.rs b/crates/ruff_linter/src/rules/refurb/rules/check_and_remove_from_set.rs index bb2c1bb5b9..fc09185c0c 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/check_and_remove_from_set.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/check_and_remove_from_set.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::contains_effect; @@ -104,7 +104,7 @@ pub(crate) fn check_and_remove_from_set(checker: &Checker, if_stmt: &ast::StmtIf return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CheckAndRemoveFromSet { element: SourceCodeSnippet::from_str(checker.locator().slice(check_element)), set: check_set.id.to_string(), @@ -116,7 +116,6 @@ pub(crate) fn check_and_remove_from_set(checker: &Checker, if_stmt: &ast::StmtIf if_stmt.start(), if_stmt.end(), ))); - checker.report_diagnostic(diagnostic); } fn compare(lhs: &ComparableExpr, rhs: &ComparableExpr) -> bool { diff --git a/crates/ruff_linter/src/rules/refurb/rules/delete_full_slice.rs b/crates/ruff_linter/src/rules/refurb/rules/delete_full_slice.rs index fca68546a2..fd495659fd 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/delete_full_slice.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/delete_full_slice.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; @@ -66,7 +66,7 @@ pub(crate) fn delete_full_slice(checker: &Checker, delete: &ast::StmtDelete) { continue; }; - let mut diagnostic = Diagnostic::new(DeleteFullSlice, delete.range); + let mut diagnostic = checker.report_diagnostic(DeleteFullSlice, delete.range); // Fix is only supported for single-target deletions. if delete.targets.len() == 1 { @@ -77,8 +77,6 @@ pub(crate) fn delete_full_slice(checker: &Checker, delete: &ast::StmtDelete) { delete.end(), ))); } - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/for_loop_set_mutations.rs b/crates/ruff_linter/src/rules/refurb/rules/for_loop_set_mutations.rs index 2a32c4240e..54b313c782 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/for_loop_set_mutations.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/for_loop_set_mutations.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, Stmt, StmtFor}; use ruff_python_semantic::analyze::typing; @@ -128,13 +128,13 @@ pub(crate) fn for_loop_set_mutations(checker: &Checker, for_stmt: &StmtFor) { applicability, ); - let diagnostic = Diagnostic::new( - ForLoopSetMutations { - method_name, - batch_method_name, - }, - for_stmt.range, - ); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic( + ForLoopSetMutations { + method_name, + batch_method_name, + }, + for_stmt.range, + ) + .set_fix(fix); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/for_loop_writes.rs b/crates/ruff_linter/src/rules/refurb/rules/for_loop_writes.rs index 991d5e29bc..e56b2dc452 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/for_loop_writes.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/for_loop_writes.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprList, ExprName, ExprTuple, Stmt, StmtFor}; use ruff_python_semantic::analyze::typing; @@ -55,26 +55,34 @@ impl AlwaysFixableViolation for ForLoopWrites { } /// FURB122 -pub(crate) fn for_loop_writes_binding(checker: &Checker, binding: &Binding) -> Option { +pub(crate) fn for_loop_writes_binding(checker: &Checker, binding: &Binding) { if !binding.kind.is_loop_var() { - return None; + return; } let semantic = checker.semantic(); - let for_stmt = binding.statement(semantic)?.as_for_stmt()?; + let Some(for_stmt) = binding + .statement(semantic) + .and_then(|stmt| stmt.as_for_stmt()) + else { + return; + }; if for_stmt.is_async { - return None; + return; } let binding_names = binding_names(&for_stmt.target); - if !binding_names.first()?.range().contains_range(binding.range) { - return None; + if !binding_names + .first() + .is_some_and(|name| name.range().contains_range(binding.range)) + { + return; } - for_loop_writes(checker, for_stmt, binding.scope, &binding_names) + for_loop_writes(checker, for_stmt, binding.scope, &binding_names); } /// FURB122 @@ -86,9 +94,7 @@ pub(crate) fn for_loop_writes_stmt(checker: &Checker, for_stmt: &StmtFor) { let scope_id = checker.semantic().scope_id; - if let Some(diagnostic) = for_loop_writes(checker, for_stmt, scope_id, &[]) { - checker.report_diagnostic(diagnostic); - } + for_loop_writes(checker, for_stmt, scope_id, &[]); } /// Find the names in a `for` loop target @@ -125,40 +131,49 @@ fn for_loop_writes( for_stmt: &StmtFor, scope_id: ScopeId, binding_names: &[&ExprName], -) -> Option { +) { if !for_stmt.orelse.is_empty() { - return None; + return; } let [Stmt::Expr(stmt_expr)] = for_stmt.body.as_slice() else { - return None; + return; }; - let call_expr = stmt_expr.value.as_call_expr()?; - let expr_attr = call_expr.func.as_attribute_expr()?; + let Some(call_expr) = stmt_expr.value.as_call_expr() else { + return; + }; + let Some(expr_attr) = call_expr.func.as_attribute_expr() else { + return; + }; if &expr_attr.attr != "write" { - return None; + return; } if !call_expr.arguments.keywords.is_empty() { - return None; + return; } let [write_arg] = call_expr.arguments.args.as_ref() else { - return None; + return; }; - let io_object_name = expr_attr.value.as_name_expr()?; + let Some(io_object_name) = expr_attr.value.as_name_expr() else { + return; + }; let semantic = checker.semantic(); // Determine whether `f` in `f.write()` was bound to a file object. - let binding = semantic.binding(semantic.resolve_name(io_object_name)?); + let Some(name) = semantic.resolve_name(io_object_name) else { + return; + }; + let binding = semantic.binding(name); if !typing::is_io_base(binding, semantic) { - return None; + return; } if loop_variables_are_used_outside_loop(binding_names, for_stmt.range, semantic, scope_id) { - return None; + return; } let locator = checker.locator(); @@ -191,14 +206,14 @@ fn for_loop_writes( applicability, ); - let diagnostic = Diagnostic::new( - ForLoopWrites { - name: io_object_name.id.to_string(), - }, - for_stmt.range, - ); - - Some(diagnostic.with_fix(fix)) + checker + .report_diagnostic( + ForLoopWrites { + name: io_object_name.id.to_string(), + }, + for_stmt.range, + ) + .set_fix(fix); } fn loop_variables_are_used_outside_loop( diff --git a/crates/ruff_linter/src/rules/refurb/rules/fromisoformat_replace_z.rs b/crates/ruff_linter/src/rules/refurb/rules/fromisoformat_replace_z.rs index 6ff1f6caef..85ff8c2c53 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/fromisoformat_replace_z.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/fromisoformat_replace_z.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{ @@ -118,10 +118,11 @@ pub(crate) fn fromisoformat_replace_z(checker: &Checker, call: &ExprCall) { let range_to_remove = TextRange::new(value_full_range.end(), argument.end()); - let diagnostic = Diagnostic::new(FromisoformatReplaceZ, argument.range()); let fix = Fix::unsafe_edit(Edit::range_deletion(range_to_remove)); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(FromisoformatReplaceZ, argument.range()) + .set_fix(fix); } fn func_is_fromisoformat(func: &Expr, semantic: &SemanticModel) -> bool { diff --git a/crates/ruff_linter/src/rules/refurb/rules/fstring_number_format.rs b/crates/ruff_linter/src/rules/refurb/rules/fstring_number_format.rs index 42d12254f3..68767e66ea 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/fstring_number_format.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/fstring_number_format.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall, Number, PythonVersion, UnaryOp}; use ruff_source_file::find_newline; @@ -145,7 +145,7 @@ pub(crate) fn fstring_number_format(checker: &Checker, subscript: &ast::ExprSubs let replacement = try_create_replacement(checker, arg, base); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( FStringNumberFormat { replacement: replacement.as_deref().map(SourceCodeSnippet::from_str), base, @@ -157,8 +157,6 @@ pub(crate) fn fstring_number_format(checker: &Checker, subscript: &ast::ExprSubs let edit = Edit::range_replacement(replacement, subscript.range()); diagnostic.set_fix(Fix::applicable_edit(edit, applicability)); } - - checker.report_diagnostic(diagnostic); } /// Generate a replacement, if possible. diff --git a/crates/ruff_linter/src/rules/refurb/rules/hardcoded_string_charset.rs b/crates/ruff_linter/src/rules/refurb/rules/hardcoded_string_charset.rs index 38e95d0cb9..c92f1450f9 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/hardcoded_string_charset.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/hardcoded_string_charset.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::importer::ImportRequest; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprStringLiteral; use ruff_text_size::TextRange; @@ -129,7 +129,7 @@ fn check_charset_exact(bytes: &[u8]) -> Option<&NamedCharset> { fn push_diagnostic(checker: &Checker, range: TextRange, charset: &NamedCharset) { let name = charset.name; - let mut diagnostic = Diagnostic::new(HardcodedStringCharset { name }, range); + let mut diagnostic = checker.report_diagnostic(HardcodedStringCharset { name }, range); diagnostic.try_set_fix(|| { let (edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("string", name), @@ -141,5 +141,4 @@ fn push_diagnostic(checker: &Checker, range: TextRange, charset: &NamedCharset) [edit], )) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/hashlib_digest_hex.rs b/crates/ruff_linter/src/rules/refurb/rules/hashlib_digest_hex.rs index 688799396d..3f6e37bf09 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/hashlib_digest_hex.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/hashlib_digest_hex.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; use ruff_python_semantic::Modules; @@ -109,13 +109,12 @@ pub(crate) fn hashlib_digest_hex(checker: &Checker, call: &ExprCall) { ) }) { - let mut diagnostic = Diagnostic::new(HashlibDigestHex, call.range()); + let mut diagnostic = checker.report_diagnostic(HashlibDigestHex, call.range()); if arguments.is_empty() { diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( ".hexdigest".to_string(), TextRange::new(value.end(), call.func.end()), ))); } - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/if_exp_instead_of_or_operator.rs b/crates/ruff_linter/src/rules/refurb/rules/if_exp_instead_of_or_operator.rs index bce08c481d..a1cc69838b 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/if_exp_instead_of_or_operator.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/if_exp_instead_of_or_operator.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::Expr; @@ -67,7 +67,7 @@ pub(crate) fn if_exp_instead_of_or_operator(checker: &Checker, if_expr: &ast::Ex return; } - let mut diagnostic = Diagnostic::new(IfExpInsteadOfOrOperator, *range); + let mut diagnostic = checker.report_diagnostic(IfExpInsteadOfOrOperator, *range); // Replace with `{test} or {orelse}`. diagnostic.set_fix(Fix::applicable_edit( @@ -85,8 +85,6 @@ pub(crate) fn if_exp_instead_of_or_operator(checker: &Checker, if_expr: &ast::Ex Applicability::Safe }, )); - - checker.report_diagnostic(diagnostic); } /// Parenthesize an expression for use in an `or` operator (e.g., parenthesize `x` in `x or y`), diff --git a/crates/ruff_linter/src/rules/refurb/rules/if_expr_min_max.rs b/crates/ruff_linter/src/rules/refurb/rules/if_expr_min_max.rs index 2d1c664b5a..89984e116d 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/if_expr_min_max.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/if_expr_min_max.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::{self as ast, CmpOp, Expr}; @@ -130,7 +130,7 @@ pub(crate) fn if_expr_min_max(checker: &Checker, if_exp: &ast::ExprIf) { checker.generator().expr(arg2), ); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( IfExprMinMax { min_max, expression: SourceCodeSnippet::from_str(checker.locator().slice(if_exp)), @@ -145,8 +145,6 @@ pub(crate) fn if_expr_min_max(checker: &Checker, if_exp: &ast::ExprIf) { if_exp.range(), ))); } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/refurb/rules/implicit_cwd.rs b/crates/ruff_linter/src/rules/refurb/rules/implicit_cwd.rs index 8191b5baa0..e11b9ecfcb 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/implicit_cwd.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/implicit_cwd.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprAttribute, ExprCall}; use ruff_text_size::Ranged; @@ -88,7 +88,7 @@ pub(crate) fn no_implicit_cwd(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new(ImplicitCwd, call.range()); + let mut diagnostic = checker.report_diagnostic(ImplicitCwd, call.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( @@ -101,6 +101,4 @@ pub(crate) fn no_implicit_cwd(checker: &Checker, call: &ExprCall) { [import_edit], )) }); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/int_on_sliced_str.rs b/crates/ruff_linter/src/rules/refurb/rules/int_on_sliced_str.rs index 559decd68c..14c8cb64de 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/int_on_sliced_str.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/int_on_sliced_str.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprCall, Identifier}; use ruff_text_size::Ranged; @@ -116,7 +116,7 @@ pub(crate) fn int_on_sliced_str(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new(IntOnSlicedStr { base: base_u8 }, call.range()); + let mut diagnostic = checker.report_diagnostic(IntOnSlicedStr { base: base_u8 }, call.range()); diagnostic.set_fix(Fix::unsafe_edits( Edit::range_replacement( checker.locator().slice(&*expr_subscript.value).to_string(), @@ -124,5 +124,4 @@ pub(crate) fn int_on_sliced_str(checker: &Checker, call: &ExprCall) { ), [Edit::range_replacement("0".to_string(), base.range())], )); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/isinstance_type_none.rs b/crates/ruff_linter/src/rules/refurb/rules/isinstance_type_none.rs index 74cd1d2286..adf7f45a41 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/isinstance_type_none.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/isinstance_type_none.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, FixAvailability, Violation}; +use ruff_diagnostics::{FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Operator}; use ruff_python_semantic::SemanticModel; @@ -69,9 +69,9 @@ pub(crate) fn isinstance_type_none(checker: &Checker, call: &ast::ExprCall) { } let fix = replace_with_identity_check(expr, call.range, false, checker); - let diagnostic = Diagnostic::new(IsinstanceTypeNone, call.range); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(IsinstanceTypeNone, call.range) + .set_fix(fix); } /// Returns `true` if the given expression is equivalent to checking if the diff --git a/crates/ruff_linter/src/rules/refurb/rules/list_reverse_copy.rs b/crates/ruff_linter/src/rules/refurb/rules/list_reverse_copy.rs index 93efd089f0..9a6ae7f2c9 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/list_reverse_copy.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/list_reverse_copy.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ Expr, ExprCall, ExprName, ExprSlice, ExprSubscript, ExprUnaryOp, Int, StmtAssign, UnaryOp, @@ -89,18 +89,17 @@ pub(crate) fn list_assign_reversed(checker: &Checker, assign: &StmtAssign) { return; } - checker.report_diagnostic( - Diagnostic::new( + checker + .report_diagnostic( ListReverseCopy { name: target_expr.id.to_string(), }, assign.range(), ) - .with_fix(Fix::unsafe_edit(Edit::range_replacement( + .set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("{}.reverse()", target_expr.id), assign.range(), - ))), - ); + ))); } /// Recursively removes any `list` wrappers from the expression. diff --git a/crates/ruff_linter/src/rules/refurb/rules/math_constant.rs b/crates/ruff_linter/src/rules/refurb/rules/math_constant.rs index b3a0f3bf63..96f265ad33 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/math_constant.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/math_constant.rs @@ -1,6 +1,6 @@ use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Number}; use ruff_text_size::Ranged; @@ -55,7 +55,7 @@ pub(crate) fn math_constant(checker: &Checker, literal: &ast::ExprNumberLiteral) }; if let Some(constant) = Constant::from_value(value) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( MathConstant { literal: checker.locator().slice(literal).into(), constant: constant.name(), @@ -63,7 +63,6 @@ pub(crate) fn math_constant(checker: &Checker, literal: &ast::ExprNumberLiteral) literal.range(), ); diagnostic.try_set_fix(|| convert_to_constant(literal, constant.name(), checker)); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/metaclass_abcmeta.rs b/crates/ruff_linter/src/rules/refurb/rules/metaclass_abcmeta.rs index e71c3e68a2..52c848f778 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/metaclass_abcmeta.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/metaclass_abcmeta.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StmtClassDef; use ruff_text_size::{Ranged, TextRange}; @@ -69,7 +69,7 @@ pub(crate) fn metaclass_abcmeta(checker: &Checker, class_def: &StmtClassDef) { return; } - let mut diagnostic = Diagnostic::new(MetaClassABCMeta, keyword.range); + let mut diagnostic = checker.report_diagnostic(MetaClassABCMeta, keyword.range); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( @@ -99,6 +99,4 @@ pub(crate) fn metaclass_abcmeta(checker: &Checker, class_def: &StmtClassDef) { ) }) }); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/print_empty_string.rs b/crates/ruff_linter/src/rules/refurb/rules/print_empty_string.rs index b20beda23a..c6cec31947 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/print_empty_string.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/print_empty_string.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::contains_effect; use ruff_python_ast::{self as ast, Expr}; @@ -84,7 +84,8 @@ pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) { Reason::EmptyArgument }; - let mut diagnostic = Diagnostic::new(PrintEmptyString { reason }, call.range()); + let mut diagnostic = + checker.report_diagnostic(PrintEmptyString { reason }, call.range()); diagnostic.set_fix( EmptyStringFix::from_call( @@ -95,8 +96,6 @@ pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) { ) .into_fix(), ); - - checker.report_diagnostic(diagnostic); } [arg] if arg.is_starred_expr() => { @@ -107,7 +106,7 @@ pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) { [] | [_] => { // If there's a `sep` argument, remove it, regardless of what it is. if call.arguments.find_keyword("sep").is_some() { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PrintEmptyString { reason: Reason::UselessSeparator, }, @@ -123,8 +122,6 @@ pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) { ) .into_fix(), ); - - checker.report_diagnostic(diagnostic); } } @@ -170,7 +167,7 @@ pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) { Separator::Remove }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( PrintEmptyString { reason: if separator == Separator::Retain { Reason::EmptyArgument @@ -185,8 +182,6 @@ pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) { EmptyStringFix::from_call(call, separator, checker.semantic(), checker.generator()) .into_fix(), ); - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/read_whole_file.rs b/crates/ruff_linter/src/rules/refurb/rules/read_whole_file.rs index 806be8f883..517a5dffdf 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/read_whole_file.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/read_whole_file.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::{self, Visitor}; use ruff_python_ast::{self as ast, Expr}; @@ -92,7 +92,7 @@ impl<'a> Visitor<'a> for ReadMatcher<'a, '_> { .position(|open| open.is_ref(read_from)) { let open = self.candidates.remove(open); - self.checker.report_diagnostic(Diagnostic::new( + self.checker.report_diagnostic( ReadWholeFile { filename: SourceCodeSnippet::from_str( &self.checker.generator().expr(open.filename), @@ -100,7 +100,7 @@ impl<'a> Visitor<'a> for ReadMatcher<'a, '_> { suggestion: make_suggestion(&open, self.checker.generator()), }, open.item.range(), - )); + ); } return; } diff --git a/crates/ruff_linter/src/rules/refurb/rules/readlines_in_for.rs b/crates/ruff_linter/src/rules/refurb/rules/readlines_in_for.rs index a8ac3d1f5b..89bafa3ce0 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/readlines_in_for.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/readlines_in_for.rs @@ -1,5 +1,5 @@ use crate::preview::is_readlines_in_for_fix_safe_enabled; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Comprehension, Expr, StmtFor}; use ruff_python_semantic::analyze::typing; @@ -85,7 +85,7 @@ fn readlines_in_iter(checker: &Checker, iter_expr: &Expr) { } } - let mut diagnostic = Diagnostic::new(ReadlinesInFor, expr_call.range()); + let mut diagnostic = checker.report_diagnostic(ReadlinesInFor, expr_call.range()); diagnostic.set_fix(if is_readlines_in_for_fix_safe_enabled(checker.settings) { Fix::safe_edit(Edit::range_deletion( expr_call.range().add_start(expr_attr.value.range().len()), @@ -95,5 +95,4 @@ fn readlines_in_iter(checker: &Checker, iter_expr: &Expr) { expr_call.range().add_start(expr_attr.value.range().len()), )) }); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/refurb/rules/redundant_log_base.rs b/crates/ruff_linter/src/rules/refurb/rules/redundant_log_base.rs index 445215aa90..d9e4b79ff2 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/redundant_log_base.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/redundant_log_base.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Number}; use ruff_text_size::Ranged; @@ -96,7 +96,7 @@ pub(crate) fn redundant_log_base(checker: &Checker, call: &ast::ExprCall) { return; }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RedundantLogBase { base, arg: checker.locator().slice(arg).into(), @@ -104,7 +104,6 @@ pub(crate) fn redundant_log_base(checker: &Checker, call: &ast::ExprCall) { call.range(), ); diagnostic.try_set_fix(|| generate_fix(checker, call, base, arg)); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/refurb/rules/regex_flag_alias.rs b/crates/ruff_linter/src/rules/refurb/rules/regex_flag_alias.rs index 1c76b1c196..e0269f57e7 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/regex_flag_alias.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/regex_flag_alias.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::Modules; @@ -74,7 +74,7 @@ pub(crate) fn regex_flag_alias(checker: &Checker, expr: &Expr) { return; }; - let mut diagnostic = Diagnostic::new(RegexFlagAlias { flag }, expr.range()); + let mut diagnostic = checker.report_diagnostic(RegexFlagAlias { flag }, expr.range()); diagnostic.try_set_fix(|| { let (edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("re", flag.full_name()), @@ -86,7 +86,6 @@ pub(crate) fn regex_flag_alias(checker: &Checker, expr: &Expr) { [edit], )) }); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/refurb/rules/reimplemented_operator.rs b/crates/ruff_linter/src/rules/refurb/rules/reimplemented_operator.rs index 751f009378..4923c69f14 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/reimplemented_operator.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/reimplemented_operator.rs @@ -4,7 +4,7 @@ use std::fmt::{Debug, Display, Formatter}; use anyhow::Result; use itertools::Itertools; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_expr; use ruff_python_ast::identifier::Identifier; @@ -112,7 +112,7 @@ pub(crate) fn reimplemented_operator(checker: &Checker, target: &FunctionLike) { return; }; let fix = target.try_fix(&operator, checker.importer(), checker.semantic()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( ReimplementedOperator { operator, target: target.kind(), @@ -120,7 +120,6 @@ pub(crate) fn reimplemented_operator(checker: &Checker, target: &FunctionLike) { target.range(), ); diagnostic.try_set_optional_fix(|| fix); - checker.report_diagnostic(diagnostic); } /// Candidate for lambda expression or function definition consisting of a return statement. diff --git a/crates/ruff_linter/src/rules/refurb/rules/reimplemented_starmap.rs b/crates/ruff_linter/src/rules/refurb/rules/reimplemented_starmap.rs index 17ec6df052..d97d57ccc3 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/reimplemented_starmap.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/reimplemented_starmap.rs @@ -1,5 +1,5 @@ use anyhow::{Result, bail}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::any_over_expr; @@ -133,7 +133,7 @@ pub(crate) fn reimplemented_starmap(checker: &Checker, target: &StarmapCandidate } } - let mut diagnostic = Diagnostic::new(ReimplementedStarmap, target.range()); + let mut diagnostic = checker.report_diagnostic(ReimplementedStarmap, target.range()); diagnostic.try_set_fix(|| { // Import `starmap` from `itertools`. let (import_edit, starmap_name) = checker.importer().get_or_import_symbol( @@ -156,7 +156,6 @@ pub(crate) fn reimplemented_starmap(checker: &Checker, target: &StarmapCandidate ); Ok(Fix::safe_edits(import_edit, [main_edit])) }); - checker.report_diagnostic(diagnostic); } /// An enum for a node that can be considered a candidate for replacement with `starmap`. diff --git a/crates/ruff_linter/src/rules/refurb/rules/repeated_append.rs b/crates/ruff_linter/src/rules/refurb/rules/repeated_append.rs index ed1f940e31..7224dcc877 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/repeated_append.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/repeated_append.rs @@ -1,7 +1,7 @@ use rustc_hash::FxHashMap; use ast::traversal; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::traversal::EnclosingSuite; use ruff_python_ast::{self as ast, Expr, Stmt}; @@ -94,7 +94,7 @@ pub(crate) fn repeated_append(checker: &Checker, stmt: &Stmt) { let replacement = make_suggestion(&group, checker.generator()); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( RepeatedAppend { name: group.name().to_string(), replacement: SourceCodeSnippet::new(replacement.clone()), @@ -119,8 +119,6 @@ pub(crate) fn repeated_append(checker: &Checker, stmt: &Stmt) { group.end(), ))); } - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/repeated_global.rs b/crates/ruff_linter/src/rules/refurb/rules/repeated_global.rs index 8f2ecfe18d..aafb0cdd1a 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/repeated_global.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/repeated_global.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; @@ -74,25 +74,23 @@ pub(crate) fn repeated_global(checker: &Checker, mut suite: &[Stmt]) { // diagnostic. if let [first, .., last] = globals_sequence { let range = first.range().cover(last.range()); - checker.report_diagnostic( - Diagnostic::new(RepeatedGlobal { global_kind }, range).with_fix(Fix::safe_edit( - Edit::range_replacement( - format!( - "{global_kind} {}", - globals_sequence - .iter() - .flat_map(|stmt| match stmt { - Stmt::Global(stmt) => &stmt.names, - Stmt::Nonlocal(stmt) => &stmt.names, - _ => unreachable!(), - }) - .map(ruff_python_ast::Identifier::id) - .format(", ") - ), - range, + checker + .report_diagnostic(RepeatedGlobal { global_kind }, range) + .set_fix(Fix::safe_edit(Edit::range_replacement( + format!( + "{global_kind} {}", + globals_sequence + .iter() + .flat_map(|stmt| match stmt { + Stmt::Global(stmt) => &stmt.names, + Stmt::Nonlocal(stmt) => &stmt.names, + _ => unreachable!(), + }) + .map(ruff_python_ast::Identifier::id) + .format(", ") ), - )), - ); + range, + ))); } suite = next_suite; diff --git a/crates/ruff_linter/src/rules/refurb/rules/single_item_membership_test.rs b/crates/ruff_linter/src/rules/refurb/rules/single_item_membership_test.rs index a2d2cacbcf..158bb6775d 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/single_item_membership_test.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/single_item_membership_test.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::generate_comparison; use ruff_python_ast::{self as ast, CmpOp, Expr, ExprStringLiteral}; @@ -83,8 +83,6 @@ pub(crate) fn single_item_membership_test( return; }; - let diagnostic = Diagnostic::new(SingleItemMembershipTest { membership_test }, expr.range()); - let edit = Edit::range_replacement( pad( generate_comparison( @@ -110,7 +108,9 @@ pub(crate) fn single_item_membership_test( let fix = Fix::applicable_edit(edit, applicability); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(SingleItemMembershipTest { membership_test }, expr.range()) + .set_fix(fix); } /// Return the single item wrapped in `Some` if the expression contains a single diff --git a/crates/ruff_linter/src/rules/refurb/rules/slice_copy.rs b/crates/ruff_linter/src/rules/refurb/rules/slice_copy.rs index f8e6d1d502..28d9fea480 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/slice_copy.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/slice_copy.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr}; @@ -61,14 +61,13 @@ pub(crate) fn slice_copy(checker: &Checker, subscript: &ast::ExprSubscript) { let Some(name) = match_list_full_slice(subscript, checker.semantic()) else { return; }; - let mut diagnostic = Diagnostic::new(SliceCopy, subscript.range()); + let mut diagnostic = checker.report_diagnostic(SliceCopy, subscript.range()); let replacement = generate_method_call(name.clone(), "copy", checker.generator()); diagnostic.set_fix(Fix::safe_edit(Edit::replacement( replacement, subscript.start(), subscript.end(), ))); - checker.report_diagnostic(diagnostic); } /// Matches `obj[:]` where `obj` is a list. diff --git a/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs b/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs index 6ede511238..43d608ddff 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, PythonVersion}; use ruff_python_semantic::SemanticModel; @@ -78,7 +78,7 @@ pub(crate) fn slice_to_remove_affix_expr(checker: &Checker, if_expr: &ast::ExprI let kind = removal_data.affix_query.kind; let text = removal_data.text; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( SliceToRemovePrefixOrSuffix { affix_kind: kind, stmt_or_expression: StmtOrExpr::Expression, @@ -93,7 +93,6 @@ pub(crate) fn slice_to_remove_affix_expr(checker: &Checker, if_expr: &ast::ExprI if_expr.start(), if_expr.end(), ))); - checker.report_diagnostic(diagnostic); } } } @@ -108,7 +107,7 @@ pub(crate) fn slice_to_remove_affix_stmt(checker: &Checker, if_stmt: &ast::StmtI let kind = removal_data.affix_query.kind; let text = removal_data.text; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( SliceToRemovePrefixOrSuffix { affix_kind: kind, stmt_or_expression: StmtOrExpr::Statement, @@ -127,7 +126,6 @@ pub(crate) fn slice_to_remove_affix_stmt(checker: &Checker, if_stmt: &ast::StmtI if_stmt.start(), if_stmt.end(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/sorted_min_max.rs b/crates/ruff_linter/src/rules/refurb/rules/sorted_min_max.rs index 2eb3834aa6..5bdbe5f748 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/sorted_min_max.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/sorted_min_max.rs @@ -1,4 +1,3 @@ -use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Edit; use ruff_diagnostics::Fix; use ruff_diagnostics::FixAvailability; @@ -178,7 +177,7 @@ pub(crate) fn sorted_min_max(checker: &Checker, subscript: &ast::ExprSubscript) (Index::Last, true) => MinMax::Min, }; - let mut diagnostic = Diagnostic::new(SortedMinMax { min_max }, subscript.range()); + let mut diagnostic = checker.report_diagnostic(SortedMinMax { min_max }, subscript.range()); if checker.semantic().has_builtin_binding(min_max.as_str()) { diagnostic.set_fix({ @@ -200,8 +199,6 @@ pub(crate) fn sorted_min_max(checker: &Checker, subscript: &ast::ExprSubscript) } }); } - - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/refurb/rules/subclass_builtin.rs b/crates/ruff_linter/src/rules/refurb/rules/subclass_builtin.rs index 9f72b42f74..fa35385bed 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/subclass_builtin.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/subclass_builtin.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Arguments, StmtClassDef, helpers::map_subscript}; use ruff_text_size::Ranged; @@ -105,7 +105,7 @@ pub(crate) fn subclass_builtin(checker: &Checker, class: &StmtClassDef) { let user_symbol = supported_builtin.user_symbol(); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( SubclassBuiltin { subclass: symbol.to_string(), replacement: user_symbol.to_string(), @@ -121,7 +121,6 @@ pub(crate) fn subclass_builtin(checker: &Checker, class: &StmtClassDef) { let other_edit = Edit::range_replacement(binding, base_expr.range()); Ok(Fix::unsafe_edits(import_edit, [other_edit])) }); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/refurb/rules/type_none_comparison.rs b/crates/ruff_linter/src/rules/refurb/rules/type_none_comparison.rs index e3abea3319..ea59f4496b 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/type_none_comparison.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/type_none_comparison.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic}; +use ruff_diagnostics::AlwaysFixableViolation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr}; use ruff_python_semantic::SemanticModel; @@ -75,12 +75,12 @@ pub(crate) fn type_none_comparison(checker: &Checker, compare: &ast::ExprCompare _ => return, }; - let diagnostic = Diagnostic::new(TypeNoneComparison { replacement }, compare.range); - let negate = replacement == IdentityCheck::IsNot; let fix = replace_with_identity_check(other_arg, compare.range, negate, checker); - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(TypeNoneComparison { replacement }, compare.range) + .set_fix(fix); } /// Returns the object passed to the function, if the expression is a call to diff --git a/crates/ruff_linter/src/rules/refurb/rules/unnecessary_enumerate.rs b/crates/ruff_linter/src/rules/refurb/rules/unnecessary_enumerate.rs index 36cd8b137a..1795cab986 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/unnecessary_enumerate.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/unnecessary_enumerate.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::name::Name; @@ -124,7 +124,7 @@ pub(crate) fn unnecessary_enumerate(checker: &Checker, stmt_for: &ast::StmtFor) // Both the index and the value are used. } (true, false) => { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEnumerate { subset: EnumerateSubset::Values, }, @@ -143,8 +143,6 @@ pub(crate) fn unnecessary_enumerate(checker: &Checker, stmt_for: &ast::StmtFor) stmt_for.target.range(), ); diagnostic.set_fix(Fix::unsafe_edits(replace_iter, [replace_target])); - - checker.report_diagnostic(diagnostic); } (false, true) => { // Ensure the sequence object works with `len`. If it doesn't, the @@ -167,7 +165,7 @@ pub(crate) fn unnecessary_enumerate(checker: &Checker, stmt_for: &ast::StmtFor) } // The value is unused, so replace with `for index in range(len(sequence))`. - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEnumerate { subset: EnumerateSubset::Indices, }, @@ -205,7 +203,6 @@ pub(crate) fn unnecessary_enumerate(checker: &Checker, stmt_for: &ast::StmtFor) diagnostic.set_fix(Fix::unsafe_edits(replace_iter, [replace_target])); } } - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.rs b/crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.rs index 549608ca16..b5352a1322 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall}; use ruff_text_size::Ranged; @@ -92,7 +92,7 @@ pub(crate) fn unnecessary_from_float(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryFromFloat { method_name, constructor, @@ -157,13 +157,11 @@ pub(crate) fn unnecessary_from_float(checker: &Checker, call: &ExprCall) { edit, [Edit::range_replacement(replacement, call.range())], )); - checker.report_diagnostic(diagnostic); return; } diagnostic.set_fix(Fix::safe_edit(edit)); - checker.report_diagnostic(diagnostic); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/crates/ruff_linter/src/rules/refurb/rules/verbose_decimal_constructor.rs b/crates/ruff_linter/src/rules/refurb/rules/verbose_decimal_constructor.rs index a37996e60c..140be4fd9a 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/verbose_decimal_constructor.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/verbose_decimal_constructor.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_trivia::PythonWhitespace; @@ -71,7 +71,7 @@ pub(crate) fn verbose_decimal_constructor(checker: &Checker, call: &ast::ExprCal return; }; - let diagnostic = match value { + match value { Expr::StringLiteral(ast::ExprStringLiteral { value: str_literal, .. }) => { @@ -120,7 +120,7 @@ pub(crate) fn verbose_decimal_constructor(checker: &Checker, call: &ast::ExprCal }; let replacement = format!("{unary}{rest}"); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( VerboseDecimalConstructor { replacement: replacement.clone(), }, @@ -131,8 +131,6 @@ pub(crate) fn verbose_decimal_constructor(checker: &Checker, call: &ast::ExprCal replacement, value.range(), ))); - - diagnostic } Expr::Call(ast::ExprCall { func, arguments, .. @@ -184,7 +182,7 @@ pub(crate) fn verbose_decimal_constructor(checker: &Checker, call: &ast::ExprCal // does not make sense for this edge case. replacement = "\"nan\"".to_string(); } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( VerboseDecimalConstructor { replacement: replacement.clone(), }, @@ -195,15 +193,9 @@ pub(crate) fn verbose_decimal_constructor(checker: &Checker, call: &ast::ExprCal replacement, value.range(), ))); - - diagnostic } - _ => { - return; - } - }; - - checker.report_diagnostic(diagnostic); + _ => {} + } } // ```console diff --git a/crates/ruff_linter/src/rules/refurb/rules/write_whole_file.rs b/crates/ruff_linter/src/rules/refurb/rules/write_whole_file.rs index 5605918c69..2f9d283b23 100644 --- a/crates/ruff_linter/src/rules/refurb/rules/write_whole_file.rs +++ b/crates/ruff_linter/src/rules/refurb/rules/write_whole_file.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::relocate::relocate_expr; use ruff_python_ast::visitor::{self, Visitor}; @@ -106,7 +106,7 @@ impl<'a> Visitor<'a> for WriteMatcher<'a, '_> { { if self.loop_counter == 0 { let open = self.candidates.remove(open); - self.checker.report_diagnostic(Diagnostic::new( + self.checker.report_diagnostic( WriteWholeFile { filename: SourceCodeSnippet::from_str( &self.checker.generator().expr(open.filename), @@ -114,7 +114,7 @@ impl<'a> Visitor<'a> for WriteMatcher<'a, '_> { suggestion: make_suggestion(&open, content, self.checker.generator()), }, open.item.range(), - )); + ); } else { self.candidates.remove(open); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/ambiguous_unicode_character.rs b/crates/ruff_linter/src/rules/ruff/rules/ambiguous_unicode_character.rs index 9cb21628c5..ae66234b24 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/ambiguous_unicode_character.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/ambiguous_unicode_character.rs @@ -182,7 +182,9 @@ pub(crate) fn ambiguous_unicode_character_comment( settings: &LinterSettings, ) { let text = locator.slice(range); - ambiguous_unicode_character(diagnostics, text, range, Context::Comment, settings); + for candidate in ambiguous_unicode_character(text, range, settings) { + diagnostics.extend(candidate.into_diagnostic(Context::Comment, settings)); + } } /// RUF001, RUF002 @@ -203,32 +205,20 @@ pub(crate) fn ambiguous_unicode_character_string(checker: &Checker, string_like: match part { ast::StringLikePart::String(string_literal) => { let text = checker.locator().slice(string_literal); - let mut diagnostics = Vec::new(); - ambiguous_unicode_character( - &mut diagnostics, - text, - string_literal.range(), - context, - checker.settings, - ); - for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); + for candidate in + ambiguous_unicode_character(text, string_literal.range(), checker.settings) + { + candidate.report_diagnostic(checker, context); } } ast::StringLikePart::Bytes(_) => {} ast::StringLikePart::FString(f_string) => { for literal in f_string.elements.literals() { let text = checker.locator().slice(literal); - let mut diagnostics = Vec::new(); - ambiguous_unicode_character( - &mut diagnostics, - text, - literal.range(), - context, - checker.settings, - ); - for diagnostic in diagnostics { - checker.report_diagnostic(diagnostic); + for candidate in + ambiguous_unicode_character(text, literal.range(), checker.settings) + { + candidate.report_diagnostic(checker, context); } } } @@ -237,15 +227,15 @@ pub(crate) fn ambiguous_unicode_character_string(checker: &Checker, string_like: } fn ambiguous_unicode_character( - diagnostics: &mut Vec, text: &str, range: TextRange, - context: Context, settings: &LinterSettings, -) { +) -> Vec { + let mut candidates = Vec::new(); + // Most of the time, we don't need to check for ambiguous unicode characters at all. if text.is_ascii() { - return; + return candidates; } // Iterate over the "words" in the text. @@ -257,9 +247,7 @@ fn ambiguous_unicode_character( if !word_candidates.is_empty() { if word_flags.is_candidate_word() { for candidate in word_candidates.drain(..) { - if let Some(diagnostic) = candidate.into_diagnostic(context, settings) { - diagnostics.push(diagnostic); - } + candidates.push(candidate); } } word_candidates.clear(); @@ -277,9 +265,7 @@ fn ambiguous_unicode_character( current_char, representant, ); - if let Some(diagnostic) = candidate.into_diagnostic(context, settings) { - diagnostics.push(diagnostic); - } + candidates.push(candidate); } } } else if current_char.is_ascii() { @@ -304,13 +290,13 @@ fn ambiguous_unicode_character( if !word_candidates.is_empty() { if word_flags.is_candidate_word() { for candidate in word_candidates.drain(..) { - if let Some(diagnostic) = candidate.into_diagnostic(context, settings) { - diagnostics.push(diagnostic); - } + candidates.push(candidate); } } word_candidates.clear(); } + + candidates } bitflags! { @@ -388,6 +374,39 @@ impl Candidate { } None } + + fn report_diagnostic(self, checker: &Checker, context: Context) { + if !checker + .settings + .allowed_confusables + .contains(&self.confusable) + { + let char_range = TextRange::at(self.offset, self.confusable.text_len()); + match context { + Context::String => checker.report_diagnostic_if_enabled( + AmbiguousUnicodeCharacterString { + confusable: self.confusable, + representant: self.representant, + }, + char_range, + ), + Context::Docstring => checker.report_diagnostic_if_enabled( + AmbiguousUnicodeCharacterDocstring { + confusable: self.confusable, + representant: self.representant, + }, + char_range, + ), + Context::Comment => checker.report_diagnostic_if_enabled( + AmbiguousUnicodeCharacterComment { + confusable: self.confusable, + representant: self.representant, + }, + char_range, + ), + }; + } + } } struct NamedUnicode(char); diff --git a/crates/ruff_linter/src/rules/ruff/rules/assert_with_print_message.rs b/crates/ruff_linter/src/rules/ruff/rules/assert_with_print_message.rs index d11d854384..1d2decaf56 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/assert_with_print_message.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/assert_with_print_message.rs @@ -1,7 +1,7 @@ use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::{Ranged, TextRange}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; @@ -62,7 +62,7 @@ pub(crate) fn assert_with_print_message(checker: &Checker, stmt: &ast::StmtAsser if semantic.match_builtin_expr(&call.func, "print") { // This is the confirmed rule condition - let mut diagnostic = Diagnostic::new(AssertWithPrintMessage, call.range()); + let mut diagnostic = checker.report_diagnostic(AssertWithPrintMessage, call.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( checker.generator().stmt(&Stmt::Assert(ast::StmtAssert { test: stmt.test.clone(), @@ -74,7 +74,6 @@ pub(crate) fn assert_with_print_message(checker: &Checker, stmt: &ast::StmtAsser // will cease to exist. stmt.range(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/assignment_in_assert.rs b/crates/ruff_linter/src/rules/ruff/rules/assignment_in_assert.rs index 2674f43198..e4e08bb1df 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/assignment_in_assert.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/assignment_in_assert.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Binding; use ruff_text_size::Ranged; @@ -58,24 +58,26 @@ impl Violation for AssignmentInAssert { } /// RUF018 -pub(crate) fn assignment_in_assert(checker: &Checker, binding: &Binding) -> Option { +pub(crate) fn assignment_in_assert(checker: &Checker, binding: &Binding) { if !binding.in_assert_statement() { - return None; + return; } let semantic = checker.semantic(); - let parent_expression = binding.expression(semantic)?.as_named_expr()?; + let Some(parent_expression) = binding + .expression(semantic) + .and_then(|expr| expr.as_named_expr()) + else { + return; + }; if binding .references() .all(|reference| semantic.reference(reference).in_assert_statement()) { - return None; + return; } - Some(Diagnostic::new( - AssignmentInAssert, - parent_expression.range(), - )) + checker.report_diagnostic(AssignmentInAssert, parent_expression.range()); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/asyncio_dangling_task.rs b/crates/ruff_linter/src/rules/ruff/rules/asyncio_dangling_task.rs index e69ba982af..e125e77616 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/asyncio_dangling_task.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/asyncio_dangling_task.rs @@ -1,7 +1,7 @@ use std::fmt; use ast::Stmt; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::{Scope, SemanticModel, analyze::typing}; @@ -67,9 +67,9 @@ impl Violation for AsyncioDanglingTask { } /// RUF006 -pub(crate) fn asyncio_dangling_task(expr: &Expr, semantic: &SemanticModel) -> Option { +pub(crate) fn asyncio_dangling_task(checker: &Checker, expr: &Expr, semantic: &SemanticModel) { let Expr::Call(ast::ExprCall { func, .. }) = expr else { - return None; + return; }; // Ex) `asyncio.create_task(...)` @@ -81,15 +81,14 @@ pub(crate) fn asyncio_dangling_task(expr: &Expr, semantic: &SemanticModel) -> Op _ => None, }) { - return Some(Diagnostic::new( + checker.report_diagnostic( AsyncioDanglingTask { expr: "asyncio".to_string(), method, }, expr.range(), - )); - } - + ); + } else // Ex) `loop = ...; loop.create_task(...)` if let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func.as_ref() { if attr == "create_task" { @@ -103,18 +102,17 @@ pub(crate) fn asyncio_dangling_task(expr: &Expr, semantic: &SemanticModel) -> Op ] ) }) { - return Some(Diagnostic::new( + checker.report_diagnostic( AsyncioDanglingTask { expr: name.id.to_string(), method: Method::CreateTask, }, expr.range(), - )); + ); } } } } - None } /// RUF006 @@ -153,18 +151,14 @@ pub(crate) fn asyncio_dangling_binding(scope: &Scope, checker: &Checker) { continue; }; - let diagnostic = match semantic.statement(source) { + match semantic.statement(source) { Stmt::Assign(ast::StmtAssign { value, targets, .. }) if targets.len() == 1 => { - asyncio_dangling_task(value, semantic) + asyncio_dangling_task(checker, value, semantic); } Stmt::AnnAssign(ast::StmtAnnAssign { value: Some(value), .. - }) => asyncio_dangling_task(value, semantic), - _ => None, - }; - - if let Some(diagnostic) = diagnostic { - checker.report_diagnostic(diagnostic); + }) => asyncio_dangling_task(checker, value, semantic), + _ => {} } } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/class_with_mixed_type_vars.rs b/crates/ruff_linter/src/rules/ruff/rules/class_with_mixed_type_vars.rs index 08568f2afb..52a58882fe 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/class_with_mixed_type_vars.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/class_with_mixed_type_vars.rs @@ -1,7 +1,7 @@ use rustc_hash::FxHashSet; use std::iter; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ Arguments, Expr, ExprStarred, ExprSubscript, ExprTuple, StmtClassDef, TypeParams, @@ -103,7 +103,7 @@ pub(crate) fn class_with_mixed_type_vars(checker: &Checker, class_def: &StmtClas return; }; - let mut diagnostic = Diagnostic::new(ClassWithMixedTypeVars, generic_base.range); + let mut diagnostic = checker.report_diagnostic(ClassWithMixedTypeVars, generic_base.range); diagnostic.try_set_optional_fix(|| { convert_type_vars( @@ -114,8 +114,6 @@ pub(crate) fn class_with_mixed_type_vars(checker: &Checker, class_def: &StmtClas checker, ) }); - - checker.report_diagnostic(diagnostic); } fn typing_generic_base_and_arguments<'a>( diff --git a/crates/ruff_linter/src/rules/ruff/rules/collection_literal_concatenation.rs b/crates/ruff_linter/src/rules/ruff/rules/collection_literal_concatenation.rs index acf3d6a4a6..743808b741 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/collection_literal_concatenation.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/collection_literal_concatenation.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprContext, Operator}; use ruff_text_size::{Ranged, TextRange}; @@ -210,7 +210,7 @@ pub(crate) fn collection_literal_concatenation(checker: &Checker, expr: &Expr) { Type::Tuple => format!("({})", checker.generator().expr(&new_expr)), Type::List => checker.generator().expr(&new_expr), }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( CollectionLiteralConcatenation { expression: SourceCodeSnippet::new(contents.clone()), }, @@ -227,5 +227,4 @@ pub(crate) fn collection_literal_concatenation(checker: &Checker, expr: &Expr) { expr.range(), ))); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/dataclass_enum.rs b/crates/ruff_linter/src/rules/ruff/rules/dataclass_enum.rs index 3d168d8c3f..d32429b66d 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/dataclass_enum.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/dataclass_enum.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::StmtClassDef; use ruff_python_semantic::analyze::class::is_enumeration; @@ -70,7 +70,5 @@ pub(crate) fn dataclass_enum(checker: &Checker, class_def: &StmtClassDef) { return; } - let diagnostic = Diagnostic::new(DataclassEnum, decorator.range); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(DataclassEnum, decorator.range); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/decimal_from_float_literal.rs b/crates/ruff_linter/src/rules/ruff/rules/decimal_from_float_literal.rs index 6458126dec..05da96b2e5 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/decimal_from_float_literal.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/decimal_from_float_literal.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_codegen::Stylist; @@ -60,10 +60,14 @@ pub(crate) fn decimal_from_float_literal_syntax(checker: &Checker, call: &ast::E matches!(qualified_name.segments(), ["decimal", "Decimal"]) }) { - let diagnostic = Diagnostic::new(DecimalFromFloatLiteral, arg.range()).with_fix( - fix_float_literal(arg.range(), float, checker.locator(), checker.stylist()), - ); - checker.report_diagnostic(diagnostic); + checker + .report_diagnostic(DecimalFromFloatLiteral, arg.range()) + .set_fix(fix_float_literal( + arg.range(), + float, + checker.locator(), + checker.stylist(), + )); } } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/default_factory_kwarg.rs b/crates/ruff_linter/src/rules/ruff/rules/default_factory_kwarg.rs index 521bd5d90a..f569c45366 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/default_factory_kwarg.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/default_factory_kwarg.rs @@ -1,7 +1,7 @@ use anyhow::Result; use ast::Keyword; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_constant; use ruff_python_ast::{self as ast, Expr}; @@ -100,14 +100,13 @@ pub(crate) fn default_factory_kwarg(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( DefaultFactoryKwarg { default_factory: SourceCodeSnippet::from_str(checker.locator().slice(keyword)), }, call.range(), ); diagnostic.try_set_fix(|| convert_to_positional(call, keyword, checker.locator())); - checker.report_diagnostic(diagnostic); } /// Returns `true` if a value is definitively not callable (e.g., `1` or `[]`). diff --git a/crates/ruff_linter/src/rules/ruff/rules/explicit_f_string_type_conversion.rs b/crates/ruff_linter/src/rules/ruff/rules/explicit_f_string_type_conversion.rs index eaf93d17dd..15e836e0f2 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/explicit_f_string_type_conversion.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/explicit_f_string_type_conversion.rs @@ -1,6 +1,6 @@ use anyhow::{Result, bail}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr}; use ruff_python_codegen::Stylist; @@ -108,11 +108,11 @@ pub(crate) fn explicit_f_string_type_conversion(checker: &Checker, f_string: &as continue; } - let mut diagnostic = Diagnostic::new(ExplicitFStringTypeConversion, expression.range()); + let mut diagnostic = + checker.report_diagnostic(ExplicitFStringTypeConversion, expression.range()); diagnostic.try_set_fix(|| { convert_call_to_conversion_flag(f_string, index, checker.locator(), checker.stylist()) }); - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/falsy_dict_get_fallback.rs b/crates/ruff_linter/src/rules/ruff/rules/falsy_dict_get_fallback.rs index 9e8c045216..921416a37c 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/falsy_dict_get_fallback.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/falsy_dict_get_fallback.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::fix::edits::{Parentheses, remove_argument}; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprAttribute, helpers::Truthiness}; use ruff_python_semantic::analyze::typing; @@ -86,7 +86,7 @@ pub(crate) fn falsy_dict_get_fallback(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new(FalsyDictGetFallback, fallback_arg.range()); + let mut diagnostic = checker.report_diagnostic(FalsyDictGetFallback, fallback_arg.range()); let comment_ranges = checker.comment_ranges(); @@ -106,6 +106,4 @@ pub(crate) fn falsy_dict_get_fallback(checker: &Checker, expr: &Expr) { ) .map(|edit| Fix::applicable_edit(edit, applicability)) }); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/function_call_in_dataclass_default.rs b/crates/ruff_linter/src/rules/ruff/rules/function_call_in_dataclass_default.rs index debba91fae..77159ed537 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/function_call_in_dataclass_default.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/function_call_in_dataclass_default.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; use ruff_python_semantic::analyze::typing::{ @@ -150,9 +150,7 @@ pub(crate) fn function_call_in_dataclass_default(checker: &Checker, class_def: & let kind = FunctionCallInDataclassDefaultArgument { name: UnqualifiedName::from_expr(func).map(|name| name.to_string()), }; - let diagnostic = Diagnostic::new(kind, expr.range()); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(kind, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/if_key_in_dict_del.rs b/crates/ruff_linter/src/rules/ruff/rules/if_key_in_dict_del.rs index f44d19d9e7..5dd3962ef2 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/if_key_in_dict_del.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/if_key_in_dict_del.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{CmpOp, Expr, ExprName, ExprSubscript, Stmt, StmtIf}; use ruff_python_semantic::analyze::typing; @@ -65,9 +65,9 @@ pub(crate) fn if_key_in_dict_del(checker: &Checker, stmt: &StmtIf) { let fix = replace_with_dict_pop_fix(checker, stmt, test_dict, test_key); - let diagnostic = Diagnostic::new(IfKeyInDictDel, delete.range); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(IfKeyInDictDel, delete.range) + .set_fix(fix); } fn extract_dict_and_key_from_test(test: &Expr) -> Option<(&Dict, &Key)> { diff --git a/crates/ruff_linter/src/rules/ruff/rules/implicit_classvar_in_dataclass.rs b/crates/ruff_linter/src/rules/ruff/rules/implicit_classvar_in_dataclass.rs index 91643214f9..8968369fee 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/implicit_classvar_in_dataclass.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/implicit_classvar_in_dataclass.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_dunder; use ruff_python_ast::{Expr, ExprName, Stmt, StmtAssign, StmtClassDef}; @@ -95,8 +95,6 @@ pub(crate) fn implicit_class_var_in_dataclass(checker: &mut Checker, class_def: continue; } - let diagnostic = Diagnostic::new(ImplicitClassVarInDataclass, target.range()); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(ImplicitClassVarInDataclass, target.range()); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/implicit_optional.rs b/crates/ruff_linter/src/rules/ruff/rules/implicit_optional.rs index 298d261e43..c24ec7fa27 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/implicit_optional.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/implicit_optional.rs @@ -2,7 +2,7 @@ use std::fmt; use anyhow::{Context, Result}; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; @@ -187,11 +187,10 @@ pub(crate) fn implicit_optional(checker: &Checker, parameters: &Parameters) { let conversion_type = checker.target_version().into(); let mut diagnostic = - Diagnostic::new(ImplicitOptional { conversion_type }, expr.range()); + checker.report_diagnostic(ImplicitOptional { conversion_type }, expr.range()); if parsed_annotation.kind().is_simple() { diagnostic.try_set_fix(|| generate_fix(checker, conversion_type, expr)); } - checker.report_diagnostic(diagnostic); } } else { // Unquoted annotation. @@ -203,9 +202,8 @@ pub(crate) fn implicit_optional(checker: &Checker, parameters: &Parameters) { let conversion_type = checker.target_version().into(); let mut diagnostic = - Diagnostic::new(ImplicitOptional { conversion_type }, expr.range()); + checker.report_diagnostic(ImplicitOptional { conversion_type }, expr.range()); diagnostic.try_set_fix(|| generate_fix(checker, conversion_type, expr)); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/in_empty_collection.rs b/crates/ruff_linter/src/rules/ruff/rules/in_empty_collection.rs index 1fe9f7675c..55d2374a82 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/in_empty_collection.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/in_empty_collection.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, CmpOp, Expr}; use ruff_python_semantic::SemanticModel; @@ -51,7 +51,7 @@ pub(crate) fn in_empty_collection(checker: &Checker, compare: &ast::ExprCompare) let semantic = checker.semantic(); if is_empty(right, semantic) { - checker.report_diagnostic(Diagnostic::new(InEmptyCollection, compare.range())); + checker.report_diagnostic(InEmptyCollection, compare.range()); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/incorrectly_parenthesized_tuple_in_subscript.rs b/crates/ruff_linter/src/rules/ruff/rules/incorrectly_parenthesized_tuple_in_subscript.rs index 44956550d2..a3b3cc6718 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/incorrectly_parenthesized_tuple_in_subscript.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/incorrectly_parenthesized_tuple_in_subscript.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprSubscript, PythonVersion}; use ruff_text_size::Ranged; @@ -111,11 +111,10 @@ pub(crate) fn subscript_with_parenthesized_tuple(checker: &Checker, subscript: & }; let edit = Edit::range_replacement(new_source, source_range); - checker.report_diagnostic( - Diagnostic::new( + checker + .report_diagnostic( IncorrectlyParenthesizedTupleInSubscript { prefer_parentheses }, source_range, ) - .with_fix(Fix::safe_edit(edit)), - ); + .set_fix(Fix::safe_edit(edit)); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/invalid_assert_message_literal_argument.rs b/crates/ruff_linter/src/rules/ruff/rules/invalid_assert_message_literal_argument.rs index b7d74d1258..fecad284df 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/invalid_assert_message_literal_argument.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/invalid_assert_message_literal_argument.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, StmtAssert}; use ruff_text_size::Ranged; @@ -52,8 +52,5 @@ pub(crate) fn invalid_assert_message_literal_argument(checker: &Checker, stmt: & return; } - checker.report_diagnostic(Diagnostic::new( - InvalidAssertMessageLiteralArgument, - message.range(), - )); + checker.report_diagnostic(InvalidAssertMessageLiteralArgument, message.range()); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/invalid_formatter_suppression_comment.rs b/crates/ruff_linter/src/rules/ruff/rules/invalid_formatter_suppression_comment.rs index 0e1bbd329a..ad873444ca 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/invalid_formatter_suppression_comment.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/invalid_formatter_suppression_comment.rs @@ -3,7 +3,7 @@ use std::fmt::Display; use smallvec::SmallVec; use ast::{StmtClassDef, StmtFunctionDef}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, AnyNodeRef, helpers::comment_indentation_after}; use ruff_python_trivia::{SuppressionKind, indentation_at_offset}; @@ -105,10 +105,9 @@ pub(crate) fn ignored_formatter_suppression_comment(checker: &Checker, suite: &a comments.sort(); for (range, reason) in comments.ignored_comments() { - checker.report_diagnostic( - Diagnostic::new(InvalidFormatterSuppressionComment { reason }, range) - .with_fix(Fix::unsafe_edit(delete_comment(range, checker.locator()))), - ); + checker + .report_diagnostic(InvalidFormatterSuppressionComment { reason }, range) + .set_fix(Fix::unsafe_edit(delete_comment(range, checker.locator()))); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/invalid_index_type.rs b/crates/ruff_linter/src/rules/ruff/rules/invalid_index_type.rs index 0118b35a91..fca2b26aef 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/invalid_index_type.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/invalid_index_type.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{Expr, ExprNumberLiteral, ExprSlice, ExprSubscript, Number}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use std::fmt; @@ -90,14 +90,14 @@ pub(crate) fn invalid_index_type(checker: &Checker, expr: &ExprSubscript) { if index_type.is_literal() { // If the index is a literal, require an integer if index_type != CheckableExprType::IntLiteral { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( InvalidIndexType { value_type: value_type.to_string(), index_type: index_type.to_string(), is_slice: false, }, index.range(), - )); + ); } } else if let Expr::Slice(ExprSlice { lower, upper, step, .. @@ -113,36 +113,36 @@ pub(crate) fn invalid_index_type(checker: &Checker, expr: &ExprSubscript) { is_slice_type, CheckableExprType::IntLiteral | CheckableExprType::NoneLiteral ) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( InvalidIndexType { value_type: value_type.to_string(), index_type: is_slice_type.to_string(), is_slice: true, }, is_slice.range(), - )); + ); } } else if let Some(is_slice_type) = CheckableExprType::try_from(is_slice.as_ref()) { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( InvalidIndexType { value_type: value_type.to_string(), index_type: is_slice_type.to_string(), is_slice: true, }, is_slice.range(), - )); + ); } } } else { // If it's some other checkable data type, it's a violation - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( InvalidIndexType { value_type: value_type.to_string(), index_type: index_type.to_string(), is_slice: false, }, index.range(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/map_int_version_parsing.rs b/crates/ruff_linter/src/rules/ruff/rules/map_int_version_parsing.rs index 7fd0e9e69d..db20a797b2 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/map_int_version_parsing.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/map_int_version_parsing.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::SemanticModel; @@ -53,7 +53,7 @@ pub(crate) fn map_int_version_parsing(checker: &Checker, call: &ast::ExprCall) { }; if is_dunder_version_split_dot(second) && semantic.match_builtin_expr(first, "int") { - checker.report_diagnostic(Diagnostic::new(MapIntVersionParsing, call.range())); + checker.report_diagnostic(MapIntVersionParsing, call.range()); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/missing_fstring_syntax.rs b/crates/ruff_linter/src/rules/ruff/rules/missing_fstring_syntax.rs index 98f54229b1..5ef7320b06 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/missing_fstring_syntax.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/missing_fstring_syntax.rs @@ -1,7 +1,7 @@ use memchr::memchr2_iter; use rustc_hash::FxHashSet; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_literal::format::FormatSpec; @@ -116,9 +116,9 @@ pub(crate) fn missing_fstring_syntax(checker: &Checker, literal: &ast::StringLit } if should_be_fstring(literal, checker.locator(), semantic) { - let diagnostic = Diagnostic::new(MissingFStringSyntax, literal.range()) - .with_fix(fix_fstring_syntax(literal.range())); - checker.report_diagnostic(diagnostic); + checker + .report_diagnostic(MissingFStringSyntax, literal.range()) + .set_fix(fix_fstring_syntax(literal.range())); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/mutable_class_default.rs b/crates/ruff_linter/src/rules/ruff/rules/mutable_class_default.rs index d2350e5069..684933272f 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/mutable_class_default.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/mutable_class_default.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::typing::{is_immutable_annotation, is_mutable_expr}; use ruff_text_size::Ranged; @@ -118,7 +118,7 @@ pub(crate) fn mutable_class_default(checker: &Checker, class_def: &ast::StmtClas return; } - checker.report_diagnostic(Diagnostic::new(MutableClassDefault, value.range())); + checker.report_diagnostic(MutableClassDefault, value.range()); } } Stmt::Assign(ast::StmtAssign { value, targets, .. }) => { @@ -130,7 +130,7 @@ pub(crate) fn mutable_class_default(checker: &Checker, class_def: &ast::StmtClas return; } - checker.report_diagnostic(Diagnostic::new(MutableClassDefault, value.range())); + checker.report_diagnostic(MutableClassDefault, value.range()); } } _ => (), diff --git a/crates/ruff_linter/src/rules/ruff/rules/mutable_dataclass_default.rs b/crates/ruff_linter/src/rules/ruff/rules/mutable_dataclass_default.rs index 29676fc10f..3eb89e8568 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/mutable_dataclass_default.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/mutable_dataclass_default.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::typing::{is_immutable_annotation, is_mutable_expr}; use ruff_text_size::Ranged; @@ -86,9 +86,7 @@ pub(crate) fn mutable_dataclass_default(checker: &Checker, class_def: &ast::Stmt && !is_class_var_annotation(annotation, checker.semantic()) && !is_immutable_annotation(annotation, checker.semantic(), &[]) { - let diagnostic = Diagnostic::new(MutableDataclassDefault, value.range()); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(MutableDataclassDefault, value.range()); } } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/mutable_fromkeys_value.rs b/crates/ruff_linter/src/rules/ruff/rules/mutable_fromkeys_value.rs index bd39425a6b..0eabf475d4 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/mutable_fromkeys_value.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/mutable_fromkeys_value.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr}; @@ -87,12 +87,11 @@ pub(crate) fn mutable_fromkeys_value(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(MutableFromkeysValue, call.range()); + let mut diagnostic = checker.report_diagnostic(MutableFromkeysValue, call.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( generate_dict_comprehension(keys, value, checker.generator()), call.range(), ))); - checker.report_diagnostic(diagnostic); } /// Format a code snippet to expression `{key: value for key in keys}`, where diff --git a/crates/ruff_linter/src/rules/ruff/rules/needless_else.rs b/crates/ruff_linter/src/rules/ruff/rules/needless_else.rs index 7b0b71e04e..7d0ede8cbc 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/needless_else.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/needless_else.rs @@ -1,6 +1,6 @@ use std::cmp::Ordering; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::comment_indentation_after; use ruff_python_ast::whitespace::indentation; @@ -70,9 +70,9 @@ pub(crate) fn needless_else(checker: &Checker, stmt: AnyNodeWithOrElse) { let edit = Edit::range_deletion(remove_range); let fix = Fix::safe_edit(edit); - let diagnostic = Diagnostic::new(NeedlessElse, else_range); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(NeedlessElse, else_range) + .set_fix(fix); } /// Whether `body` contains only one `pass` or `...` statement. diff --git a/crates/ruff_linter/src/rules/ruff/rules/never_union.rs b/crates/ruff_linter/src/rules/ruff/rules/never_union.rs index 57cdcf0763..6257b91d82 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/never_union.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/never_union.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprBinOp, Operator}; use ruff_python_semantic::{SemanticModel, analyze::typing::traverse_union}; @@ -77,7 +77,7 @@ pub(crate) fn never_union(checker: &Checker, expr: &Expr) { }) => { // Analyze the left-hand side of the `|` operator. if let Some(never_like) = NeverLike::from_expr(left, checker.semantic()) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NeverUnion { never_like, union_like: UnionLike::PEP604, @@ -95,12 +95,11 @@ pub(crate) fn never_union(checker: &Checker, expr: &Expr) { expr.range(), ))); } - checker.report_diagnostic(diagnostic); } // Analyze the right-hand side of the `|` operator. if let Some(never_like) = NeverLike::from_expr(right, checker.semantic()) { - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NeverUnion { never_like, union_like: UnionLike::PEP604, @@ -113,7 +112,6 @@ pub(crate) fn never_union(checker: &Checker, expr: &Expr) { expr.range(), ))); } - checker.report_diagnostic(diagnostic); } } @@ -143,7 +141,7 @@ pub(crate) fn never_union(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( NeverUnion { never_like, union_like: UnionLike::TypingUnion, @@ -172,7 +170,6 @@ pub(crate) fn never_union(checker: &Checker, expr: &Expr) { }, expr.range(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/none_not_at_end_of_union.rs b/crates/ruff_linter/src/rules/ruff/rules/none_not_at_end_of_union.rs index 3645b3e574..f4fd20d008 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/none_not_at_end_of_union.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/none_not_at_end_of_union.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::analyze::typing::traverse_union; @@ -70,6 +70,6 @@ pub(crate) fn none_not_at_end_of_union<'a>(checker: &Checker, union: &'a Expr) { } for none_expr in none_exprs { - checker.report_diagnostic(Diagnostic::new(NoneNotAtEndOfUnion, none_expr.range())); + checker.report_diagnostic(NoneNotAtEndOfUnion, none_expr.range()); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/parenthesize_chained_operators.rs b/crates/ruff_linter/src/rules/ruff/rules/parenthesize_chained_operators.rs index cdcf523301..d1706e67d6 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/parenthesize_chained_operators.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/parenthesize_chained_operators.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::parenthesize::parenthesized_range; @@ -86,10 +86,9 @@ pub(crate) fn parenthesize_chained_logical_operators(checker: &Checker, expr: &a { let new_source = format!("({})", locator.slice(source_range)); let edit = Edit::range_replacement(new_source, source_range); - checker.report_diagnostic( - Diagnostic::new(ParenthesizeChainedOperators, source_range) - .with_fix(Fix::safe_edit(edit)), - ); + checker + .report_diagnostic(ParenthesizeChainedOperators, source_range) + .set_fix(Fix::safe_edit(edit)); } } _ => continue, diff --git a/crates/ruff_linter/src/rules/ruff/rules/post_init_default.rs b/crates/ruff_linter/src/rules/ruff/rules/post_init_default.rs index f189459e27..26bc325261 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/post_init_default.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/post_init_default.rs @@ -1,6 +1,6 @@ use anyhow::Context; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::{Scope, ScopeKind}; @@ -113,7 +113,7 @@ pub(crate) fn post_init_default(checker: &Checker, function_def: &ast::StmtFunct let Some(default) = parameter.default() else { continue; }; - let mut diagnostic = Diagnostic::new(PostInitDefault, default.range()); + let mut diagnostic = checker.report_diagnostic(PostInitDefault, default.range()); if !stopped_fixes { diagnostic.try_set_fix(|| { @@ -130,8 +130,6 @@ pub(crate) fn post_init_default(checker: &Checker, function_def: &ast::StmtFunct // following parameter with a default). stopped_fixes |= diagnostic.fix.is_none(); } - - checker.report_diagnostic(diagnostic); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/pytest_raises_ambiguous_pattern.rs b/crates/ruff_linter/src/rules/ruff/rules/pytest_raises_ambiguous_pattern.rs index 46b48a4ef2..3133536223 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/pytest_raises_ambiguous_pattern.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/pytest_raises_ambiguous_pattern.rs @@ -1,6 +1,6 @@ use crate::checkers::ast::Checker; use crate::rules::flake8_pytest_style::rules::is_pytest_raises; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; @@ -98,9 +98,7 @@ pub(crate) fn pytest_raises_ambiguous_pattern(checker: &Checker, call: &ast::Exp return; } - let diagnostic = Diagnostic::new(PytestRaisesAmbiguousPattern, string.range); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(PytestRaisesAmbiguousPattern, string.range); } fn string_has_unescaped_metacharacters(value: &ast::StringLiteralValue) -> bool { diff --git a/crates/ruff_linter/src/rules/ruff/rules/quadratic_list_summation.rs b/crates/ruff_linter/src/rules/ruff/rules/quadratic_list_summation.rs index 2a7e28c69a..eb290b9e53 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/quadratic_list_summation.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/quadratic_list_summation.rs @@ -1,7 +1,7 @@ use anyhow::Result; use itertools::Itertools; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{self as ast, Arguments, Expr}; @@ -95,9 +95,8 @@ pub(crate) fn quadratic_list_summation(checker: &Checker, call: &ast::ExprCall) return; } - let mut diagnostic = Diagnostic::new(QuadraticListSummation, *range); + let mut diagnostic = checker.report_diagnostic(QuadraticListSummation, *range); diagnostic.try_set_fix(|| convert_to_reduce(iterable, call, checker)); - checker.report_diagnostic(diagnostic); } /// Generate a [`Fix`] to convert a `sum()` call to a `functools.reduce()` call. diff --git a/crates/ruff_linter/src/rules/ruff/rules/redundant_bool_literal.rs b/crates/ruff_linter/src/rules/ruff/rules/redundant_bool_literal.rs index 0faa8bad9a..6aa037e4e8 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/redundant_bool_literal.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/redundant_bool_literal.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_semantic::analyze::typing::traverse_literal; @@ -111,7 +111,7 @@ pub(crate) fn redundant_bool_literal<'a>(checker: &Checker, literal_expr: &'a Ex let seen_others = seen_expr.contains(BooleanLiteral::OTHER); let mut diagnostic = - Diagnostic::new(RedundantBoolLiteral { seen_others }, literal_expr.range()); + checker.report_diagnostic(RedundantBoolLiteral { seen_others }, literal_expr.range()); // Provide a [`Fix`] when the complete `Literal` can be replaced. Applying the fix // can leave an unused import to be fixed by the `unused-import` rule. @@ -123,8 +123,6 @@ pub(crate) fn redundant_bool_literal<'a>(checker: &Checker, literal_expr: &'a Ex ))); } } - - checker.report_diagnostic(diagnostic); } bitflags! { diff --git a/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_all.rs b/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_all.rs index 6834e7643d..6107c3a117 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_all.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_all.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_source_file::LineRanges; @@ -199,15 +199,13 @@ fn sort_dunder_all(checker: &Checker, target: &ast::Expr, node: &ast::Expr) { return; } - let mut diagnostic = Diagnostic::new(UnsortedDunderAll, range); + let mut diagnostic = checker.report_diagnostic(UnsortedDunderAll, range); if let SortClassification::UnsortedAndMaybeFixable { items } = elts_analysis { if let Some(fix) = create_fix(range, elts, &items, kind, checker) { diagnostic.set_fix(fix); } } - - checker.report_diagnostic(diagnostic); } /// Attempt to return `Some(fix)`, where `fix` is a `Fix` diff --git a/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_slots.rs b/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_slots.rs index ec7157621e..d318569fdf 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_slots.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/sort_dunder_slots.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use itertools::izip; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Binding; @@ -110,38 +110,50 @@ const SORTING_STYLE: SortingStyle = SortingStyle::Natural; /// This routine checks whether the display is sorted, and emits a /// violation if it is not sorted. If the tuple/list/set was not sorted, /// it attempts to set a `Fix` on the violation. -pub(crate) fn sort_dunder_slots(checker: &Checker, binding: &Binding) -> Option { +pub(crate) fn sort_dunder_slots(checker: &Checker, binding: &Binding) { let semantic = checker.semantic(); - let (target, value) = match binding.statement(semantic)? { - ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => match targets.as_slice() { - [target] => (target, &**value), - _ => return None, - }, - ast::Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => { - (&**target, value.as_deref()?) - } - _ => return None, + let Some(stmt) = binding.statement(semantic) else { + return; }; - let ast::ExprName { id, .. } = target.as_name_expr()?; + let (target, value) = match stmt { + ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => match targets.as_slice() { + [target] => (target, &**value), + _ => return, + }, + ast::Stmt::AnnAssign(ast::StmtAnnAssign { + target, + value: Some(value), + .. + }) => (&**target, &**value), + _ => return, + }; + + let Some(ast::ExprName { id, .. }) = target.as_name_expr() else { + return; + }; if id != "__slots__" { - return None; + return; } // We're only interested in `__slots__` in the class scope - let enclosing_class = semantic.scopes[binding.scope].kind.as_class()?; + let Some(enclosing_class) = semantic.scopes[binding.scope].kind.as_class() else { + return; + }; // and it has to be an assignment to a "display literal" (a literal dict/set/tuple/list) - let display = StringLiteralDisplay::new(value)?; + let Some(display) = StringLiteralDisplay::new(value) else { + return; + }; let sort_classification = SortClassification::of_elements(&display.elts, SORTING_STYLE); if sort_classification.is_not_a_list_of_string_literals() || sort_classification.is_sorted() { - return None; + return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnsortedDunderSlots { class_name: enclosing_class.name.id.clone(), }, @@ -163,8 +175,6 @@ pub(crate) fn sort_dunder_slots(checker: &Checker, binding: &Binding) -> Option< diagnostic.set_fix(Fix::applicable_edit(edit, applicability)); } } - - Some(diagnostic) } /// Struct representing a [display](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries) diff --git a/crates/ruff_linter/src/rules/ruff/rules/starmap_zip.rs b/crates/ruff_linter/src/rules/ruff/rules/starmap_zip.rs index c20371284c..8e192ef2c3 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/starmap_zip.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/starmap_zip.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprCall, parenthesize::parenthesized_range}; use ruff_python_parser::TokenKind; @@ -89,13 +89,11 @@ pub(crate) fn starmap_zip(checker: &Checker, call: &ExprCall) { return; } - let mut diagnostic = Diagnostic::new(StarmapZip, call.range); + let mut diagnostic = checker.report_diagnostic(StarmapZip, call.range); if let Some(fix) = replace_with_map(call, iterable_call, checker) { diagnostic.set_fix(fix); } - - checker.report_diagnostic(diagnostic); } /// Replace the `starmap` call with a call to the `map` builtin, if `map` has not been shadowed. diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs index 4b97745a3a..872ecfbf35 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_cast_to_int.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_python_ast::{Arguments, Expr, ExprCall}; @@ -88,9 +88,9 @@ pub(crate) fn unnecessary_cast_to_int(checker: &Checker, call: &ExprCall) { checker.comment_ranges(), checker.source(), ); - let diagnostic = Diagnostic::new(UnnecessaryCastToInt, call.range()); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(UnnecessaryCastToInt, call.range()) + .set_fix(fix); } /// Creates a fix that replaces `int(expression)` with `expression`. diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_iterable_allocation_for_first_element.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_iterable_allocation_for_first_element.rs index f01e6aca11..8bc725f53e 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_iterable_allocation_for_first_element.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_iterable_allocation_for_first_element.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Comprehension, Expr, Int}; use ruff_python_semantic::SemanticModel; @@ -115,7 +115,7 @@ pub(crate) fn unnecessary_iterable_allocation_for_first_element(checker: &Checke Cow::Owned(format!("iter({iterable})")) }; - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryIterableAllocationForFirstElement { iterable: SourceCodeSnippet::new(iterable.to_string()), }, @@ -126,8 +126,6 @@ pub(crate) fn unnecessary_iterable_allocation_for_first_element(checker: &Checke format!("next({iterable})"), expr.range(), ))); - - checker.report_diagnostic(diagnostic); } /// Check that the slice [`Expr`] is a slice of the first element (e.g., `x[0]`). diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_key_check.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_key_check.rs index 34d1d9f9d0..c34d075b1a 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_key_check.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_key_check.rs @@ -1,7 +1,7 @@ use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::{self as ast, BoolOp, CmpOp, Expr}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::contains_effect; use ruff_python_ast::parenthesize::parenthesized_range; @@ -102,7 +102,7 @@ pub(crate) fn unnecessary_key_check(checker: &Checker, expr: &Expr) { return; } - let mut diagnostic = Diagnostic::new(UnnecessaryKeyCheck, expr.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryKeyCheck, expr.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( format!( "{}.get({})", @@ -127,5 +127,4 @@ pub(crate) fn unnecessary_key_check(checker: &Checker, expr: &Expr) { ), expr.range(), ))); - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_literal_within_deque_call.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_literal_within_deque_call.rs index eeef2580c6..869f23d4aa 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_literal_within_deque_call.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_literal_within_deque_call.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; @@ -91,7 +91,7 @@ pub(crate) fn unnecessary_literal_within_deque_call(checker: &Checker, deque: &a return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryEmptyIterableWithinDequeCall { has_maxlen: maxlen.is_some(), }, @@ -99,8 +99,6 @@ pub(crate) fn unnecessary_literal_within_deque_call(checker: &Checker, deque: &a ); diagnostic.set_fix(fix_unnecessary_literal_in_deque(checker, deque, maxlen)); - - checker.report_diagnostic(diagnostic); } fn fix_unnecessary_literal_in_deque( diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_nested_literal.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_nested_literal.rs index a40bb723cb..0595b1e0f7 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_nested_literal.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_nested_literal.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{AnyNodeRef, Expr, ExprContext, ExprSubscript, ExprTuple}; use ruff_python_semantic::analyze::typing::traverse_literal; @@ -105,7 +105,7 @@ pub(crate) fn unnecessary_nested_literal<'a>(checker: &Checker, literal_expr: &' literal_expr, ); - let mut diagnostic = Diagnostic::new(UnnecessaryNestedLiteral, literal_expr.range()); + let mut diagnostic = checker.report_diagnostic(UnnecessaryNestedLiteral, literal_expr.range()); // Create a [`Fix`] that flattens all nodes. if let Expr::Subscript(subscript) = literal_expr { @@ -134,6 +134,4 @@ pub(crate) fn unnecessary_nested_literal<'a>(checker: &Checker, literal_expr: &' ); diagnostic.set_fix(fix); } - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_regular_expression.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_regular_expression.rs index 2c9c7ed247..6200664b0a 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_regular_expression.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_regular_expression.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ Arguments, CmpOp, Expr, ExprAttribute, ExprCall, ExprCompare, ExprContext, ExprStringLiteral, @@ -116,7 +116,7 @@ pub(crate) fn unnecessary_regular_expression(checker: &Checker, call: &ExprCall) let new_expr = re_func.replacement(); let repl = new_expr.map(|expr| checker.generator().expr(&expr)); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnnecessaryRegularExpression { replacement: repl.clone(), }, @@ -133,8 +133,6 @@ pub(crate) fn unnecessary_regular_expression(checker: &Checker, call: &ExprCall) }, )); } - - checker.report_diagnostic(diagnostic); } /// The `re` functions supported by this rule. diff --git a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_round.rs b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_round.rs index 009d875ba1..070ebc4e40 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unnecessary_round.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unnecessary_round.rs @@ -1,6 +1,6 @@ use crate::Locator; use crate::checkers::ast::Checker; -use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Applicability, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Arguments, Expr, ExprCall, ExprNumberLiteral, Number}; use ruff_python_semantic::SemanticModel; @@ -100,9 +100,9 @@ pub(crate) fn unnecessary_round(checker: &Checker, call: &ExprCall) { let edit = unwrap_round_call(call, rounded, checker.semantic(), checker.locator()); let fix = Fix::applicable_edit(edit, applicability); - let diagnostic = Diagnostic::new(UnnecessaryRound, call.range()); - - checker.report_diagnostic(diagnostic.with_fix(fix)); + checker + .report_diagnostic(UnnecessaryRound, call.range()) + .set_fix(fix); } #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/crates/ruff_linter/src/rules/ruff/rules/unraw_re_pattern.rs b/crates/ruff_linter/src/rules/ruff/rules/unraw_re_pattern.rs index 18135f9bb9..9119be93b2 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unraw_re_pattern.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unraw_re_pattern.rs @@ -1,7 +1,7 @@ use std::fmt::{Display, Formatter}; use std::str::FromStr; -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ BytesLiteral, Expr, ExprBytesLiteral, ExprCall, ExprStringLiteral, StringLiteral, @@ -161,7 +161,7 @@ fn check_string(checker: &Checker, literal: &StringLiteral, module: RegexModule, let kind = PatternKind::String; let func = func.to_string(); let range = literal.range; - let mut diagnostic = Diagnostic::new(UnrawRePattern { module, func, kind }, range); + let mut diagnostic = checker.report_diagnostic(UnrawRePattern { module, func, kind }, range); if // The (no-op) `u` prefix is a syntax error when combined with `r` @@ -177,7 +177,6 @@ fn check_string(checker: &Checker, literal: &StringLiteral, module: RegexModule, literal.range().start(), ))); } - checker.report_diagnostic(diagnostic); } fn check_bytes(checker: &Checker, literal: &BytesLiteral, module: RegexModule, func: &str) { @@ -188,7 +187,5 @@ fn check_bytes(checker: &Checker, literal: &BytesLiteral, module: RegexModule, f let kind = PatternKind::Bytes; let func = func.to_string(); let range = literal.range; - let diagnostic = Diagnostic::new(UnrawRePattern { module, func, kind }, range); - - checker.report_diagnostic(diagnostic); + checker.report_diagnostic(UnrawRePattern { module, func, kind }, range); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/unused_async.rs b/crates/ruff_linter/src/rules/ruff/rules/unused_async.rs index 6bc529ec55..f9f7b32c9b 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unused_async.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unused_async.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::source_order; @@ -188,11 +188,11 @@ pub(crate) fn unused_async( }; if !found_await_or_async { - checker.report_diagnostic(Diagnostic::new( + checker.report_diagnostic( UnusedAsync { name: name.to_string(), }, function_def.identifier(), - )); + ); } } diff --git a/crates/ruff_linter/src/rules/ruff/rules/unused_unpacked_variable.rs b/crates/ruff_linter/src/rules/ruff/rules/unused_unpacked_variable.rs index 02defb9326..bf4997abca 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/unused_unpacked_variable.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/unused_unpacked_variable.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Binding; use ruff_text_size::Ranged; @@ -78,7 +78,7 @@ pub(crate) fn unused_unpacked_variable(checker: &Checker, name: &str, binding: & return; } - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UnusedUnpackedVariable { name: name.to_string(), }, @@ -87,5 +87,4 @@ pub(crate) fn unused_unpacked_variable(checker: &Checker, name: &str, binding: & if let Some(fix) = remove_unused_variable(binding, checker) { diagnostic.set_fix(fix); } - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/used_dummy_variable.rs b/crates/ruff_linter/src/rules/ruff/rules/used_dummy_variable.rs index a6737dff85..facb461624 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/used_dummy_variable.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/used_dummy_variable.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_dunder; use ruff_python_semantic::{Binding, BindingId}; @@ -98,20 +98,16 @@ impl Violation for UsedDummyVariable { } /// RUF052 -pub(crate) fn used_dummy_variable( - checker: &Checker, - binding: &Binding, - binding_id: BindingId, -) -> Option { +pub(crate) fn used_dummy_variable(checker: &Checker, binding: &Binding, binding_id: BindingId) { let name = binding.name(checker.source()); // Ignore `_` and dunder variables if name == "_" || is_dunder(name) { - return None; + return; } // only used variables if binding.is_unused() { - return None; + return; } // We only emit the lint on variables defined via assignments. @@ -131,12 +127,12 @@ pub(crate) fn used_dummy_variable( // - // - if !binding.kind.is_assignment() { - return None; + return; } // This excludes `global` and `nonlocal` variables. if binding.is_global() || binding.is_nonlocal() { - return None; + return; } let semantic = checker.semantic(); @@ -144,7 +140,7 @@ pub(crate) fn used_dummy_variable( // Only variables defined in function scopes let scope = &semantic.scopes[binding.scope]; if !scope.kind.is_function() { - return None; + return; } // Recall from above that we do not wish to flag "private" @@ -159,21 +155,22 @@ pub(crate) fn used_dummy_variable( .shadowed_bindings(binding_id) .any(|shadow_id| semantic.binding(shadow_id).kind.is_argument()) { - return None; + return; } if !checker.settings.dummy_variable_rgx.is_match(name) { - return None; + return; } // If the name doesn't start with an underscore, we don't consider it for a fix if !name.starts_with('_') { - return Some(Diagnostic::new( + checker.report_diagnostic( UsedDummyVariable { name: name.to_string(), shadowed_kind: None, }, binding.range(), - )); + ); + return; } // Trim the leading underscores for further checks @@ -181,7 +178,7 @@ pub(crate) fn used_dummy_variable( let shadowed_kind = ShadowedKind::new(binding, trimmed_name, checker); - let mut diagnostic = Diagnostic::new( + let mut diagnostic = checker.report_diagnostic( UsedDummyVariable { name: name.to_string(), shadowed_kind: Some(shadowed_kind), @@ -196,8 +193,6 @@ pub(crate) fn used_dummy_variable( .map(|(edit, rest)| Fix::unsafe_edits(edit, rest)) }); } - - Some(diagnostic) } /// Suggests a potential alternative name to resolve a shadowing conflict. diff --git a/crates/ruff_linter/src/rules/ruff/rules/useless_if_else.rs b/crates/ruff_linter/src/rules/ruff/rules/useless_if_else.rs index d1f59ca8d2..1076ec0edf 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/useless_if_else.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/useless_if_else.rs @@ -1,5 +1,5 @@ use crate::checkers::ast::Checker; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::comparable::ComparableExpr; @@ -44,5 +44,5 @@ pub(crate) fn useless_if_else(checker: &Checker, if_expr: &ast::ExprIf) { return; } - checker.report_diagnostic(Diagnostic::new(UselessIfElse, *range)); + checker.report_diagnostic(UselessIfElse, *range); } diff --git a/crates/ruff_linter/src/rules/ruff/rules/zip_instead_of_pairwise.rs b/crates/ruff_linter/src/rules/ruff/rules/zip_instead_of_pairwise.rs index d4bcd9844d..7e055c204e 100644 --- a/crates/ruff_linter/src/rules/ruff/rules/zip_instead_of_pairwise.rs +++ b/crates/ruff_linter/src/rules/ruff/rules/zip_instead_of_pairwise.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr, Int}; use ruff_text_size::Ranged; @@ -160,7 +160,7 @@ pub(crate) fn zip_instead_of_pairwise(checker: &Checker, call: &ast::ExprCall) { return; } - let mut diagnostic = Diagnostic::new(ZipInsteadOfPairwise, func.range()); + let mut diagnostic = checker.report_diagnostic(ZipInsteadOfPairwise, func.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( @@ -172,6 +172,4 @@ pub(crate) fn zip_instead_of_pairwise(checker: &Checker, call: &ast::ExprCall) { Edit::range_replacement(format!("{binding}({})", first_arg_info.id), call.range()); Ok(Fix::unsafe_edits(import_edit, [reference_edit])) }); - - checker.report_diagnostic(diagnostic); } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/error_instead_of_exception.rs b/crates/ruff_linter/src/rules/tryceratops/rules/error_instead_of_exception.rs index dadbaa807c..e8a1c7b66c 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/error_instead_of_exception.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/error_instead_of_exception.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Applicability, Diagnostic, Edit, Fix, FixAvailability, Violation}; +use ruff_diagnostics::{Applicability, Edit, Fix, FixAvailability, Violation}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, ExceptHandler, Expr}; @@ -80,7 +80,8 @@ pub(crate) fn error_instead_of_exception(checker: &Checker, handlers: &[ExceptHa for (expr, logging_level) in calls { if matches!(logging_level, LoggingLevel::Error) { if exc_info(&expr.arguments, checker.semantic()).is_none() { - let mut diagnostic = Diagnostic::new(ErrorInsteadOfException, expr.range()); + let mut diagnostic = + checker.report_diagnostic(ErrorInsteadOfException, expr.range()); match expr.func.as_ref() { Expr::Attribute(ast::ExprAttribute { attr, .. }) => { @@ -134,8 +135,6 @@ pub(crate) fn error_instead_of_exception(checker: &Checker, handlers: &[ExceptHa } _ => {} } - - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_args.rs b/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_args.rs index 05cb8020b4..3d5737c7dc 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_args.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_args.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr}; use ruff_text_size::Ranged; @@ -78,7 +78,7 @@ pub(crate) fn raise_vanilla_args(checker: &Checker, expr: &Expr) { } if contains_message(arg) { - checker.report_diagnostic(Diagnostic::new(RaiseVanillaArgs, expr.range())); + checker.report_diagnostic(RaiseVanillaArgs, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_class.rs b/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_class.rs index 5f189ab4a3..ff393ad010 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_class.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/raise_vanilla_class.rs @@ -1,7 +1,7 @@ use ruff_python_ast::Expr; use ruff_python_ast::helpers::map_callable; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -74,6 +74,6 @@ pub(crate) fn raise_vanilla_class(checker: &Checker, expr: &Expr) { ) }) { - checker.report_diagnostic(Diagnostic::new(RaiseVanillaClass, expr.range())); + checker.report_diagnostic(RaiseVanillaClass, expr.range()); } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/raise_within_try.rs b/crates/ruff_linter/src/rules/tryceratops/rules/raise_within_try.rs index 6ac0172744..80035ee847 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/raise_within_try.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/raise_within_try.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ comparable::ComparableExpr, @@ -115,7 +115,7 @@ pub(crate) fn raise_within_try(checker: &Checker, body: &[Stmt], handlers: &[Exc .is_some_and(|builtin| matches!(builtin, "Exception" | "BaseException")) }) { - checker.report_diagnostic(Diagnostic::new(RaiseWithinTry, stmt.range())); + checker.report_diagnostic(RaiseWithinTry, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs b/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs index 87839a4e72..38ca82348c 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::contains_effect; use ruff_text_size::Ranged; @@ -73,7 +73,7 @@ pub(crate) fn try_consider_else( return; } } - checker.report_diagnostic(Diagnostic::new(TryConsiderElse, stmt.range())); + checker.report_diagnostic(TryConsiderElse, stmt.range()); } } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/type_check_without_type_error.rs b/crates/ruff_linter/src/rules/tryceratops/rules/type_check_without_type_error.rs index c84f2238fd..6414dc6cdc 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/type_check_without_type_error.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/type_check_without_type_error.rs @@ -1,4 +1,4 @@ -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; @@ -94,7 +94,7 @@ fn check_type_check_test(semantic: &SemanticModel, test: &Expr) -> bool { fn check_raise(checker: &Checker, exc: &Expr, item: &Stmt) { if is_builtin_exception(exc, checker.semantic()) { - checker.report_diagnostic(Diagnostic::new(TypeCheckWithoutTypeError, item.range())); + checker.report_diagnostic(TypeCheckWithoutTypeError, item.range()); } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/useless_try_except.rs b/crates/ruff_linter/src/rules/tryceratops/rules/useless_try_except.rs index 199685480e..b65c0dd246 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/useless_try_except.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/useless_try_except.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, ExceptHandlerExceptHandler, Expr, Stmt}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; @@ -63,7 +63,7 @@ pub(crate) fn useless_try_except(checker: &Checker, handlers: &[ExceptHandler]) }) { // Require that all handlers are useless, but create one diagnostic per handler. for handler in handlers { - checker.report_diagnostic(Diagnostic::new(UselessTryExcept, handler.range())); + checker.report_diagnostic(UselessTryExcept, handler.range()); } } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/verbose_log_message.rs b/crates/ruff_linter/src/rules/tryceratops/rules/verbose_log_message.rs index 252d3c5562..f83046c629 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/verbose_log_message.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/verbose_log_message.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, Expr}; -use ruff_diagnostics::{Diagnostic, Violation}; +use ruff_diagnostics::Violation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor; use ruff_python_ast::visitor::Visitor; @@ -78,7 +78,7 @@ pub(crate) fn verbose_log_message(checker: &Checker, handlers: &[ExceptHandler]) }; let binding = checker.semantic().binding(id); if binding.kind.is_bound_exception() { - checker.report_diagnostic(Diagnostic::new(VerboseLogMessage, expr.range())); + checker.report_diagnostic(VerboseLogMessage, expr.range()); } } } diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/verbose_raise.rs b/crates/ruff_linter/src/rules/tryceratops/rules/verbose_raise.rs index 008748680f..2d95dded60 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/verbose_raise.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/verbose_raise.rs @@ -1,6 +1,6 @@ use ruff_python_ast::{self as ast, ExceptHandler, Expr, Stmt}; -use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; +use ruff_diagnostics::{AlwaysFixableViolation, Edit, Fix}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; use ruff_text_size::Ranged; @@ -72,12 +72,12 @@ pub(crate) fn verbose_raise(checker: &Checker, handlers: &[ExceptHandler]) { // ...and the raised object is bound to the same name... if let Expr::Name(ast::ExprName { id, .. }) = exc.as_ref() { if id == exception_name.as_str() { - let mut diagnostic = Diagnostic::new(VerboseRaise, exc.range()); + let mut diagnostic = + checker.report_diagnostic(VerboseRaise, exc.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( "raise".to_string(), raise.range(), ))); - checker.report_diagnostic(diagnostic); } } } diff --git a/crates/ruff_macros/src/violation_metadata.rs b/crates/ruff_macros/src/violation_metadata.rs index 3cf60307ab..bc8789d818 100644 --- a/crates/ruff_macros/src/violation_metadata.rs +++ b/crates/ruff_macros/src/violation_metadata.rs @@ -7,10 +7,12 @@ pub(crate) fn violation_metadata(input: DeriveInput) -> syn::Result let name = input.ident; + let (impl_generics, ty_generics, where_clause) = &input.generics.split_for_impl(); + Ok(quote! { #[automatically_derived] #[expect(deprecated)] - impl ruff_diagnostics::ViolationMetadata for #name { + impl #impl_generics ruff_diagnostics::ViolationMetadata for #name #ty_generics #where_clause { fn rule_name() -> &'static str { ::ruff_macros::kebab_case!(#name) }