Rename more local usages of `check` to `diagnostic` (#1738)

This commit is contained in:
Charlie Marsh 2023-01-08 18:10:08 -05:00 committed by GitHub
parent 2c537e24cc
commit 161ab05533
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
78 changed files with 660 additions and 634 deletions

View File

@ -30,15 +30,15 @@ impl From<bool> for Mode {
/// Auto-fix errors in a file, and write the fixed source code to disk. /// Auto-fix errors in a file, and write the fixed source code to disk.
pub fn fix_file<'a>( pub fn fix_file<'a>(
checks: &'a [Diagnostic], diagnostics: &'a [Diagnostic],
locator: &'a SourceCodeLocator<'a>, locator: &'a SourceCodeLocator<'a>,
) -> Option<(Cow<'a, str>, usize)> { ) -> Option<(Cow<'a, str>, usize)> {
if checks.iter().all(|check| check.fix.is_none()) { if diagnostics.iter().all(|check| check.fix.is_none()) {
return None; return None;
} }
Some(apply_fixes( Some(apply_fixes(
checks.iter().filter_map(|check| check.fix.as_ref()), diagnostics.iter().filter_map(|check| check.fix.as_ref()),
locator, locator,
)) ))
} }

View File

@ -4073,16 +4073,16 @@ impl<'a> Checker<'a> {
let defined_in = self.child_to_parent.get(defined_by); let defined_in = self.child_to_parent.get(defined_by);
let child: &Stmt = defined_by.into(); let child: &Stmt = defined_by.into();
let check_lineno = binding.range.location.row(); let diagnostic_lineno = binding.range.location.row();
let parent_lineno = if matches!(child.node, StmtKind::ImportFrom { .. }) let parent_lineno = if matches!(child.node, StmtKind::ImportFrom { .. })
&& child.location.row() != check_lineno && child.location.row() != diagnostic_lineno
{ {
Some(child.location.row()) Some(child.location.row())
} else { } else {
None None
}; };
if self.is_ignored(&RuleCode::F401, check_lineno) if self.is_ignored(&RuleCode::F401, diagnostic_lineno)
|| parent_lineno.map_or(false, |parent_lineno| { || parent_lineno.map_or(false, |parent_lineno| {
self.is_ignored(&RuleCode::F401, parent_lineno) self.is_ignored(&RuleCode::F401, parent_lineno)
}) })

View File

@ -12,7 +12,7 @@ pub fn check_lines(
settings: &Settings, settings: &Settings,
autofix: flags::Autofix, autofix: flags::Autofix,
) -> Vec<Diagnostic> { ) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
let enforce_unnecessary_coding_comment = settings.enabled.contains(&RuleCode::UP009); let enforce_unnecessary_coding_comment = settings.enabled.contains(&RuleCode::UP009);
let enforce_line_too_long = settings.enabled.contains(&RuleCode::E501); let enforce_line_too_long = settings.enabled.contains(&RuleCode::E501);
@ -28,52 +28,52 @@ pub fn check_lines(
{ {
if enforce_unnecessary_coding_comment { if enforce_unnecessary_coding_comment {
if index < 2 { if index < 2 {
if let Some(check) = unnecessary_coding_comment( if let Some(diagnostic) = unnecessary_coding_comment(
index, index,
line, line,
matches!(autofix, flags::Autofix::Enabled) matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&RuleCode::UP009), && settings.fixable.contains(&RuleCode::UP009),
) { ) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
if enforce_blanket_type_ignore { if enforce_blanket_type_ignore {
if commented_lines.contains(&(index + 1)) { if commented_lines.contains(&(index + 1)) {
if let Some(check) = blanket_type_ignore(index, line) { if let Some(diagnostic) = blanket_type_ignore(index, line) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
if enforce_blanket_noqa { if enforce_blanket_noqa {
if commented_lines.contains(&(index + 1)) { if commented_lines.contains(&(index + 1)) {
if let Some(check) = blanket_noqa(index, line) { if let Some(diagnostic) = blanket_noqa(index, line) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
} }
if enforce_line_too_long { if enforce_line_too_long {
if let Some(check) = line_too_long(index, line, settings) { if let Some(diagnostic) = line_too_long(index, line, settings) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
if enforce_no_newline_at_end_of_file { if enforce_no_newline_at_end_of_file {
if let Some(check) = no_newline_at_end_of_file( if let Some(diagnostic) = no_newline_at_end_of_file(
contents, contents,
matches!(autofix, flags::Autofix::Enabled) matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&RuleCode::W292), && settings.fixable.contains(&RuleCode::W292),
) { ) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
checks diagnostics
} }
#[cfg(test)] #[cfg(test)]

View File

@ -14,7 +14,7 @@ use crate::violations::UnusedCodes;
use crate::{noqa, violations}; use crate::{noqa, violations};
pub fn check_noqa( pub fn check_noqa(
checks: &mut Vec<Diagnostic>, diagnostics: &mut Vec<Diagnostic>,
contents: &str, contents: &str,
commented_lines: &[usize], commented_lines: &[usize],
noqa_line_for: &IntMap<usize, usize>, noqa_line_for: &IntMap<usize, usize>,
@ -30,7 +30,7 @@ pub fn check_noqa(
for lineno in commented_lines { for lineno in commented_lines {
// If we hit an exemption for the entire file, bail. // If we hit an exemption for the entire file, bail.
if is_file_exempt(lines[lineno - 1]) { if is_file_exempt(lines[lineno - 1]) {
checks.drain(..); diagnostics.drain(..);
return; return;
} }
@ -41,14 +41,14 @@ pub fn check_noqa(
} }
} }
// Remove any ignored checks. // Remove any ignored diagnostics.
for (index, check) in checks.iter().enumerate() { for (index, diagnostic) in diagnostics.iter().enumerate() {
if matches!(check.kind, DiagnosticKind::BlanketNOQA(..)) { if matches!(diagnostic.kind, DiagnosticKind::BlanketNOQA(..)) {
continue; continue;
} }
// Is the check ignored by a `noqa` directive on the parent line? // Is the check ignored by a `noqa` directive on the parent line?
if let Some(parent_lineno) = check.parent.map(|location| location.row()) { if let Some(parent_lineno) = diagnostic.parent.map(|location| location.row()) {
let noqa_lineno = noqa_line_for.get(&parent_lineno).unwrap_or(&parent_lineno); let noqa_lineno = noqa_line_for.get(&parent_lineno).unwrap_or(&parent_lineno);
if commented_lines.contains(noqa_lineno) { if commented_lines.contains(noqa_lineno) {
let noqa = noqa_directives.entry(noqa_lineno - 1).or_insert_with(|| { let noqa = noqa_directives.entry(noqa_lineno - 1).or_insert_with(|| {
@ -56,13 +56,13 @@ pub fn check_noqa(
}); });
match noqa { match noqa {
(Directive::All(..), matches) => { (Directive::All(..), matches) => {
matches.push(check.kind.code().as_ref()); matches.push(diagnostic.kind.code().as_ref());
ignored.push(index); ignored.push(index);
continue; continue;
} }
(Directive::Codes(.., codes), matches) => { (Directive::Codes(.., codes), matches) => {
if noqa::includes(check.kind.code(), codes) { if noqa::includes(diagnostic.kind.code(), codes) {
matches.push(check.kind.code().as_ref()); matches.push(diagnostic.kind.code().as_ref());
ignored.push(index); ignored.push(index);
continue; continue;
} }
@ -72,21 +72,23 @@ pub fn check_noqa(
} }
} }
// Is the check ignored by a `noqa` directive on the same line? // Is the diagnostic ignored by a `noqa` directive on the same line?
let check_lineno = check.location.row(); let diagnostic_lineno = diagnostic.location.row();
let noqa_lineno = noqa_line_for.get(&check_lineno).unwrap_or(&check_lineno); let noqa_lineno = noqa_line_for
.get(&diagnostic_lineno)
.unwrap_or(&diagnostic_lineno);
if commented_lines.contains(noqa_lineno) { if commented_lines.contains(noqa_lineno) {
let noqa = noqa_directives let noqa = noqa_directives
.entry(noqa_lineno - 1) .entry(noqa_lineno - 1)
.or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno - 1]), vec![])); .or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno - 1]), vec![]));
match noqa { match noqa {
(Directive::All(..), matches) => { (Directive::All(..), matches) => {
matches.push(check.kind.code().as_ref()); matches.push(diagnostic.kind.code().as_ref());
ignored.push(index); ignored.push(index);
} }
(Directive::Codes(.., codes), matches) => { (Directive::Codes(.., codes), matches) => {
if noqa::includes(check.kind.code(), codes) { if noqa::includes(diagnostic.kind.code(), codes) {
matches.push(check.kind.code().as_ref()); matches.push(diagnostic.kind.code().as_ref());
ignored.push(index); ignored.push(index);
} }
} }
@ -101,19 +103,19 @@ pub fn check_noqa(
match directive { match directive {
Directive::All(spaces, start, end) => { Directive::All(spaces, start, end) => {
if matches.is_empty() { if matches.is_empty() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnusedNOQA(None), violations::UnusedNOQA(None),
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)), Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
); );
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code()) && settings.fixable.contains(diagnostic.kind.code())
{ {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(row + 1, start - spaces), Location::new(row + 1, start - spaces),
Location::new(row + 1, lines[row].chars().count()), Location::new(row + 1, lines[row].chars().count()),
)); ));
} }
checks.push(check); diagnostics.push(diagnostic);
} }
} }
Directive::Codes(spaces, start, end, codes) => { Directive::Codes(spaces, start, end, codes) => {
@ -152,7 +154,7 @@ pub fn check_noqa(
&& unknown_codes.is_empty() && unknown_codes.is_empty()
&& unmatched_codes.is_empty()) && unmatched_codes.is_empty())
{ {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnusedNOQA(Some(UnusedCodes { violations::UnusedNOQA(Some(UnusedCodes {
disabled: disabled_codes disabled: disabled_codes
.iter() .iter()
@ -170,22 +172,22 @@ pub fn check_noqa(
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)), Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
); );
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code()) && settings.fixable.contains(diagnostic.kind.code())
{ {
if valid_codes.is_empty() { if valid_codes.is_empty() {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(row + 1, start - spaces), Location::new(row + 1, start - spaces),
Location::new(row + 1, lines[row].chars().count()), Location::new(row + 1, lines[row].chars().count()),
)); ));
} else { } else {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("# noqa: {}", valid_codes.join(", ")), format!("# noqa: {}", valid_codes.join(", ")),
Location::new(row + 1, start), Location::new(row + 1, start),
Location::new(row + 1, lines[row].chars().count()), Location::new(row + 1, lines[row].chars().count()),
)); ));
} }
} }
checks.push(check); diagnostics.push(diagnostic);
} }
} }
Directive::None => {} Directive::None => {}
@ -195,6 +197,6 @@ pub fn check_noqa(
ignored.sort_unstable(); ignored.sort_unstable();
for index in ignored.iter().rev() { for index in ignored.iter().rev() {
checks.swap_remove(*index); diagnostics.swap_remove(*index);
} }
} }

View File

@ -15,7 +15,7 @@ pub fn check_tokens(
settings: &Settings, settings: &Settings,
autofix: flags::Autofix, autofix: flags::Autofix,
) -> Vec<Diagnostic> { ) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
let enforce_ambiguous_unicode_character = settings.enabled.contains(&RuleCode::RUF001) let enforce_ambiguous_unicode_character = settings.enabled.contains(&RuleCode::RUF001)
|| settings.enabled.contains(&RuleCode::RUF002) || settings.enabled.contains(&RuleCode::RUF002)
@ -40,7 +40,7 @@ pub fn check_tokens(
// RUF001, RUF002, RUF003 // RUF001, RUF002, RUF003
if enforce_ambiguous_unicode_character { if enforce_ambiguous_unicode_character {
if matches!(tok, Tok::String { .. } | Tok::Comment(_)) { if matches!(tok, Tok::String { .. } | Tok::Comment(_)) {
checks.extend(ruff::checks::ambiguous_unicode_character( diagnostics.extend(ruff::checks::ambiguous_unicode_character(
locator, locator,
start, start,
end, end,
@ -62,15 +62,15 @@ pub fn check_tokens(
// flake8-quotes // flake8-quotes
if enforce_quotes { if enforce_quotes {
if matches!(tok, Tok::String { .. }) { if matches!(tok, Tok::String { .. }) {
if let Some(check) = flake8_quotes::checks::quotes( if let Some(diagnostic) = flake8_quotes::checks::quotes(
locator, locator,
start, start,
end, end,
is_docstring, is_docstring,
&settings.flake8_quotes, &settings.flake8_quotes,
) { ) {
if settings.enabled.contains(check.kind.code()) { if settings.enabled.contains(diagnostic.kind.code()) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
@ -79,10 +79,10 @@ pub fn check_tokens(
// eradicate // eradicate
if enforce_commented_out_code { if enforce_commented_out_code {
if matches!(tok, Tok::Comment(_)) { if matches!(tok, Tok::Comment(_)) {
if let Some(check) = if let Some(diagnostic) =
eradicate::checks::commented_out_code(locator, start, end, settings, autofix) eradicate::checks::commented_out_code(locator, start, end, settings, autofix)
{ {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
@ -90,7 +90,7 @@ pub fn check_tokens(
// W605 // W605
if enforce_invalid_escape_sequence { if enforce_invalid_escape_sequence {
if matches!(tok, Tok::String { .. }) { if matches!(tok, Tok::String { .. }) {
checks.extend(pycodestyle::checks::invalid_escape_sequence( diagnostics.extend(pycodestyle::checks::invalid_escape_sequence(
locator, locator,
start, start,
end, end,
@ -103,12 +103,12 @@ pub fn check_tokens(
// ISC001, ISC002 // ISC001, ISC002
if enforce_implicit_string_concatenation { if enforce_implicit_string_concatenation {
checks.extend( diagnostics.extend(
flake8_implicit_str_concat::checks::implicit(tokens, locator) flake8_implicit_str_concat::checks::implicit(tokens, locator)
.into_iter() .into_iter()
.filter(|check| settings.enabled.contains(check.kind.code())), .filter(|diagnostic| settings.enabled.contains(diagnostic.kind.code())),
); );
} }
checks diagnostics
} }

View File

@ -32,13 +32,13 @@ pub fn commented_out_code(
// Verify that the comment is on its own line, and that it contains code. // Verify that the comment is on its own line, and that it contains code.
if is_standalone_comment(&line) && comment_contains_code(&line, &settings.task_tags[..]) { if is_standalone_comment(&line) && comment_contains_code(&line, &settings.task_tags[..]) {
let mut check = Diagnostic::new(violations::CommentedOutCode, Range::new(start, end)); let mut diagnostic = Diagnostic::new(violations::CommentedOutCode, Range::new(start, end));
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(&RuleCode::ERA001) && settings.fixable.contains(&RuleCode::ERA001)
{ {
check.amend(Fix::deletion(location, end_location)); diagnostic.amend(Fix::deletion(location, end_location));
} }
Some(check) Some(diagnostic)
} else { } else {
None None
} }

View File

@ -326,19 +326,19 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
if !(checker.settings.flake8_annotations.mypy_init_return if !(checker.settings.flake8_annotations.mypy_init_return
&& has_any_typed_arg) && has_any_typed_arg)
{ {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::MissingReturnTypeSpecialMethod(name.to_string()), violations::MissingReturnTypeSpecialMethod(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
match fixes::add_return_none_annotation(checker.locator, stmt) { match fixes::add_return_none_annotation(checker.locator, stmt) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} else if visibility::is_magic(stmt) { } else if visibility::is_magic(stmt) {

View File

@ -19,7 +19,7 @@ fn check_password_kwarg(arg: &Located<ArgData>, default: &Expr) -> Option<Diagno
/// S107 /// S107
pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Diagnostic> { pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = Vec::new(); let mut diagnostics: Vec<Diagnostic> = Vec::new();
let defaults_start = let defaults_start =
arguments.posonlyargs.len() + arguments.args.len() - arguments.defaults.len(); arguments.posonlyargs.len() + arguments.args.len() - arguments.defaults.len();
@ -31,8 +31,8 @@ pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Diagnostic> {
{ {
if let Some(i) = i.checked_sub(defaults_start) { if let Some(i) = i.checked_sub(defaults_start) {
let default = &arguments.defaults[i]; let default = &arguments.defaults[i];
if let Some(check) = check_password_kwarg(arg, default) { if let Some(diagnostic) = check_password_kwarg(arg, default) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
@ -41,11 +41,11 @@ pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Diagnostic> {
for (i, kwarg) in arguments.kwonlyargs.iter().enumerate() { for (i, kwarg) in arguments.kwonlyargs.iter().enumerate() {
if let Some(i) = i.checked_sub(defaults_start) { if let Some(i) = i.checked_sub(defaults_start) {
let default = &arguments.kw_defaults[i]; let default = &arguments.kw_defaults[i];
if let Some(check) = check_password_kwarg(kwarg, default) { if let Some(diagnostic) = check_password_kwarg(kwarg, default) {
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
checks diagnostics
} }

View File

@ -46,15 +46,15 @@ pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option
return; return;
}; };
let mut check = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test)); let mut diagnostic = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test));
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_stmt(&assertion_error(msg)); generator.unparse_stmt(&assertion_error(msg));
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -44,7 +44,7 @@ fn duplicate_handler_exceptions<'a>(
if checker.settings.enabled.contains(&RuleCode::B014) { if checker.settings.enabled.contains(&RuleCode::B014) {
// TODO(charlie): Handle "BaseException" and redundant exception aliases. // TODO(charlie): Handle "BaseException" and redundant exception aliases.
if !duplicates.is_empty() { if !duplicates.is_empty() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DuplicateHandlerException( violations::DuplicateHandlerException(
duplicates duplicates
.into_iter() .into_iter()
@ -54,20 +54,20 @@ fn duplicate_handler_exceptions<'a>(
), ),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
if unique_elts.len() == 1 { if unique_elts.len() == 1 {
generator.unparse_expr(unique_elts[0], 0); generator.unparse_expr(unique_elts[0], 0);
} else { } else {
generator.unparse_expr(&type_pattern(unique_elts), 0); generator.unparse_expr(&type_pattern(unique_elts), 0);
} }
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -36,7 +36,7 @@ fn is_immutable_func(
} }
struct ArgumentDefaultVisitor<'a> { struct ArgumentDefaultVisitor<'a> {
checks: Vec<(DiagnosticKind, Range)>, diagnostics: Vec<(DiagnosticKind, Range)>,
extend_immutable_calls: &'a [(&'a str, &'a str)], extend_immutable_calls: &'a [(&'a str, &'a str)],
from_imports: &'a FxHashMap<&'a str, FxHashSet<&'a str>>, from_imports: &'a FxHashMap<&'a str, FxHashSet<&'a str>>,
import_aliases: &'a FxHashMap<&'a str, &'a str>, import_aliases: &'a FxHashMap<&'a str, &'a str>,
@ -58,7 +58,7 @@ where
) )
&& !is_nan_or_infinity(func, args) && !is_nan_or_infinity(func, args)
{ {
self.checks.push(( self.diagnostics.push((
violations::FunctionCallArgumentDefault(compose_call_path(expr)).into(), violations::FunctionCallArgumentDefault(compose_call_path(expr)).into(),
Range::from_located(expr), Range::from_located(expr),
)); ));
@ -105,7 +105,7 @@ pub fn function_call_argument_default(checker: &mut Checker, arguments: &Argumen
.map(|target| to_module_and_member(target)) .map(|target| to_module_and_member(target))
.collect(); .collect();
let mut visitor = ArgumentDefaultVisitor { let mut visitor = ArgumentDefaultVisitor {
checks: vec![], diagnostics: vec![],
extend_immutable_calls: &extend_immutable_cells, extend_immutable_calls: &extend_immutable_cells,
from_imports: &checker.from_imports, from_imports: &checker.from_imports,
import_aliases: &checker.import_aliases, import_aliases: &checker.import_aliases,
@ -117,7 +117,7 @@ pub fn function_call_argument_default(checker: &mut Checker, arguments: &Argumen
{ {
visitor.visit_expr(expr); visitor.visit_expr(expr);
} }
for (check, range) in visitor.checks { for (check, range) in visitor.diagnostics {
checker.diagnostics.push(Diagnostic::new(check, range)); checker.diagnostics.push(Diagnostic::new(check, range));
} }
} }

View File

@ -45,15 +45,16 @@ pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
return; return;
} }
let mut check = Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&attribute(obj, value), 0); generator.unparse_expr(&attribute(obj, value), 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -8,7 +8,7 @@ use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
struct RaiseVisitor { struct RaiseVisitor {
checks: Vec<Diagnostic>, diagnostics: Vec<Diagnostic>,
} }
impl<'a> Visitor<'a> for RaiseVisitor { impl<'a> Visitor<'a> for RaiseVisitor {
@ -20,7 +20,7 @@ impl<'a> Visitor<'a> for RaiseVisitor {
} => match &exc.node { } => match &exc.node {
ExprKind::Name { id, .. } if is_lower(id) => {} ExprKind::Name { id, .. } if is_lower(id) => {}
_ => { _ => {
self.checks.push(Diagnostic::new( self.diagnostics.push(Diagnostic::new(
violations::RaiseWithoutFromInsideExcept, violations::RaiseWithoutFromInsideExcept,
Range::from_located(stmt), Range::from_located(stmt),
)); ));
@ -46,9 +46,11 @@ impl<'a> Visitor<'a> for RaiseVisitor {
} }
pub fn raise_without_from_inside_except(checker: &mut Checker, body: &[Stmt]) { pub fn raise_without_from_inside_except(checker: &mut Checker, body: &[Stmt]) {
let mut visitor = RaiseVisitor { checks: vec![] }; let mut visitor = RaiseVisitor {
diagnostics: vec![],
};
for stmt in body { for stmt in body {
visitor.visit_stmt(stmt); visitor.visit_stmt(stmt);
} }
checker.diagnostics.extend(visitor.checks); checker.diagnostics.extend(visitor.diagnostics);
} }

View File

@ -19,19 +19,19 @@ pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[E
let [elt] = &elts[..] else { let [elt] = &elts[..] else {
continue; continue;
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::RedundantTupleInExceptionHandler(elt.to_string()), violations::RedundantTupleInExceptionHandler(elt.to_string()),
Range::from_located(type_), Range::from_located(type_),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(elt, 0); generator.unparse_expr(elt, 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
type_.location, type_.location,
type_.end_location.unwrap(), type_.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -61,16 +61,16 @@ pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
// (i.e., it's directly within an `StmtKind::Expr`). // (i.e., it's directly within an `StmtKind::Expr`).
if let StmtKind::Expr { value: child } = &checker.current_stmt().node { if let StmtKind::Expr { value: child } = &checker.current_stmt().node {
if expr == child.as_ref() { if expr == child.as_ref() {
let mut check = let mut diagnostic =
Diagnostic::new(violations::SetAttrWithConstant, Range::from_located(expr)); Diagnostic::new(violations::SetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
assignment(obj, name, value, checker.style), assignment(obj, name, value, checker.style),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -62,18 +62,18 @@ pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body:
continue; continue;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnusedLoopControlVariable(name.to_string()), violations::UnusedLoopControlVariable(name.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Prefix the variable name with an underscore. // Prefix the variable name with an underscore.
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("_{name}"), format!("_{name}"),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -59,16 +59,16 @@ pub fn unnecessary_generator_list(
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?;
if let ExprKind::GeneratorExp { .. } = argument { if let ExprKind::GeneratorExp { .. } = argument {
let mut check = Diagnostic::new(violations::UnnecessaryGeneratorList, location); let mut diagnostic = Diagnostic::new(violations::UnnecessaryGeneratorList, location);
if fix { if fix {
match fixes::fix_unnecessary_generator_list(locator, expr) { match fixes::fix_unnecessary_generator_list(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
return Some(check); return Some(diagnostic);
} }
None None
} }
@ -85,16 +85,16 @@ pub fn unnecessary_generator_set(
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
if let ExprKind::GeneratorExp { .. } = argument { if let ExprKind::GeneratorExp { .. } = argument {
let mut check = Diagnostic::new(violations::UnnecessaryGeneratorSet, location); let mut diagnostic = Diagnostic::new(violations::UnnecessaryGeneratorSet, location);
if fix { if fix {
match fixes::fix_unnecessary_generator_set(locator, expr) { match fixes::fix_unnecessary_generator_set(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
return Some(check); return Some(diagnostic);
} }
None None
} }
@ -113,16 +113,17 @@ pub fn unnecessary_generator_dict(
if let ExprKind::GeneratorExp { elt, .. } = argument { if let ExprKind::GeneratorExp { elt, .. } = argument {
match &elt.node { match &elt.node {
ExprKind::Tuple { elts, .. } if elts.len() == 2 => { ExprKind::Tuple { elts, .. } if elts.len() == 2 => {
let mut check = Diagnostic::new(violations::UnnecessaryGeneratorDict, location); let mut diagnostic =
Diagnostic::new(violations::UnnecessaryGeneratorDict, location);
if fix { if fix {
match fixes::fix_unnecessary_generator_dict(locator, expr) { match fixes::fix_unnecessary_generator_dict(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
return Some(check); return Some(diagnostic);
} }
_ => {} _ => {}
} }
@ -142,16 +143,16 @@ pub fn unnecessary_list_comprehension_set(
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?; let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
if let ExprKind::ListComp { .. } = &argument { if let ExprKind::ListComp { .. } = &argument {
let mut check = Diagnostic::new(violations::UnnecessaryListComprehensionSet, location); let mut diagnostic = Diagnostic::new(violations::UnnecessaryListComprehensionSet, location);
if fix { if fix {
match fixes::fix_unnecessary_list_comprehension_set(locator, expr) { match fixes::fix_unnecessary_list_comprehension_set(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
return Some(check); return Some(diagnostic);
} }
None None
} }
@ -176,16 +177,16 @@ pub fn unnecessary_list_comprehension_dict(
if elts.len() != 2 { if elts.len() != 2 {
return None; return None;
} }
let mut check = Diagnostic::new(violations::UnnecessaryListComprehensionDict, location); let mut diagnostic = Diagnostic::new(violations::UnnecessaryListComprehensionDict, location);
if fix { if fix {
match fixes::fix_unnecessary_list_comprehension_dict(locator, expr) { match fixes::fix_unnecessary_list_comprehension_dict(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C405 (`set([1, 2])`) /// C405 (`set([1, 2])`)
@ -204,19 +205,19 @@ pub fn unnecessary_literal_set(
ExprKind::Tuple { .. } => "tuple", ExprKind::Tuple { .. } => "tuple",
_ => return None, _ => return None,
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralSet(kind.to_string()), violations::UnnecessaryLiteralSet(kind.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_literal_set(locator, expr) { match fixes::fix_unnecessary_literal_set(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C406 (`dict([(1, 2)])`) /// C406 (`dict([(1, 2)])`)
@ -242,19 +243,19 @@ pub fn unnecessary_literal_dict(
{ {
return None; return None;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralDict(kind.to_string()), violations::UnnecessaryLiteralDict(kind.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_literal_dict(locator, expr) { match fixes::fix_unnecessary_literal_dict(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C408 /// C408
@ -280,19 +281,19 @@ pub fn unnecessary_collection_call(
} }
_ => return None, _ => return None,
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryCollectionCall(id.to_string()), violations::UnnecessaryCollectionCall(id.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_collection_call(locator, expr) { match fixes::fix_unnecessary_collection_call(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C409 /// C409
@ -310,19 +311,19 @@ pub fn unnecessary_literal_within_tuple_call(
ExprKind::List { .. } => "list", ExprKind::List { .. } => "list",
_ => return None, _ => return None,
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()), violations::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_literal_within_tuple_call(locator, expr) { match fixes::fix_unnecessary_literal_within_tuple_call(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C410 /// C410
@ -340,19 +341,19 @@ pub fn unnecessary_literal_within_list_call(
ExprKind::List { .. } => "list", ExprKind::List { .. } => "list",
_ => return None, _ => return None,
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralWithinListCall(argument_kind.to_string()), violations::UnnecessaryLiteralWithinListCall(argument_kind.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_literal_within_list_call(locator, expr) { match fixes::fix_unnecessary_literal_within_list_call(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C411 /// C411
@ -368,16 +369,16 @@ pub fn unnecessary_list_call(
if !matches!(argument, ExprKind::ListComp { .. }) { if !matches!(argument, ExprKind::ListComp { .. }) {
return None; return None;
} }
let mut check = Diagnostic::new(violations::UnnecessaryListCall, location); let mut diagnostic = Diagnostic::new(violations::UnnecessaryListCall, location);
if fix { if fix {
match fixes::fix_unnecessary_list_call(locator, expr) { match fixes::fix_unnecessary_list_call(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C413 /// C413
@ -400,19 +401,19 @@ pub fn unnecessary_call_around_sorted(
return None; return None;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryCallAroundSorted(outer.to_string()), violations::UnnecessaryCallAroundSorted(outer.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_call_around_sorted(locator, expr) { match fixes::fix_unnecessary_call_around_sorted(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C414 /// C414
@ -525,19 +526,19 @@ pub fn unnecessary_comprehension(
ExprKind::SetComp { .. } => "set", ExprKind::SetComp { .. } => "set",
_ => return None, _ => return None,
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryComprehension(expr_kind.to_string()), violations::UnnecessaryComprehension(expr_kind.to_string()),
location, location,
); );
if fix { if fix {
match fixes::fix_unnecessary_comprehension(locator, expr) { match fixes::fix_unnecessary_comprehension(locator, expr) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to generate fix: {e}"), Err(e) => error!("Failed to generate fix: {e}"),
} }
} }
Some(check) Some(diagnostic)
} }
/// C417 /// C417

View File

@ -27,21 +27,21 @@ pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) {
} }
) { ) {
if matches!(pass_stmt.node, StmtKind::Pass) { if matches!(pass_stmt.node, StmtKind::Pass) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoUnnecessaryPass, violations::NoUnnecessaryPass,
Range::from_located(pass_stmt), Range::from_located(pass_stmt),
); );
if checker.patch(&RuleCode::PIE790) { if checker.patch(&RuleCode::PIE790) {
match delete_stmt(pass_stmt, None, &[], checker.locator) { match delete_stmt(pass_stmt, None, &[], checker.locator) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => { Err(e) => {
error!("Failed to delete `pass` statement: {}", e); error!("Failed to delete `pass` statement: {}", e);
} }
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -78,14 +78,14 @@ pub fn dupe_class_field_definitions(checker: &mut Checker, bases: &[Expr], body:
}; };
if seen_targets.contains(target) { if seen_targets.contains(target) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DupeClassFieldDefinitions(target.to_string()), violations::DupeClassFieldDefinitions(target.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(&RuleCode::PIE794) { if checker.patch(&RuleCode::PIE794) {
check.amend(Fix::deletion(stmt.location, stmt.end_location.unwrap())); diagnostic.amend(Fix::deletion(stmt.location, stmt.end_location.unwrap()));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} else { } else {
seen_targets.insert(target); seen_targets.insert(target);
} }
@ -100,16 +100,16 @@ pub fn prefer_list_builtin(checker: &mut Checker, expr: &Expr) {
if args.args.is_empty() { if args.args.is_empty() {
if let ExprKind::List { elts, .. } = &body.node { if let ExprKind::List { elts, .. } = &body.node {
if elts.is_empty() { if elts.is_empty() {
let mut check = let mut diagnostic =
Diagnostic::new(violations::PreferListBuiltin, Range::from_located(expr)); Diagnostic::new(violations::PreferListBuiltin, Range::from_located(expr));
if checker.patch(&RuleCode::PIE807) { if checker.patch(&RuleCode::PIE807) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"list".to_string(), "list".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -10,7 +10,7 @@ use crate::violations;
/// T201, T203 /// T201, T203
pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) { pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) {
let mut check = { let mut diagnostic = {
let call_path = dealias_call_path(collect_call_paths(func), &checker.import_aliases); let call_path = dealias_call_path(collect_call_paths(func), &checker.import_aliases);
if match_call_path(&call_path, "", "print", &checker.from_imports) { if match_call_path(&call_path, "", "print", &checker.from_imports) {
// If the print call has a `file=` argument (that isn't `None`, `"sys.stdout"`, // If the print call has a `file=` argument (that isn't `None`, `"sys.stdout"`,
@ -36,11 +36,11 @@ pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) {
} }
}; };
if !checker.settings.enabled.contains(check.kind.code()) { if !checker.settings.enabled.contains(diagnostic.kind.code()) {
return; return;
} }
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let defined_by = checker.current_stmt(); let defined_by = checker.current_stmt();
let defined_in = checker.current_stmt_parent(); let defined_in = checker.current_stmt_parent();
if matches!(defined_by.node, StmtKind::Expr { .. }) { if matches!(defined_by.node, StmtKind::Expr { .. }) {
@ -59,12 +59,12 @@ pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) {
if fix.content.is_empty() || fix.content == "pass" { if fix.content.is_empty() || fix.content == "pass" {
checker.deletions.insert(defined_by.clone()); checker.deletions.insert(defined_by.clone());
} }
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to remove print call: {e}"), Err(e) => error!("Failed to remove print call: {e}"),
} }
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -99,20 +99,20 @@ pub fn unittest_assertion(
match &func.node { match &func.node {
ExprKind::Attribute { attr, .. } => { ExprKind::Attribute { attr, .. } => {
if let Ok(unittest_assert) = UnittestAssert::try_from(attr.as_str()) { if let Ok(unittest_assert) = UnittestAssert::try_from(attr.as_str()) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnittestAssertion(unittest_assert.to_string()), violations::UnittestAssertion(unittest_assert.to_string()),
Range::from_located(func), Range::from_located(func),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) { if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_stmt(&stmt, checker.style), unparse_stmt(&stmt, checker.style),
call.location, call.location,
call.end_location.unwrap(), call.end_location.unwrap(),
)); ));
} }
} }
Some(check) Some(diagnostic)
} else { } else {
None None
} }

View File

@ -79,14 +79,14 @@ fn pytest_fixture_parentheses(
preferred: &str, preferred: &str,
actual: &str, actual: &str,
) { ) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()), violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()),
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(fix); diagnostic.amend(fix);
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// PT001, PT002, PT003 /// PT001, PT002, PT003
@ -176,12 +176,12 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
if let StmtKind::Expr { value, .. } = &stmt.node { if let StmtKind::Expr { value, .. } = &stmt.node {
if let ExprKind::Yield { .. } = value.node { if let ExprKind::Yield { .. } = value.node {
if visitor.yield_statements.len() == 1 { if visitor.yield_statements.len() == 1 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UselessYieldFixture(func_name.to_string()), violations::UselessYieldFixture(func_name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"return".to_string(), "return".to_string(),
stmt.location, stmt.location,
Location::new( Location::new(
@ -190,7 +190,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -14,7 +14,7 @@ fn pytest_mark_parentheses(
preferred: &str, preferred: &str,
actual: &str, actual: &str,
) { ) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::IncorrectMarkParenthesesStyle( violations::IncorrectMarkParenthesesStyle(
get_mark_name(decorator).to_string(), get_mark_name(decorator).to_string(),
preferred.to_string(), preferred.to_string(),
@ -22,10 +22,10 @@ fn pytest_mark_parentheses(
), ),
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(fix); diagnostic.amend(fix);
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
fn check_mark_parentheses(checker: &mut Checker, decorator: &Expr) { fn check_mark_parentheses(checker: &mut Checker, decorator: &Expr) {
@ -71,15 +71,15 @@ fn check_useless_usefixtures(checker: &mut Checker, decorator: &Expr) {
} }
if !has_parameters { if !has_parameters {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UseFixturesWithoutParameters, violations::UseFixturesWithoutParameters,
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let at_start = Location::new(decorator.location.row(), decorator.location.column() - 1); let at_start = Location::new(decorator.location.row(), decorator.location.column() - 1);
check.amend(Fix::deletion(at_start, decorator.end_location.unwrap())); diagnostic.amend(Fix::deletion(at_start, decorator.end_location.unwrap()));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -80,11 +80,11 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
if names.len() > 1 { if names.len() > 1 {
match names_type { match names_type {
types::ParametrizeNameType::Tuple => { types::ParametrizeNameType::Tuple => {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::Tuple { &create_expr(ExprKind::Tuple {
@ -101,20 +101,20 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}), }),
1, 1,
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
types::ParametrizeNameType::List => { types::ParametrizeNameType::List => {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::List { &create_expr(ExprKind::List {
@ -131,13 +131,13 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}), }),
0, 0,
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
types::ParametrizeNameType::CSV => {} types::ParametrizeNameType::CSV => {}
} }
@ -152,11 +152,11 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
match names_type { match names_type {
types::ParametrizeNameType::Tuple => {} types::ParametrizeNameType::Tuple => {}
types::ParametrizeNameType::List => { types::ParametrizeNameType::List => {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::List { &create_expr(ExprKind::List {
@ -165,29 +165,29 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}), }),
0, 0,
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
types::ParametrizeNameType::CSV => { types::ParametrizeNameType::CSV => {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(content) = elts_to_csv(elts, checker) { if let Some(content) = elts_to_csv(elts, checker) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
}; };
@ -201,11 +201,11 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
match names_type { match names_type {
types::ParametrizeNameType::List => {} types::ParametrizeNameType::List => {}
types::ParametrizeNameType::Tuple => { types::ParametrizeNameType::Tuple => {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::Tuple { &create_expr(ExprKind::Tuple {
@ -214,29 +214,29 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}), }),
1, // so tuple is generated with parentheses 1, // so tuple is generated with parentheses
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
types::ParametrizeNameType::CSV => { types::ParametrizeNameType::CSV => {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(content) = elts_to_csv(elts, checker) { if let Some(content) = elts_to_csv(elts, checker) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
}; };
@ -278,21 +278,21 @@ fn check_values(checker: &mut Checker, expr: &Expr) {
} }
fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) { fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV), violations::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&create_expr(value.node.clone()), 0); generator.unparse_expr(&create_expr(value.node.clone()), 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
fn handle_value_rows( fn handle_value_rows(

View File

@ -27,16 +27,16 @@ fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) {
) { ) {
continue; continue;
} }
let mut check = let mut diagnostic =
Diagnostic::new(violations::UnnecessaryReturnNone, Range::from_located(stmt)); Diagnostic::new(violations::UnnecessaryReturnNone, Range::from_located(stmt));
if checker.patch(&RuleCode::RET501) { if checker.patch(&RuleCode::RET501) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"return".to_string(), "return".to_string(),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -46,15 +46,16 @@ fn implicit_return_value(checker: &mut Checker, stack: &Stack) {
if expr.is_some() { if expr.is_some() {
continue; continue;
} }
let mut check = Diagnostic::new(violations::ImplicitReturnValue, Range::from_located(stmt)); let mut diagnostic =
Diagnostic::new(violations::ImplicitReturnValue, Range::from_located(stmt));
if checker.patch(&RuleCode::RET502) { if checker.patch(&RuleCode::RET502) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"return None".to_string(), "return None".to_string(),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -102,19 +103,19 @@ fn implicit_return(checker: &mut Checker, last_stmt: &Stmt) {
| StmtKind::Raise { .. } | StmtKind::Raise { .. }
| StmtKind::Try { .. } => {} | StmtKind::Try { .. } => {}
_ => { _ => {
let mut check = let mut diagnostic =
Diagnostic::new(violations::ImplicitReturn, Range::from_located(last_stmt)); Diagnostic::new(violations::ImplicitReturn, Range::from_located(last_stmt));
if checker.patch(&RuleCode::RET503) { if checker.patch(&RuleCode::RET503) {
let mut content = String::new(); let mut content = String::new();
content.push_str(&indentation(checker, last_stmt)); content.push_str(&indentation(checker, last_stmt));
content.push_str("return None"); content.push_str("return None");
content.push('\n'); content.push('\n');
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
content, content,
Location::new(last_stmt.end_location.unwrap().row() + 1, 0), Location::new(last_stmt.end_location.unwrap().row() + 1, 0),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -62,7 +62,7 @@ pub fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) {
// Generate a `Diagnostic` for each duplicate. // Generate a `Diagnostic` for each duplicate.
for (arg_name, indices) in duplicates { for (arg_name, indices) in duplicates {
if indices.len() > 1 { if indices.len() > 1 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DuplicateIsinstanceCall(arg_name.to_string()), violations::DuplicateIsinstanceCall(arg_name.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
@ -125,13 +125,13 @@ pub fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) {
// Populate the `Fix`. Replace the _entire_ `BoolOp`. Note that if we have // Populate the `Fix`. Replace the _entire_ `BoolOp`. Note that if we have
// multiple duplicates, the fixes will conflict. // multiple duplicates, the fixes will conflict.
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr(&bool_op, checker.style), unparse_expr(&bool_op, checker.style),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -171,7 +171,7 @@ pub fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
.iter() .iter()
.map(|value| unparse_expr(value, checker.style)) .map(|value| unparse_expr(value, checker.style))
.collect(); .collect();
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::CompareWithTuple( violations::CompareWithTuple(
value.to_string(), value.to_string(),
str_values, str_values,
@ -192,13 +192,13 @@ pub fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
ctx: ExprContext::Load, ctx: ExprContext::Load,
})], })],
}); });
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr(&in_expr, checker.style), unparse_expr(&in_expr, checker.style),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -233,18 +233,18 @@ pub fn a_and_not_a(checker: &mut Checker, expr: &Expr) {
for negate_expr in negated_expr { for negate_expr in negated_expr {
for non_negate_expr in &non_negated_expr { for non_negate_expr in &non_negated_expr {
if let Some(id) = is_same_expr(negate_expr, non_negate_expr) { if let Some(id) = is_same_expr(negate_expr, non_negate_expr) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::AAndNotA(id.to_string()), violations::AAndNotA(id.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(&RuleCode::SIM220) { if checker.patch(&RuleCode::SIM220) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"False".to_string(), "False".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -281,18 +281,18 @@ pub fn a_or_not_a(checker: &mut Checker, expr: &Expr) {
for negate_expr in negated_expr { for negate_expr in negated_expr {
for non_negate_expr in &non_negated_expr { for non_negate_expr in &non_negated_expr {
if let Some(id) = is_same_expr(negate_expr, non_negate_expr) { if let Some(id) = is_same_expr(negate_expr, non_negate_expr) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::AOrNotA(id.to_string()), violations::AOrNotA(id.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(&RuleCode::SIM220) { if checker.patch(&RuleCode::SIM220) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"True".to_string(), "True".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -309,15 +309,15 @@ pub fn or_true(checker: &mut Checker, expr: &Expr) {
.. ..
} = &value.node } = &value.node
{ {
let mut check = Diagnostic::new(violations::OrTrue, Range::from_located(value)); let mut diagnostic = Diagnostic::new(violations::OrTrue, Range::from_located(value));
if checker.patch(&RuleCode::SIM223) { if checker.patch(&RuleCode::SIM223) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"True".to_string(), "True".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -333,15 +333,15 @@ pub fn and_false(checker: &mut Checker, expr: &Expr) {
.. ..
} = &value.node } = &value.node
{ {
let mut check = Diagnostic::new(violations::AndFalse, Range::from_located(value)); let mut diagnostic = Diagnostic::new(violations::AndFalse, Range::from_located(value));
if checker.patch(&RuleCode::SIM223) { if checker.patch(&RuleCode::SIM223) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"False".to_string(), "False".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -118,18 +118,18 @@ pub fn convert_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling: &Stm
loop_info.iter, loop_info.iter,
checker.style, checker.style,
); );
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ConvertLoopToAny(content.clone()), violations::ConvertLoopToAny(content.clone()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(&RuleCode::SIM110) { if checker.patch(&RuleCode::SIM110) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
stmt.location, stmt.location,
sibling.end_location.unwrap(), sibling.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -157,18 +157,18 @@ pub fn convert_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling: &Stm
loop_info.iter, loop_info.iter,
checker.style, checker.style,
); );
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ConvertLoopToAll(content.clone()), violations::ConvertLoopToAll(content.clone()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(&RuleCode::SIM111) { if checker.patch(&RuleCode::SIM111) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
stmt.location, stmt.location,
sibling.end_location.unwrap(), sibling.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -88,7 +88,7 @@ pub fn return_bool_condition_directly(checker: &mut Checker, stmt: &Stmt) {
return; return;
} }
let condition = unparse_expr(test, checker.style); let condition = unparse_expr(test, checker.style);
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ReturnBoolConditionDirectly(condition), violations::ReturnBoolConditionDirectly(condition),
Range::from_located(stmt), Range::from_located(stmt),
); );
@ -96,13 +96,13 @@ pub fn return_bool_condition_directly(checker: &mut Checker, stmt: &Stmt) {
let return_stmt = create_stmt(StmtKind::Return { let return_stmt = create_stmt(StmtKind::Return {
value: Some(test.clone()), value: Some(test.clone()),
}); });
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_stmt(&return_stmt, checker.style), unparse_stmt(&return_stmt, checker.style),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
fn ternary(target_var: &Expr, body_value: &Expr, test: &Expr, orelse_value: &Expr) -> Stmt { fn ternary(target_var: &Expr, body_value: &Expr, test: &Expr, orelse_value: &Expr) -> Stmt {
@ -178,16 +178,16 @@ pub fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: Option<&
let ternary = ternary(target_var, body_value, test, orelse_value); let ternary = ternary(target_var, body_value, test, orelse_value);
let content = unparse_stmt(&ternary, checker.style); let content = unparse_stmt(&ternary, checker.style);
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UseTernaryOperator(content.clone()), violations::UseTernaryOperator(content.clone()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(&RuleCode::SIM108) { if checker.patch(&RuleCode::SIM108) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -28,12 +28,12 @@ pub fn explicit_true_false_in_ifexpr(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::IfExprWithTrueFalse(unparse_expr(test, checker.style)), violations::IfExprWithTrueFalse(unparse_expr(test, checker.style)),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::Call { &create_expr(ExprKind::Call {
func: Box::new(create_expr(ExprKind::Name { func: Box::new(create_expr(ExprKind::Name {
@ -49,7 +49,7 @@ pub fn explicit_true_false_in_ifexpr(
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// SIM211 /// SIM211
@ -73,12 +73,12 @@ pub fn explicit_false_true_in_ifexpr(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::IfExprWithFalseTrue(unparse_expr(test, checker.style)), violations::IfExprWithFalseTrue(unparse_expr(test, checker.style)),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::UnaryOp { &create_expr(ExprKind::UnaryOp {
op: Unaryop::Not, op: Unaryop::Not,
@ -90,7 +90,7 @@ pub fn explicit_false_true_in_ifexpr(
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// SIM212 /// SIM212
@ -119,15 +119,15 @@ pub fn twisted_arms_in_ifexpr(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::IfExprWithTwistedArms( violations::IfExprWithTwistedArms(
unparse_expr(body, checker.style), unparse_expr(body, checker.style),
unparse_expr(orelse, checker.style), unparse_expr(orelse, checker.style),
), ),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::IfExp { &create_expr(ExprKind::IfExp {
test: Box::new(create_expr(orelse.node.clone())), test: Box::new(create_expr(orelse.node.clone())),
@ -140,5 +140,5 @@ pub fn twisted_arms_in_ifexpr(
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -35,15 +35,15 @@ pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop,
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NegateEqualOp( violations::NegateEqualOp(
unparse_expr(left, checker.style), unparse_expr(left, checker.style),
unparse_expr(&comparators[0], checker.style), unparse_expr(&comparators[0], checker.style),
), ),
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::Compare { &create_expr(ExprKind::Compare {
left: left.clone(), left: left.clone(),
@ -56,7 +56,7 @@ pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// SIM202 /// SIM202
@ -79,15 +79,15 @@ pub fn negation_with_not_equal_op(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NegateNotEqualOp( violations::NegateNotEqualOp(
unparse_expr(left, checker.style), unparse_expr(left, checker.style),
unparse_expr(&comparators[0], checker.style), unparse_expr(&comparators[0], checker.style),
), ),
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::Compare { &create_expr(ExprKind::Compare {
left: left.clone(), left: left.clone(),
@ -100,7 +100,7 @@ pub fn negation_with_not_equal_op(
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// SIM208 /// SIM208
@ -115,16 +115,16 @@ pub fn double_negation(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DoubleNegation(operand.to_string()), violations::DoubleNegation(operand.to_string()),
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr(operand, checker.style), unparse_expr(operand, checker.style),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -34,18 +34,18 @@ fn key_in_dict(checker: &mut Checker, left: &Expr, right: &Expr, range: Range) {
.locator .locator
.slice_source_code_range(&Range::from_located(value)); .slice_source_code_range(&Range::from_located(value));
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::KeyInDict(left_content.to_string(), value_content.to_string()), violations::KeyInDict(left_content.to_string(), value_content.to_string()),
range, range,
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
value_content.to_string(), value_content.to_string(),
right.location, right.location,
right.end_location.unwrap(), right.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// SIM118 in a for loop /// SIM118 in a for loop

View File

@ -30,11 +30,10 @@ pub fn use_contextlib_suppress(
} else { } else {
handler_names.join(", ") handler_names.join(", ")
}; };
let check = Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
violations::UseContextlibSuppress(exception), violations::UseContextlibSuppress(exception),
Range::from_located(stmt), Range::from_located(stmt),
); ));
checker.diagnostics.push(check);
} }
} }
} }

View File

@ -41,18 +41,18 @@ pub fn yoda_conditions(
.locator .locator
.slice_source_code_range(&Range::from_located(right)); .slice_source_code_range(&Range::from_located(right));
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::YodaConditions(left_content.to_string(), right_content.to_string()), violations::YodaConditions(left_content.to_string(), right_content.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("{right_content} == {left_content}"), format!("{right_content} == {left_content}"),
left.location, left.location,
right.end_location.unwrap(), right.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -21,7 +21,7 @@ fn function(
dummy_variable_rgx: &Regex, dummy_variable_rgx: &Regex,
ignore_variadic_names: bool, ignore_variadic_names: bool,
) -> Vec<Diagnostic> { ) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
for arg in args for arg in args
.posonlyargs .posonlyargs
.iter() .iter()
@ -46,14 +46,14 @@ fn function(
&& matches!(binding.kind, BindingKind::Argument) && matches!(binding.kind, BindingKind::Argument)
&& !dummy_variable_rgx.is_match(arg.node.arg.as_str()) && !dummy_variable_rgx.is_match(arg.node.arg.as_str())
{ {
checks.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
argumentable.check_for(arg.node.arg.to_string()), argumentable.check_for(arg.node.arg.to_string()),
binding.range, binding.range,
)); ));
} }
} }
} }
checks diagnostics
} }
/// Check a method for unused arguments. /// Check a method for unused arguments.
@ -65,7 +65,7 @@ fn method(
dummy_variable_rgx: &Regex, dummy_variable_rgx: &Regex,
ignore_variadic_names: bool, ignore_variadic_names: bool,
) -> Vec<Diagnostic> { ) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
for arg in args for arg in args
.posonlyargs .posonlyargs
.iter() .iter()
@ -91,14 +91,14 @@ fn method(
&& matches!(binding.kind, BindingKind::Argument) && matches!(binding.kind, BindingKind::Argument)
&& !dummy_variable_rgx.is_match(arg.node.arg.as_str()) && !dummy_variable_rgx.is_match(arg.node.arg.as_str())
{ {
checks.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
argumentable.check_for(arg.node.arg.to_string()), argumentable.check_for(arg.node.arg.to_string()),
binding.range, binding.range,
)); ));
} }
} }
} }
checks diagnostics
} }
/// ARG001, ARG002, ARG003, ARG004, ARG005 /// ARG001, ARG002, ARG003, ARG004, ARG005

View File

@ -92,16 +92,16 @@ pub fn check_imports(
if actual == dedent(&expected) { if actual == dedent(&expected) {
None None
} else { } else {
let mut check = Diagnostic::new(violations::UnsortedImports, range); let mut diagnostic = Diagnostic::new(violations::UnsortedImports, range);
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code()) && settings.fixable.contains(diagnostic.kind.code())
{ {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
indent(&expected, indentation), indent(&expected, indentation),
range.location, range.location,
range.end_location, range.end_location,
)); ));
} }
Some(check) Some(diagnostic)
} }
} }

View File

@ -172,16 +172,16 @@ pub fn check(contents: &str, options: JsValue) -> Result<JsValue, JsValue> {
) )
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let messages: Vec<ExpandedMessage> = checks let messages: Vec<ExpandedMessage> = diagnostics
.into_iter() .into_iter()
.map(|check| ExpandedMessage { .map(|diagnostic| ExpandedMessage {
code: check.kind.code().clone(), code: diagnostic.kind.code().clone(),
message: check.kind.body(), message: diagnostic.kind.body(),
location: check.location, location: diagnostic.location,
end_location: check.end_location, end_location: diagnostic.end_location,
fix: check.fix.map(|fix| ExpandedFix { fix: diagnostic.fix.map(|fix| ExpandedFix {
content: fix.content, content: fix.content,
message: check.kind.commit(), message: diagnostic.kind.commit(),
location: fix.location, location: fix.location,
end_location: fix.end_location, end_location: fix.end_location,
}), }),

View File

@ -164,7 +164,7 @@ pub(crate) fn check_path(
if !ignores.is_empty() { if !ignores.is_empty() {
return Ok(diagnostics return Ok(diagnostics
.into_iter() .into_iter()
.filter(|check| !ignores.contains(&check.kind.code())) .filter(|diagnostic| !ignores.contains(&diagnostic.kind.code()))
.collect()); .collect());
} }
} }

View File

@ -54,7 +54,7 @@ pub fn line_too_long(lineno: usize, line: &str, settings: &Settings) -> Option<D
/// E721 /// E721
pub fn type_comparison(ops: &[Cmpop], comparators: &[Expr], location: Range) -> Vec<Diagnostic> { pub fn type_comparison(ops: &[Cmpop], comparators: &[Expr], location: Range) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
for (op, right) in izip!(ops, comparators) { for (op, right) in izip!(ops, comparators) {
if !matches!(op, Cmpop::Is | Cmpop::IsNot | Cmpop::Eq | Cmpop::NotEq) { if !matches!(op, Cmpop::Is | Cmpop::IsNot | Cmpop::Eq | Cmpop::NotEq) {
@ -75,7 +75,8 @@ pub fn type_comparison(ops: &[Cmpop], comparators: &[Expr], location: Range) ->
kind: None kind: None
} }
) { ) {
checks.push(Diagnostic::new(violations::TypeComparison, location)); diagnostics
.push(Diagnostic::new(violations::TypeComparison, location));
} }
} }
} }
@ -85,7 +86,7 @@ pub fn type_comparison(ops: &[Cmpop], comparators: &[Expr], location: Range) ->
if let ExprKind::Name { id, .. } = &value.node { if let ExprKind::Name { id, .. } = &value.node {
// Ex) types.IntType // Ex) types.IntType
if id == "types" { if id == "types" {
checks.push(Diagnostic::new(violations::TypeComparison, location)); diagnostics.push(Diagnostic::new(violations::TypeComparison, location));
} }
} }
} }
@ -93,7 +94,7 @@ pub fn type_comparison(ops: &[Cmpop], comparators: &[Expr], location: Range) ->
} }
} }
checks diagnostics
} }
/// E722 /// E722
@ -171,14 +172,14 @@ pub fn no_newline_at_end_of_file(contents: &str, autofix: bool) -> Option<Diagno
if let Some(line) = contents.lines().last() { if let Some(line) = contents.lines().last() {
// Both locations are at the end of the file (and thus the same). // Both locations are at the end of the file (and thus the same).
let location = Location::new(contents.lines().count(), line.len()); let location = Location::new(contents.lines().count(), line.len());
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoNewLineAtEndOfFile, violations::NoNewLineAtEndOfFile,
Range::new(location, location), Range::new(location, location),
); );
if autofix { if autofix {
check.amend(Fix::insertion("\n".to_string(), location)); diagnostic.amend(Fix::insertion("\n".to_string(), location));
} }
return Some(check); return Some(diagnostic);
} }
} }
None None

View File

@ -47,7 +47,7 @@ pub fn literal_comparisons(
// then replace the entire expression at the end with one "real" fix, to // then replace the entire expression at the end with one "real" fix, to
// avoid conflicts. // avoid conflicts.
let mut bad_ops: FxHashMap<usize, Cmpop> = FxHashMap::default(); let mut bad_ops: FxHashMap<usize, Cmpop> = FxHashMap::default();
let mut checks: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
let op = ops.first().unwrap(); let op = ops.first().unwrap();
@ -64,24 +64,24 @@ pub fn literal_comparisons(
) )
{ {
if matches!(op, Cmpop::Eq) { if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { if checker.patch(diagnostic.kind.code()) && !helpers::is_constant_non_singleton(next) {
bad_ops.insert(0, Cmpop::Is); bad_ops.insert(0, Cmpop::Is);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
if matches!(op, Cmpop::NotEq) { if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { if checker.patch(diagnostic.kind.code()) && !helpers::is_constant_non_singleton(next) {
bad_ops.insert(0, Cmpop::IsNot); bad_ops.insert(0, Cmpop::IsNot);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
} }
@ -92,24 +92,28 @@ pub fn literal_comparisons(
} = comparator.node } = comparator.node
{ {
if matches!(op, Cmpop::Eq) { if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(next)
{
bad_ops.insert(0, Cmpop::Is); bad_ops.insert(0, Cmpop::Is);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
if matches!(op, Cmpop::NotEq) { if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(check.kind.code()) && !helpers::is_constant_non_singleton(next) { if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(next)
{
bad_ops.insert(0, Cmpop::IsNot); bad_ops.insert(0, Cmpop::IsNot);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
@ -126,28 +130,28 @@ pub fn literal_comparisons(
) )
{ {
if matches!(op, Cmpop::Eq) { if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(check.kind.code()) if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::Is); bad_ops.insert(idx, Cmpop::Is);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
if matches!(op, Cmpop::NotEq) { if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(check.kind.code()) if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::IsNot); bad_ops.insert(idx, Cmpop::IsNot);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
} }
@ -158,28 +162,28 @@ pub fn literal_comparisons(
} = next.node } = next.node
{ {
if matches!(op, Cmpop::Eq) { if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(check.kind.code()) if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::Is); bad_ops.insert(idx, Cmpop::Is);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
if matches!(op, Cmpop::NotEq) { if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new( let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(check.kind.code()) if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::IsNot); bad_ops.insert(idx, Cmpop::IsNot);
} }
checks.push(check); diagnostics.push(diagnostic);
} }
} }
} }
@ -198,8 +202,8 @@ pub fn literal_comparisons(
.cloned() .cloned()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let content = compare(left, &ops, comparators, checker.style); let content = compare(left, &ops, comparators, checker.style);
for check in &mut checks { for diagnostic in &mut diagnostics {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content.to_string(), content.to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
@ -207,7 +211,7 @@ pub fn literal_comparisons(
} }
} }
checker.diagnostics.extend(checks); checker.diagnostics.extend(diagnostics);
} }
/// E713, E714 /// E713, E714
@ -232,34 +236,34 @@ pub fn not_tests(
match op { match op {
Cmpop::In => { Cmpop::In => {
if check_not_in { if check_not_in {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NotInTest, violations::NotInTest,
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(check.kind.code()) && should_fix { if checker.patch(diagnostic.kind.code()) && should_fix {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
compare(left, &[Cmpop::NotIn], comparators, checker.style), compare(left, &[Cmpop::NotIn], comparators, checker.style),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
Cmpop::Is => { Cmpop::Is => {
if check_not_is { if check_not_is {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NotIsTest, violations::NotIsTest,
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(check.kind.code()) && should_fix { if checker.patch(diagnostic.kind.code()) && should_fix {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
compare(left, &[Cmpop::IsNot], comparators, checker.style), compare(left, &[Cmpop::IsNot], comparators, checker.style),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
_ => {} _ => {}
@ -303,11 +307,11 @@ fn function(
pub fn do_not_assign_lambda(checker: &mut Checker, target: &Expr, value: &Expr, stmt: &Stmt) { pub fn do_not_assign_lambda(checker: &mut Checker, target: &Expr, value: &Expr, stmt: &Stmt) {
if let ExprKind::Name { id, .. } = &target.node { if let ExprKind::Name { id, .. } = &target.node {
if let ExprKind::Lambda { args, body } = &value.node { if let ExprKind::Lambda { args, body } = &value.node {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DoNotAssignLambda(id.to_string()), violations::DoNotAssignLambda(id.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if !match_leading_content(stmt, checker.locator) if !match_leading_content(stmt, checker.locator)
&& !match_trailing_content(stmt, checker.locator) && !match_trailing_content(stmt, checker.locator)
{ {
@ -326,14 +330,14 @@ pub fn do_not_assign_lambda(checker: &mut Checker, target: &Expr, value: &Expr,
indented.push_str(line); indented.push_str(line);
} }
} }
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
indented, indented,
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -166,18 +166,18 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
.take_while(|line| line.trim().is_empty()) .take_while(|line| line.trim().is_empty())
.count(); .count();
if blank_lines_before != 0 { if blank_lines_before != 0 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoBlankLineBeforeFunction(blank_lines_before), violations::NoBlankLineBeforeFunction(blank_lines_before),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete the blank line before the docstring. // Delete the blank line before the docstring.
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(docstring.expr.location.row() - blank_lines_before, 0), Location::new(docstring.expr.location.row() - blank_lines_before, 0),
Location::new(docstring.expr.location.row(), 0), Location::new(docstring.expr.location.row(), 0),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -207,13 +207,13 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
} }
if blank_lines_after != 0 { if blank_lines_after != 0 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoBlankLineAfterFunction(blank_lines_after), violations::NoBlankLineAfterFunction(blank_lines_after),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete the blank line after the docstring. // Delete the blank line after the docstring.
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(docstring.expr.end_location.unwrap().row() + 1, 0), Location::new(docstring.expr.end_location.unwrap().row() + 1, 0),
Location::new( Location::new(
docstring.expr.end_location.unwrap().row() + 1 + blank_lines_after, docstring.expr.end_location.unwrap().row() + 1 + blank_lines_after,
@ -221,7 +221,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -248,35 +248,35 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
.count(); .count();
if checker.settings.enabled.contains(&RuleCode::D211) { if checker.settings.enabled.contains(&RuleCode::D211) {
if blank_lines_before != 0 { if blank_lines_before != 0 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoBlankLineBeforeClass(blank_lines_before), violations::NoBlankLineBeforeClass(blank_lines_before),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete the blank line before the class. // Delete the blank line before the class.
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(docstring.expr.location.row() - blank_lines_before, 0), Location::new(docstring.expr.location.row() - blank_lines_before, 0),
Location::new(docstring.expr.location.row(), 0), Location::new(docstring.expr.location.row(), 0),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
if checker.settings.enabled.contains(&RuleCode::D203) { if checker.settings.enabled.contains(&RuleCode::D203) {
if blank_lines_before != 1 { if blank_lines_before != 1 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::OneBlankLineBeforeClass(blank_lines_before), violations::OneBlankLineBeforeClass(blank_lines_before),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Insert one blank line before the class. // Insert one blank line before the class.
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"\n".to_string(), "\n".to_string(),
Location::new(docstring.expr.location.row() - blank_lines_before, 0), Location::new(docstring.expr.location.row() - blank_lines_before, 0),
Location::new(docstring.expr.location.row(), 0), Location::new(docstring.expr.location.row(), 0),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -301,13 +301,13 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
.take_while(|line| line.trim().is_empty()) .take_while(|line| line.trim().is_empty())
.count(); .count();
if blank_lines_after != 1 { if blank_lines_after != 1 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::OneBlankLineAfterClass(blank_lines_after), violations::OneBlankLineAfterClass(blank_lines_after),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Insert a blank line before the class (replacing any existing lines). // Insert a blank line before the class (replacing any existing lines).
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"\n".to_string(), "\n".to_string(),
Location::new(docstring.expr.end_location.unwrap().row() + 1, 0), Location::new(docstring.expr.end_location.unwrap().row() + 1, 0),
Location::new( Location::new(
@ -316,7 +316,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -336,11 +336,11 @@ pub fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) {
} }
} }
if lines_count > 1 && blanks_count != 1 { if lines_count > 1 && blanks_count != 1 {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::BlankLineAfterSummary(blanks_count), violations::BlankLineAfterSummary(blanks_count),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if blanks_count > 1 { if blanks_count > 1 {
// Find the "summary" line (defined as the first non-blank line). // Find the "summary" line (defined as the first non-blank line).
let mut summary_line = 0; let mut summary_line = 0;
@ -353,7 +353,7 @@ pub fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) {
} }
// Insert one blank line after the summary (replacing any existing lines). // Insert one blank line after the summary (replacing any existing lines).
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"\n".to_string(), "\n".to_string(),
Location::new(docstring.expr.location.row() + summary_line + 1, 0), Location::new(docstring.expr.location.row() + summary_line + 1, 0),
Location::new( Location::new(
@ -363,7 +363,7 @@ pub fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) {
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -405,21 +405,21 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
if (i == lines.len() - 1 || !is_blank) if (i == lines.len() - 1 || !is_blank)
&& line_indent.len() < docstring.indentation.len() && line_indent.len() < docstring.indentation.len()
{ {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoUnderIndentation, violations::NoUnderIndentation,
Range::new( Range::new(
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
), ),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, line_indent.len()), Location::new(docstring.expr.location.row() + i, line_indent.len()),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -455,21 +455,21 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
if line_indent.len() > docstring.indentation.len() { if line_indent.len() > docstring.indentation.len() {
// We report over-indentation on every line. This isn't great, but // We report over-indentation on every line. This isn't great, but
// enables autofix. // enables autofix.
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoOverIndentation, violations::NoOverIndentation,
Range::new( Range::new(
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
), ),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, line_indent.len()), Location::new(docstring.expr.location.row() + i, line_indent.len()),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -479,21 +479,21 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
let i = lines.len() - 1; let i = lines.len() - 1;
let line_indent = whitespace::leading_space(lines[i]); let line_indent = whitespace::leading_space(lines[i]);
if line_indent.len() > docstring.indentation.len() { if line_indent.len() > docstring.indentation.len() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoOverIndentation, violations::NoOverIndentation,
Range::new( Range::new(
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
), ),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, line_indent.len()), Location::new(docstring.expr.location.row() + i, line_indent.len()),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -512,14 +512,14 @@ pub fn newline_after_last_paragraph(checker: &mut Checker, docstring: &Docstring
if line_count > 1 { if line_count > 1 {
if let Some(last_line) = contents.lines().last().map(str::trim) { if let Some(last_line) = contents.lines().last().map(str::trim) {
if last_line != "\"\"\"" && last_line != "'''" { if last_line != "\"\"\"" && last_line != "'''" {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NewLineAfterLastParagraph, violations::NewLineAfterLastParagraph,
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Insert a newline just before the end-quote(s). // Insert a newline just before the end-quote(s).
let content = format!("\n{}", whitespace::clean(docstring.indentation)); let content = format!("\n{}", whitespace::clean(docstring.indentation));
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
content, content,
Location::new( Location::new(
docstring.expr.end_location.unwrap().row(), docstring.expr.end_location.unwrap().row(),
@ -527,7 +527,7 @@ pub fn newline_after_last_paragraph(checker: &mut Checker, docstring: &Docstring
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
return; return;
@ -551,17 +551,17 @@ pub fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) {
if line == trimmed { if line == trimmed {
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoSurroundingWhitespace, violations::NoSurroundingWhitespace,
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(pattern) = leading_quote(contents) { if let Some(pattern) = leading_quote(contents) {
if let Some(quote) = pattern.chars().last() { if let Some(quote) = pattern.chars().last() {
// If removing whitespace would lead to an invalid string of quote // If removing whitespace would lead to an invalid string of quote
// characters, avoid applying the fix. // characters, avoid applying the fix.
if !trimmed.ends_with(quote) { if !trimmed.ends_with(quote) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
trimmed.to_string(), trimmed.to_string(),
Location::new( Location::new(
docstring.expr.location.row(), docstring.expr.location.row(),
@ -576,7 +576,7 @@ pub fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) {
} }
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// D212, D213 /// D212, D213
@ -696,7 +696,7 @@ pub fn ends_with_period(checker: &mut Checker, docstring: &Docstring) {
let trimmed = line.trim_end(); let trimmed = line.trim_end();
if !trimmed.ends_with('.') { if !trimmed.ends_with('.') {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::EndsInPeriod, violations::EndsInPeriod,
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
@ -718,10 +718,10 @@ pub fn ends_with_period(checker: &mut Checker, docstring: &Docstring) {
trimmed.chars().count(), trimmed.chars().count(),
)) ))
} { } {
check.amend(Fix::insertion(".".to_string(), Location::new(row, column))); diagnostic.amend(Fix::insertion(".".to_string(), Location::new(row, column)));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
}; };
} }
} }
@ -843,7 +843,7 @@ pub fn ends_with_punctuation(checker: &mut Checker, docstring: &Docstring) {
let line = body.lines().nth(index).unwrap(); let line = body.lines().nth(index).unwrap();
let trimmed = line.trim_end(); let trimmed = line.trim_end();
if !(trimmed.ends_with('.') || trimmed.ends_with('!') || trimmed.ends_with('?')) { if !(trimmed.ends_with('.') || trimmed.ends_with('!') || trimmed.ends_with('?')) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::EndsInPunctuation, violations::EndsInPunctuation,
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
@ -865,10 +865,10 @@ pub fn ends_with_punctuation(checker: &mut Checker, docstring: &Docstring) {
trimmed.chars().count(), trimmed.chars().count(),
)) ))
} { } {
check.amend(Fix::insertion(".".to_string(), Location::new(row, column))); diagnostic.amend(Fix::insertion(".".to_string(), Location::new(row, column)));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
}; };
} }
} }
@ -961,18 +961,18 @@ fn blanks_and_section_underline(
// Nothing but blank lines after the section header. // Nothing but blank lines after the section header.
if blank_lines_after_header == context.following_lines.len() { if blank_lines_after_header == context.following_lines.len() {
if checker.settings.enabled.contains(&RuleCode::D407) { if checker.settings.enabled.contains(&RuleCode::D407) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DashedUnderlineAfterSection(context.section_name.to_string()), violations::DashedUnderlineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Add a dashed line (of the appropriate length) under the section header. // Add a dashed line (of the appropriate length) under the section header.
let content = format!( let content = format!(
"{}{}\n", "{}{}\n",
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
"-".repeat(context.section_name.len()) "-".repeat(context.section_name.len())
); );
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
content, content,
Location::new( Location::new(
docstring.expr.location.row() + context.original_index + 1, docstring.expr.location.row() + context.original_index + 1,
@ -980,7 +980,7 @@ fn blanks_and_section_underline(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
if checker.settings.enabled.contains(&RuleCode::D414) { if checker.settings.enabled.contains(&RuleCode::D414) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
@ -999,13 +999,13 @@ fn blanks_and_section_underline(
if dash_line_found { if dash_line_found {
if blank_lines_after_header > 0 { if blank_lines_after_header > 0 {
if checker.settings.enabled.contains(&RuleCode::D408) { if checker.settings.enabled.contains(&RuleCode::D408) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::SectionUnderlineAfterName(context.section_name.to_string()), violations::SectionUnderlineAfterName(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete any blank lines between the header and the underline. // Delete any blank lines between the header and the underline.
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
docstring.expr.location.row() + context.original_index + 1, docstring.expr.location.row() + context.original_index + 1,
0, 0,
@ -1019,7 +1019,7 @@ fn blanks_and_section_underline(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -1031,20 +1031,20 @@ fn blanks_and_section_underline(
!= context.section_name.len() != context.section_name.len()
{ {
if checker.settings.enabled.contains(&RuleCode::D409) { if checker.settings.enabled.contains(&RuleCode::D409) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::SectionUnderlineMatchesSectionLength( violations::SectionUnderlineMatchesSectionLength(
context.section_name.to_string(), context.section_name.to_string(),
), ),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Replace the existing underline with a line of the appropriate length. // Replace the existing underline with a line of the appropriate length.
let content = format!( let content = format!(
"{}{}\n", "{}{}\n",
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
"-".repeat(context.section_name.len()) "-".repeat(context.section_name.len())
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
Location::new( Location::new(
docstring.expr.location.row() docstring.expr.location.row()
@ -1063,20 +1063,20 @@ fn blanks_and_section_underline(
), ),
)); ));
}; };
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
if checker.settings.enabled.contains(&RuleCode::D215) { if checker.settings.enabled.contains(&RuleCode::D215) {
let leading_space = whitespace::leading_space(non_empty_line); let leading_space = whitespace::leading_space(non_empty_line);
if leading_space.len() > docstring.indentation.len() { if leading_space.len() > docstring.indentation.len() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::SectionUnderlineNotOverIndented(context.section_name.to_string()), violations::SectionUnderlineNotOverIndented(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Replace the existing indentation with whitespace of the appropriate length. // Replace the existing indentation with whitespace of the appropriate length.
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new( Location::new(
docstring.expr.location.row() docstring.expr.location.row()
@ -1094,7 +1094,7 @@ fn blanks_and_section_underline(
), ),
)); ));
}; };
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -1117,15 +1117,15 @@ fn blanks_and_section_underline(
} }
} else { } else {
if checker.settings.enabled.contains(&RuleCode::D412) { if checker.settings.enabled.contains(&RuleCode::D412) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoBlankLinesBetweenHeaderAndContent( violations::NoBlankLinesBetweenHeaderAndContent(
context.section_name.to_string(), context.section_name.to_string(),
), ),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete any blank lines between the header and content. // Delete any blank lines between the header and content.
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
docstring.expr.location.row() docstring.expr.location.row()
+ context.original_index + context.original_index
@ -1143,7 +1143,7 @@ fn blanks_and_section_underline(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -1157,18 +1157,18 @@ fn blanks_and_section_underline(
} }
} else { } else {
if checker.settings.enabled.contains(&RuleCode::D407) { if checker.settings.enabled.contains(&RuleCode::D407) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DashedUnderlineAfterSection(context.section_name.to_string()), violations::DashedUnderlineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Add a dashed line (of the appropriate length) under the section header. // Add a dashed line (of the appropriate length) under the section header.
let content = format!( let content = format!(
"{}{}\n", "{}{}\n",
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
"-".repeat(context.section_name.len()) "-".repeat(context.section_name.len())
); );
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
content, content,
Location::new( Location::new(
docstring.expr.location.row() + context.original_index + 1, docstring.expr.location.row() + context.original_index + 1,
@ -1176,19 +1176,19 @@ fn blanks_and_section_underline(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
if blank_lines_after_header > 0 { if blank_lines_after_header > 0 {
if checker.settings.enabled.contains(&RuleCode::D412) { if checker.settings.enabled.contains(&RuleCode::D412) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NoBlankLinesBetweenHeaderAndContent( violations::NoBlankLinesBetweenHeaderAndContent(
context.section_name.to_string(), context.section_name.to_string(),
), ),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete any blank lines between the header and content. // Delete any blank lines between the header and content.
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
docstring.expr.location.row() + context.original_index + 1, docstring.expr.location.row() + context.original_index + 1,
0, 0,
@ -1202,7 +1202,7 @@ fn blanks_and_section_underline(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -1221,18 +1221,18 @@ fn common_section(
.section_names() .section_names()
.contains(capitalized_section_name.as_str()) .contains(capitalized_section_name.as_str())
{ {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::CapitalizeSectionName(context.section_name.to_string()), violations::CapitalizeSectionName(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Replace the section title with the capitalized variant. This requires // Replace the section title with the capitalized variant. This requires
// locating the start and end of the section name. // locating the start and end of the section name.
if let Some(index) = context.line.find(context.section_name) { if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters. // Map from bytes to characters.
let section_name_start = &context.line[..index].chars().count(); let section_name_start = &context.line[..index].chars().count();
let section_name_length = &context.section_name.chars().count(); let section_name_length = &context.section_name.chars().count();
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
capitalized_section_name, capitalized_section_name,
Location::new( Location::new(
docstring.expr.location.row() + context.original_index, docstring.expr.location.row() + context.original_index,
@ -1245,7 +1245,7 @@ fn common_section(
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -1253,13 +1253,13 @@ fn common_section(
if checker.settings.enabled.contains(&RuleCode::D214) { if checker.settings.enabled.contains(&RuleCode::D214) {
let leading_space = whitespace::leading_space(context.line); let leading_space = whitespace::leading_space(context.line);
if leading_space.len() > docstring.indentation.len() { if leading_space.len() > docstring.indentation.len() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::SectionNotOverIndented(context.section_name.to_string()), violations::SectionNotOverIndented(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Replace the existing indentation with whitespace of the appropriate length. // Replace the existing indentation with whitespace of the appropriate length.
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + context.original_index, 0), Location::new(docstring.expr.location.row() + context.original_index, 0),
Location::new( Location::new(
@ -1268,7 +1268,7 @@ fn common_section(
), ),
)); ));
}; };
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -1279,13 +1279,13 @@ fn common_section(
{ {
if context.is_last_section { if context.is_last_section {
if checker.settings.enabled.contains(&RuleCode::D413) { if checker.settings.enabled.contains(&RuleCode::D413) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::BlankLineAfterLastSection(context.section_name.to_string()), violations::BlankLineAfterLastSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Add a newline after the section. // Add a newline after the section.
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
"\n".to_string(), "\n".to_string(),
Location::new( Location::new(
docstring.expr.location.row() docstring.expr.location.row()
@ -1296,17 +1296,17 @@ fn common_section(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} else { } else {
if checker.settings.enabled.contains(&RuleCode::D410) { if checker.settings.enabled.contains(&RuleCode::D410) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::BlankLineAfterSection(context.section_name.to_string()), violations::BlankLineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Add a newline after the section. // Add a newline after the section.
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
"\n".to_string(), "\n".to_string(),
Location::new( Location::new(
docstring.expr.location.row() docstring.expr.location.row()
@ -1317,25 +1317,25 @@ fn common_section(
), ),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
if checker.settings.enabled.contains(&RuleCode::D411) { if checker.settings.enabled.contains(&RuleCode::D411) {
if !context.previous_line.is_empty() { if !context.previous_line.is_empty() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::BlankLineBeforeSection(context.section_name.to_string()), violations::BlankLineBeforeSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Add a blank line before the section. // Add a blank line before the section.
check.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
"\n".to_string(), "\n".to_string(),
Location::new(docstring.expr.location.row() + context.original_index, 0), Location::new(docstring.expr.location.row() + context.original_index, 0),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -1513,11 +1513,11 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
.strip_prefix(context.section_name) .strip_prefix(context.section_name)
.unwrap(); .unwrap();
if !suffix.is_empty() { if !suffix.is_empty() {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NewLineAfterSectionName(context.section_name.to_string()), violations::NewLineAfterSectionName(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Delete the suffix. This requires locating the end of the section name. // Delete the suffix. This requires locating the end of the section name.
if let Some(index) = context.line.find(context.section_name) { if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters. // Map from bytes to characters.
@ -1525,7 +1525,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
.chars() .chars()
.count(); .count();
let suffix_length = suffix.chars().count(); let suffix_length = suffix.chars().count();
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
docstring.expr.location.row() + context.original_index, docstring.expr.location.row() + context.original_index,
*suffix_start, *suffix_start,
@ -1537,7 +1537,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
@ -1559,11 +1559,11 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
.strip_prefix(context.section_name) .strip_prefix(context.section_name)
.unwrap(); .unwrap();
if suffix != ":" { if suffix != ":" {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::SectionNameEndsInColon(context.section_name.to_string()), violations::SectionNameEndsInColon(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
// Replace the suffix. This requires locating the end of the section name. // Replace the suffix. This requires locating the end of the section name.
if let Some(index) = context.line.find(context.section_name) { if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters. // Map from bytes to characters.
@ -1571,7 +1571,7 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
.chars() .chars()
.count(); .count();
let suffix_length = suffix.chars().count(); let suffix_length = suffix.chars().count();
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
":".to_string(), ":".to_string(),
Location::new( Location::new(
docstring.expr.location.row() + context.original_index, docstring.expr.location.row() + context.original_index,
@ -1584,7 +1584,7 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -6,7 +6,7 @@ use crate::pyflakes::checks;
/// F631 /// F631
pub fn assert_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) { pub fn assert_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) {
if let Some(check) = checks::assert_tuple(test, Range::from_located(stmt)) { if let Some(diagnostic) = checks::assert_tuple(test, Range::from_located(stmt)) {
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -13,14 +13,14 @@ pub fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checker: &mut
.any(|value| matches!(value.node, ExprKind::FormattedValue { .. })) .any(|value| matches!(value.node, ExprKind::FormattedValue { .. }))
{ {
for (prefix_range, tok_range) in find_useless_f_strings(expr, checker.locator) { for (prefix_range, tok_range) in find_useless_f_strings(expr, checker.locator) {
let mut check = Diagnostic::new(violations::FStringMissingPlaceholders, tok_range); let mut diagnostic = Diagnostic::new(violations::FStringMissingPlaceholders, tok_range);
if checker.patch(&RuleCode::F541) { if checker.patch(&RuleCode::F541) {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
prefix_range.location, prefix_range.location,
prefix_range.end_location, prefix_range.end_location,
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -6,7 +6,7 @@ use crate::pyflakes::checks;
/// F634 /// F634
pub fn if_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) { pub fn if_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) {
if let Some(check) = checks::if_tuple(test, Range::from_located(stmt)) { if let Some(diagnostic) = checks::if_tuple(test, Range::from_located(stmt)) {
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -25,8 +25,8 @@ pub fn invalid_literal_comparison(
&& (helpers::is_constant_non_singleton(left) && (helpers::is_constant_non_singleton(left)
|| helpers::is_constant_non_singleton(right)) || helpers::is_constant_non_singleton(right))
{ {
let mut check = Diagnostic::new(violations::IsLiteral(op.into()), location); let mut diagnostic = Diagnostic::new(violations::IsLiteral(op.into()), location);
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(located_op) = &located.get(index) { if let Some(located_op) = &located.get(index) {
assert_eq!(&located_op.node, op); assert_eq!(&located_op.node, op);
if let Some(content) = match &located_op.node { if let Some(content) = match &located_op.node {
@ -37,7 +37,7 @@ pub fn invalid_literal_comparison(
None None
} }
} { } {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
helpers::to_absolute(located_op.location, location.location), helpers::to_absolute(located_op.location, location.location),
helpers::to_absolute( helpers::to_absolute(
@ -50,7 +50,7 @@ pub fn invalid_literal_comparison(
eprintln!("Failed to fix invalid comparison due to missing op"); eprintln!("Failed to fix invalid comparison due to missing op");
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
left = right; left = right;
} }

View File

@ -30,13 +30,14 @@ pub fn raise_not_implemented(checker: &mut Checker, expr: &Expr) {
let Some(expr) = match_not_implemented(expr) else { let Some(expr) = match_not_implemented(expr) else {
return; return;
}; };
let mut check = Diagnostic::new(violations::RaiseNotImplemented, Range::from_located(expr)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::RaiseNotImplemented, Range::from_located(expr));
check.amend(Fix::replacement( if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
"NotImplementedError".to_string(), "NotImplementedError".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -40,7 +40,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
if checker.settings.enabled.contains(&RuleCode::F601) { if checker.settings.enabled.contains(&RuleCode::F601) {
let comparable_value: ComparableExpr = (&values[i]).into(); let comparable_value: ComparableExpr = (&values[i]).into();
let is_duplicate_value = seen_values.contains(&comparable_value); let is_duplicate_value = seen_values.contains(&comparable_value);
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::MultiValueRepeatedKeyLiteral( violations::MultiValueRepeatedKeyLiteral(
unparse_expr(&keys[i], checker.style), unparse_expr(&keys[i], checker.style),
is_duplicate_value, is_duplicate_value,
@ -49,7 +49,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
); );
if is_duplicate_value { if is_duplicate_value {
if checker.patch(&RuleCode::F601) { if checker.patch(&RuleCode::F601) {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
values[i - 1].end_location.unwrap(), values[i - 1].end_location.unwrap(),
values[i].end_location.unwrap(), values[i].end_location.unwrap(),
)); ));
@ -57,14 +57,14 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
} else { } else {
seen_values.insert(comparable_value); seen_values.insert(comparable_value);
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
DictionaryKey::Variable(key) => { DictionaryKey::Variable(key) => {
if checker.settings.enabled.contains(&RuleCode::F602) { if checker.settings.enabled.contains(&RuleCode::F602) {
let comparable_value: ComparableExpr = (&values[i]).into(); let comparable_value: ComparableExpr = (&values[i]).into();
let is_duplicate_value = seen_values.contains(&comparable_value); let is_duplicate_value = seen_values.contains(&comparable_value);
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::MultiValueRepeatedKeyVariable( violations::MultiValueRepeatedKeyVariable(
key.to_string(), key.to_string(),
is_duplicate_value, is_duplicate_value,
@ -73,7 +73,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
); );
if is_duplicate_value { if is_duplicate_value {
if checker.patch(&RuleCode::F602) { if checker.patch(&RuleCode::F602) {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
values[i - 1].end_location.unwrap(), values[i - 1].end_location.unwrap(),
values[i].end_location.unwrap(), values[i].end_location.unwrap(),
)); ));
@ -81,7 +81,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
} else { } else {
seen_values.insert(comparable_value); seen_values.insert(comparable_value);
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -110,21 +110,21 @@ pub(crate) fn percent_format_extra_named_arguments(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::PercentFormatExtraNamedArguments( violations::PercentFormatExtraNamedArguments(
missing.iter().map(|&arg| arg.to_string()).collect(), missing.iter().map(|&arg| arg.to_string()).collect(),
), ),
location, location,
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
match remove_unused_format_arguments_from_dict(&missing, right, checker.locator) { match remove_unused_format_arguments_from_dict(&missing, right, checker.locator) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to remove unused format arguments: {e}"), Err(e) => error!("Failed to remove unused format arguments: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// F505 /// F505
@ -268,22 +268,22 @@ pub(crate) fn string_dot_format_extra_named_arguments(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::StringDotFormatExtraNamedArguments( violations::StringDotFormatExtraNamedArguments(
missing.iter().map(|&arg| arg.to_string()).collect(), missing.iter().map(|&arg| arg.to_string()).collect(),
), ),
location, location,
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
match remove_unused_keyword_arguments_from_format_call(&missing, location, checker.locator) match remove_unused_keyword_arguments_from_format_call(&missing, location, checker.locator)
{ {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to remove unused keyword arguments: {e}"), Err(e) => error!("Failed to remove unused keyword arguments: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// F523 /// F523

View File

@ -169,7 +169,7 @@ pub fn unused_variable(checker: &mut Checker, scope: usize) {
&& name != &"__traceback_info__" && name != &"__traceback_info__"
&& name != &"__traceback_supplement__" && name != &"__traceback_supplement__"
{ {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnusedVariable((*name).to_string()), violations::UnusedVariable((*name).to_string()),
binding.range, binding.range,
); );
@ -180,11 +180,11 @@ pub fn unused_variable(checker: &mut Checker, scope: usize) {
if matches!(kind, DeletionKind::Whole) { if matches!(kind, DeletionKind::Whole) {
checker.deletions.insert(RefEquality(stmt)); checker.deletions.insert(RefEquality(stmt));
} }
check.amend(fix); diagnostic.amend(fix);
} }
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -40,16 +40,16 @@ pub fn misplaced_comparison_constant(
_ => unreachable!("Expected comparison operator"), _ => unreachable!("Expected comparison operator"),
}; };
let suggestion = format!("{right} {reversed_op} {left}"); let suggestion = format!("{right} {reversed_op} {left}");
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::MisplacedComparisonConstant(suggestion.clone()), violations::MisplacedComparisonConstant(suggestion.clone()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
suggestion, suggestion,
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -75,19 +75,19 @@ pub fn use_sys_exit(checker: &mut Checker, func: &Expr) {
if !checker.is_builtin(name) { if !checker.is_builtin(name) {
continue; continue;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UseSysExit(name.to_string()), violations::UseSysExit(name.to_string()),
Range::from_located(func), Range::from_located(func),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(content) = get_member_import_name_alias(checker, "sys", "exit") { if let Some(content) = get_member_import_name_alias(checker, "sys", "exit") {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
func.location, func.location,
func.end_location.unwrap(), func.end_location.unwrap(),
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -17,13 +17,14 @@ pub fn useless_import_alias(checker: &mut Checker, alias: &Alias) {
return; return;
} }
let mut check = Diagnostic::new(violations::UselessImportAlias, Range::from_located(alias)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::UselessImportAlias, Range::from_located(alias));
check.amend(Fix::replacement( if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
asname.to_string(), asname.to_string(),
alias.location, alias.location,
alias.end_location.unwrap(), alias.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -176,17 +176,17 @@ static CODING_COMMENT_REGEX: Lazy<Regex> =
pub fn unnecessary_coding_comment(lineno: usize, line: &str, autofix: bool) -> Option<Diagnostic> { pub fn unnecessary_coding_comment(lineno: usize, line: &str, autofix: bool) -> Option<Diagnostic> {
// PEP3120 makes utf-8 the default encoding. // PEP3120 makes utf-8 the default encoding.
if CODING_COMMENT_REGEX.is_match(line) { if CODING_COMMENT_REGEX.is_match(line) {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::PEP3120UnnecessaryCodingComment, violations::PEP3120UnnecessaryCodingComment,
Range::new(Location::new(lineno + 1, 0), Location::new(lineno + 2, 0)), Range::new(Location::new(lineno + 1, 0), Location::new(lineno + 2, 0)),
); );
if autofix { if autofix {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(lineno + 1, 0), Location::new(lineno + 1, 0),
Location::new(lineno + 2, 0), Location::new(lineno + 2, 0),
)); ));
} }
Some(check) Some(diagnostic)
} else { } else {
None None
} }

View File

@ -157,16 +157,16 @@ pub fn convert_named_tuple_functional_to_class(
{ {
return; return;
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ConvertNamedTupleFunctionalToClass(typename.to_string()), violations::ConvertNamedTupleFunctionalToClass(typename.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
match match_defaults(keywords) match match_defaults(keywords)
.and_then(|defaults| create_properties_from_args(args, defaults)) .and_then(|defaults| create_properties_from_args(args, defaults))
{ {
Ok(properties) => { Ok(properties) => {
check.amend(convert_to_class( diagnostic.amend(convert_to_class(
stmt, stmt,
typename, typename,
properties, properties,
@ -177,5 +177,5 @@ pub fn convert_named_tuple_functional_to_class(
Err(err) => debug!("Skipping ineligible `NamedTuple` \"{typename}\": {err}"), Err(err) => debug!("Skipping ineligible `NamedTuple` \"{typename}\": {err}"),
}; };
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -200,14 +200,14 @@ pub fn convert_typed_dict_functional_to_class(
return; return;
}; };
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::ConvertTypedDictFunctionalToClass(class_name.to_string()), violations::ConvertTypedDictFunctionalToClass(class_name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
match match_properties_and_total(args, keywords) { match match_properties_and_total(args, keywords) {
Ok((body, total_keyword)) => { Ok((body, total_keyword)) => {
check.amend(convert_to_class( diagnostic.amend(convert_to_class(
stmt, stmt,
class_name, class_name,
body, body,
@ -219,5 +219,5 @@ pub fn convert_typed_dict_functional_to_class(
Err(err) => debug!("Skipping ineligible `TypedDict` \"{class_name}\": {err}"), Err(err) => debug!("Skipping ineligible `TypedDict` \"{class_name}\": {err}"),
}; };
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -11,9 +11,10 @@ use crate::violations;
pub fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) { pub fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) {
let dealiased_call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases); let dealiased_call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases);
if dealiased_call_path == ["datetime", "timezone", "utc"] { if dealiased_call_path == ["datetime", "timezone", "utc"] {
let mut check = Diagnostic::new(violations::DatetimeTimezoneUTC, Range::from_located(expr)); let mut diagnostic =
Diagnostic::new(violations::DatetimeTimezoneUTC, Range::from_located(expr));
if checker.patch(&RuleCode::UP017) { if checker.patch(&RuleCode::UP017) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
compose_call_path(expr) compose_call_path(expr)
.unwrap() .unwrap()
.replace("timezone.utc", "UTC"), .replace("timezone.utc", "UTC"),
@ -21,6 +22,6 @@ pub fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) {
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -42,16 +42,16 @@ pub fn deprecated_unittest_alias(checker: &mut Checker, expr: &Expr) {
if id != "self" { if id != "self" {
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::DeprecatedUnittestAlias(attr.to_string(), target.to_string()), violations::DeprecatedUnittestAlias(attr.to_string(), target.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("self.{target}"), format!("self.{target}"),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -25,13 +25,13 @@ pub fn native_literals(
if (id == "str" || id == "bytes") && checker.is_builtin(id) { if (id == "str" || id == "bytes") && checker.is_builtin(id) {
let Some(arg) = args.get(0) else { let Some(arg) = args.get(0) else {
let mut check = Diagnostic::new(violations::NativeLiterals(if id == "str" { let mut diagnostic = Diagnostic::new(violations::NativeLiterals(if id == "str" {
LiteralType::Str LiteralType::Str
} else { } else {
LiteralType::Bytes LiteralType::Bytes
}), Range::from_located(expr)); }), Range::from_located(expr));
if checker.patch(&RuleCode::UP018) { if checker.patch(&RuleCode::UP018) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
if id == "bytes" { if id == "bytes" {
let mut content = String::with_capacity(3); let mut content = String::with_capacity(3);
content.push('b'); content.push('b');
@ -48,7 +48,7 @@ pub fn native_literals(
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
return; return;
}; };
@ -93,7 +93,7 @@ pub fn native_literals(
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::NativeLiterals(if id == "str" { violations::NativeLiterals(if id == "str" {
LiteralType::Str LiteralType::Str
} else { } else {
@ -102,12 +102,12 @@ pub fn native_literals(
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(&RuleCode::UP018) { if checker.patch(&RuleCode::UP018) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
arg_code.to_string(), arg_code.to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -12,14 +12,14 @@ pub fn open_alias(checker: &mut Checker, expr: &Expr, func: &Expr) {
let call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases); let call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases);
if match_call_path(&call_path, "io", "open", &checker.from_imports) { if match_call_path(&call_path, "io", "open", &checker.from_imports) {
let mut check = Diagnostic::new(violations::OpenAlias, Range::from_located(expr)); let mut diagnostic = Diagnostic::new(violations::OpenAlias, Range::from_located(expr));
if checker.patch(&RuleCode::UP020) { if checker.patch(&RuleCode::UP020) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"open".to_string(), "open".to_string(),
func.location, func.location,
func.end_location.unwrap(), func.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -158,15 +158,16 @@ fn handle_making_changes(
final_str.insert(0, '('); final_str.insert(0, '(');
final_str.push(')'); final_str.push(')');
} }
let mut check = Diagnostic::new(violations::OSErrorAlias(compose_call_path(target)), range); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::OSErrorAlias(compose_call_path(target)), range);
check.amend(Fix::replacement( if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
final_str, final_str,
range.location, range.location,
range.end_location, range.end_location,
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -80,13 +80,13 @@ fn create_check(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
patch: bool, patch: bool,
) -> Diagnostic { ) -> Diagnostic {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::RedundantOpenModes(replacement_value.clone()), violations::RedundantOpenModes(replacement_value.clone()),
Range::from_located(expr), Range::from_located(expr),
); );
if patch { if patch {
if let Some(content) = replacement_value { if let Some(content) = replacement_value {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
mode_param.location, mode_param.location,
mode_param.end_location.unwrap(), mode_param.end_location.unwrap(),
@ -94,13 +94,13 @@ fn create_check(
} else { } else {
match create_remove_param_fix(locator, expr, mode_param) { match create_remove_param_fix(locator, expr, mode_param) {
Ok(fix) => { Ok(fix) => {
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to remove parameter: {e}"), Err(e) => error!("Failed to remove parameter: {e}"),
} }
} }
} }
check diagnostic
} }
fn create_remove_param_fix( fn create_remove_param_fix(

View File

@ -35,15 +35,16 @@ fn map_name(name: &str, expr: &Expr, patch: bool) -> Option<Diagnostic> {
_ => None, _ => None,
}; };
if let Some(replacement) = replacement { if let Some(replacement) = replacement {
let mut check = Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr)); let mut diagnostic =
Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr));
if patch { if patch {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
replacement.to_string(), replacement.to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
Some(check) Some(diagnostic)
} else { } else {
None None
} }
@ -58,7 +59,8 @@ fn replace_by_str_literal(
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
match &arg.node { match &arg.node {
ExprKind::Constant { .. } => { ExprKind::Constant { .. } => {
let mut check = Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr)); let mut diagnostic =
Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr));
if patch { if patch {
let content = format!( let content = format!(
"{}{}", "{}{}",
@ -68,13 +70,13 @@ fn replace_by_str_literal(
arg.end_location.unwrap(), arg.end_location.unwrap(),
)) ))
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
}; };
Some(check) Some(diagnostic)
} }
_ => None, _ => None,
} }
@ -132,17 +134,17 @@ fn replace_by_expr_kind(
patch: bool, patch: bool,
stylist: &SourceCodeStyleDetector, stylist: &SourceCodeStyleDetector,
) -> Diagnostic { ) -> Diagnostic {
let mut check = Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr)); let mut diagnostic = Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr));
if patch { if patch {
let mut generator: SourceCodeGenerator = stylist.into(); let mut generator: SourceCodeGenerator = stylist.into();
generator.unparse_expr(&create_expr(node), 0); generator.unparse_expr(&create_expr(node), 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
check diagnostic
} }
fn replace_by_stmt_kind( fn replace_by_stmt_kind(
@ -151,17 +153,17 @@ fn replace_by_stmt_kind(
patch: bool, patch: bool,
stylist: &SourceCodeStyleDetector, stylist: &SourceCodeStyleDetector,
) -> Diagnostic { ) -> Diagnostic {
let mut check = Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr)); let mut diagnostic = Diagnostic::new(violations::RemoveSixCompat, Range::from_located(expr));
if patch { if patch {
let mut generator: SourceCodeGenerator = stylist.into(); let mut generator: SourceCodeGenerator = stylist.into();
generator.unparse_stmt(&create_stmt(node)); generator.unparse_stmt(&create_stmt(node));
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
check diagnostic
} }
// => `raise exc from cause` // => `raise exc from cause`
@ -411,15 +413,17 @@ fn handle_next_on_six_dict(expr: &Expr, patch: bool, checker: &Checker) -> Optio
/// UP016 /// UP016
pub fn remove_six_compat(checker: &mut Checker, expr: &Expr) { pub fn remove_six_compat(checker: &mut Checker, expr: &Expr) {
if let Some(check) = handle_next_on_six_dict(expr, checker.patch(&RuleCode::UP016), checker) { if let Some(diagnostic) =
checker.diagnostics.push(check); handle_next_on_six_dict(expr, checker.patch(&RuleCode::UP016), checker)
{
checker.diagnostics.push(diagnostic);
return; return;
} }
let call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases); let call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases);
if is_module_member(&call_path, "six") { if is_module_member(&call_path, "six") {
let patch = checker.patch(&RuleCode::UP016); let patch = checker.patch(&RuleCode::UP016);
let check = match &expr.node { let diagnostic = match &expr.node {
ExprKind::Call { ExprKind::Call {
func, func,
args, args,
@ -437,8 +441,8 @@ pub fn remove_six_compat(checker: &mut Checker, expr: &Expr) {
ExprKind::Name { id, .. } => map_name(id.as_str(), expr, patch), ExprKind::Name { id, .. } => map_name(id.as_str(), expr, patch),
_ => return, _ => return,
}; };
if let Some(check) = check { if let Some(diagnostic) = diagnostic {
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -75,8 +75,9 @@ pub fn replace_stdout_stderr(checker: &mut Checker, expr: &Expr, kwargs: &[Keywo
return; return;
} }
let mut check = Diagnostic::new(violations::ReplaceStdoutStderr, Range::from_located(expr)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::ReplaceStdoutStderr, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
let first = if stdout.location < stderr.location { let first = if stdout.location < stderr.location {
stdout stdout
} else { } else {
@ -104,12 +105,12 @@ pub fn replace_stdout_stderr(checker: &mut Checker, expr: &Expr, kwargs: &[Keywo
} }
contents.push_str(middle.contents); contents.push_str(middle.contents);
} }
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
contents, contents,
first.location, first.location,
last.end_location.unwrap(), last.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -24,14 +24,14 @@ pub fn replace_universal_newlines(checker: &mut Checker, expr: &Expr, kwargs: &[
kwarg.location.column() + "universal_newlines".len(), kwarg.location.column() + "universal_newlines".len(),
), ),
); );
let mut check = Diagnostic::new(violations::ReplaceUniversalNewlines, range); let mut diagnostic = Diagnostic::new(violations::ReplaceUniversalNewlines, range);
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"text".to_string(), "text".to_string(),
range.location, range.location,
range.end_location, range.end_location,
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -7,18 +7,19 @@ use crate::registry::Diagnostic;
use crate::violations; use crate::violations;
fn add_check_for_node<T>(checker: &mut Checker, node: &Located<T>) { fn add_check_for_node<T>(checker: &mut Checker, node: &Located<T>) {
let mut check = Diagnostic::new(violations::RewriteCElementTree, Range::from_located(node)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::RewriteCElementTree, Range::from_located(node));
if checker.patch(diagnostic.kind.code()) {
let contents = checker let contents = checker
.locator .locator
.slice_source_code_range(&Range::from_located(node)); .slice_source_code_range(&Range::from_located(node));
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
contents.replacen("cElementTree", "ElementTree", 1), contents.replacen("cElementTree", "ElementTree", 1),
node.location, node.location,
node.end_location.unwrap(), node.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
/// UP023 /// UP023

View File

@ -205,18 +205,18 @@ fn format_import_from(
pub fn rewrite_mock_attribute(checker: &mut Checker, expr: &Expr) { pub fn rewrite_mock_attribute(checker: &mut Checker, expr: &Expr) {
if let ExprKind::Attribute { value, .. } = &expr.node { if let ExprKind::Attribute { value, .. } = &expr.node {
if collect_call_paths(value) == ["mock", "mock"] { if collect_call_paths(value) == ["mock", "mock"] {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::RewriteMockImport(MockReference::Attribute), violations::RewriteMockImport(MockReference::Attribute),
Range::from_located(value), Range::from_located(value),
); );
if checker.patch(&RuleCode::UP026) { if checker.patch(&RuleCode::UP026) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"mock".to_string(), "mock".to_string(),
value.location, value.location,
value.end_location.unwrap(), value.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -247,18 +247,18 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) {
// Add a `Diagnostic` for each `mock` import. // Add a `Diagnostic` for each `mock` import.
for name in names { for name in names {
if name.node.name == "mock" || name.node.name == "mock.mock" { if name.node.name == "mock" || name.node.name == "mock.mock" {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::RewriteMockImport(MockReference::Import), violations::RewriteMockImport(MockReference::Import),
Range::from_located(name), Range::from_located(name),
); );
if let Some(content) = content.as_ref() { if let Some(content) = content.as_ref() {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content.clone(), content.clone(),
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -273,7 +273,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) {
} }
if module == "mock" { if module == "mock" {
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::RewriteMockImport(MockReference::Import), violations::RewriteMockImport(MockReference::Import),
Range::from_located(stmt), Range::from_located(stmt),
); );
@ -281,7 +281,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) {
let indent = indentation(checker, stmt); let indent = indentation(checker, stmt);
match format_import_from(stmt, &indent, checker.locator, checker.style) { match format_import_from(stmt, &indent, checker.locator, checker.style) {
Ok(content) => { Ok(content) => {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
stmt.location, stmt.location,
stmt.end_location.unwrap(), stmt.end_location.unwrap(),
@ -290,7 +290,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) {
Err(e) => error!("Failed to rewrite `mock` import: {e}"), Err(e) => error!("Failed to rewrite `mock` import: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
_ => (), _ => (),

View File

@ -10,15 +10,15 @@ use crate::violations;
pub fn rewrite_unicode_literal(checker: &mut Checker, expr: &Expr, kind: Option<&str>) { pub fn rewrite_unicode_literal(checker: &mut Checker, expr: &Expr, kind: Option<&str>) {
if let Some(const_kind) = kind { if let Some(const_kind) = kind {
if const_kind.to_lowercase() == "u" { if const_kind.to_lowercase() == "u" {
let mut check = let mut diagnostic =
Diagnostic::new(violations::RewriteUnicodeLiteral, Range::from_located(expr)); Diagnostic::new(violations::RewriteUnicodeLiteral, Range::from_located(expr));
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
expr.location, expr.location,
Location::new(expr.location.row(), expr.location.column() + 1), Location::new(expr.location.row(), expr.location.column() + 1),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -157,20 +157,20 @@ pub fn rewrite_yield_from(checker: &mut Checker, stmt: &Stmt) {
continue; continue;
} }
let mut check = let mut diagnostic =
Diagnostic::new(violations::RewriteYieldFrom, Range::from_located(item.stmt)); Diagnostic::new(violations::RewriteYieldFrom, Range::from_located(item.stmt));
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let contents = checker let contents = checker
.locator .locator
.slice_source_code_range(&Range::from_located(item.iter)); .slice_source_code_range(&Range::from_located(item.iter));
let contents = format!("yield from {contents}"); let contents = format!("yield from {contents}");
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
contents, contents,
item.stmt.location, item.stmt.location,
item.stmt.end_location.unwrap(), item.stmt.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -18,13 +18,13 @@ pub fn super_call_with_parameters(checker: &mut Checker, expr: &Expr, func: &Exp
.iter() .iter()
.map(std::convert::Into::into) .map(std::convert::Into::into)
.collect(); .collect();
let Some(mut check) = checks::super_args(scope, &parents, expr, func, args) else { let Some(mut diagnostic) = checks::super_args(scope, &parents, expr, func, args) else {
return; return;
}; };
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(fix) = pyupgrade::fixes::remove_super_arguments(checker.locator, expr) { if let Some(fix) = pyupgrade::fixes::remove_super_arguments(checker.locator, expr) {
check.amend(fix); diagnostic.amend(fix);
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -9,18 +9,19 @@ use crate::violations;
/// UP003 /// UP003
pub fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { pub fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) {
let Some(mut check) = checks::type_of_primitive(func, args, Range::from_located(expr)) else { let Some(mut diagnostic) = checks::type_of_primitive(func, args, Range::from_located(expr)) else {
return; return;
}; };
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let DiagnosticKind::TypeOfPrimitive(violations::TypeOfPrimitive(primitive)) = &check.kind if let DiagnosticKind::TypeOfPrimitive(violations::TypeOfPrimitive(primitive)) =
&diagnostic.kind
{ {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
primitive.builtin(), primitive.builtin(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -16,14 +16,15 @@ pub fn typing_text_str_alias(checker: &mut Checker, expr: &Expr) {
&checker.from_imports, &checker.from_imports,
&checker.import_aliases, &checker.import_aliases,
) { ) {
let mut check = Diagnostic::new(violations::TypingTextStrAlias, Range::from_located(expr)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::TypingTextStrAlias, Range::from_located(expr));
check.amend(Fix::replacement( if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
"str".to_string(), "str".to_string(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -68,7 +68,7 @@ pub fn unnecessary_builtin_import(
if unused_imports.is_empty() { if unused_imports.is_empty() {
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryBuiltinImport( violations::UnnecessaryBuiltinImport(
unused_imports unused_imports
.iter() .iter()
@ -79,7 +79,7 @@ pub fn unnecessary_builtin_import(
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let deleted: Vec<&Stmt> = checker let deleted: Vec<&Stmt> = checker
.deletions .deletions
.iter() .iter()
@ -102,10 +102,10 @@ pub fn unnecessary_builtin_import(
if fix.content.is_empty() || fix.content == "pass" { if fix.content.is_empty() || fix.content == "pass" {
checker.deletions.insert(defined_by.clone()); checker.deletions.insert(defined_by.clone());
} }
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to remove builtin import: {e}"), Err(e) => error!("Failed to remove builtin import: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -60,19 +60,19 @@ fn delete_default_encode_arg_or_kwarg(
patch: bool, patch: bool,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
if let Some(arg) = args.get(0) { if let Some(arg) = args.get(0) {
let mut check = let mut diagnostic =
Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr)); Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr));
if patch { if patch {
check.amend(Fix::deletion(arg.location, arg.end_location.unwrap())); diagnostic.amend(Fix::deletion(arg.location, arg.end_location.unwrap()));
} }
Some(check) Some(diagnostic)
} else if let Some(kwarg) = kwargs.get(0) { } else if let Some(kwarg) = kwargs.get(0) {
let mut check = let mut diagnostic =
Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr)); Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr));
if patch { if patch {
check.amend(Fix::deletion(kwarg.location, kwarg.end_location.unwrap())); diagnostic.amend(Fix::deletion(kwarg.location, kwarg.end_location.unwrap()));
} }
Some(check) Some(diagnostic)
} else { } else {
None None
} }
@ -85,7 +85,8 @@ fn replace_with_bytes_literal(
locator: &SourceCodeLocator, locator: &SourceCodeLocator,
patch: bool, patch: bool,
) -> Diagnostic { ) -> Diagnostic {
let mut check = Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr)); let mut diagnostic =
Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr));
if patch { if patch {
let content = locator.slice_source_code_range(&Range::new( let content = locator.slice_source_code_range(&Range::new(
constant.location, constant.location,
@ -95,13 +96,13 @@ fn replace_with_bytes_literal(
"b{}", "b{}",
content.trim_start_matches('u').trim_start_matches('U') content.trim_start_matches('u').trim_start_matches('U')
); );
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
check diagnostic
} }
/// UP012 /// UP012
@ -133,13 +134,13 @@ pub fn unnecessary_encode_utf8(
)); ));
} else { } else {
// "unicode text©".encode("utf-8") // "unicode text©".encode("utf-8")
if let Some(check) = delete_default_encode_arg_or_kwarg( if let Some(diagnostic) = delete_default_encode_arg_or_kwarg(
expr, expr,
args, args,
kwargs, kwargs,
checker.patch(&RuleCode::UP012), checker.patch(&RuleCode::UP012),
) { ) {
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }
@ -147,13 +148,13 @@ pub fn unnecessary_encode_utf8(
// f"foo{bar}".encode(*args, **kwargs) // f"foo{bar}".encode(*args, **kwargs)
ExprKind::JoinedStr { .. } => { ExprKind::JoinedStr { .. } => {
if is_default_encode(args, kwargs) { if is_default_encode(args, kwargs) {
if let Some(check) = delete_default_encode_arg_or_kwarg( if let Some(diagnostic) = delete_default_encode_arg_or_kwarg(
expr, expr,
args, args,
kwargs, kwargs,
checker.patch(&RuleCode::UP012), checker.patch(&RuleCode::UP012),
) { ) {
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -53,7 +53,7 @@ pub fn unnecessary_future_import(checker: &mut Checker, stmt: &Stmt, names: &[Lo
if unused_imports.is_empty() { if unused_imports.is_empty() {
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UnnecessaryFutureImport( violations::UnnecessaryFutureImport(
unused_imports unused_imports
.iter() .iter()
@ -64,7 +64,7 @@ pub fn unnecessary_future_import(checker: &mut Checker, stmt: &Stmt, names: &[Lo
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let deleted: Vec<&Stmt> = checker let deleted: Vec<&Stmt> = checker
.deletions .deletions
.iter() .iter()
@ -87,10 +87,10 @@ pub fn unnecessary_future_import(checker: &mut Checker, stmt: &Stmt, names: &[Lo
if fix.content.is_empty() || fix.content == "pass" { if fix.content.is_empty() || fix.content == "pass" {
checker.deletions.insert(defined_by.clone()); checker.deletions.insert(defined_by.clone());
} }
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to remove `__future__` import: {e}"), Err(e) => error!("Failed to remove `__future__` import: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -6,7 +6,7 @@ use crate::pyupgrade::checks;
/// UP011 /// UP011
pub fn unnecessary_lru_cache_params(checker: &mut Checker, decorator_list: &[Expr]) { pub fn unnecessary_lru_cache_params(checker: &mut Checker, decorator_list: &[Expr]) {
let Some(mut check) = checks::unnecessary_lru_cache_params( let Some(mut diagnostic) = checks::unnecessary_lru_cache_params(
decorator_list, decorator_list,
checker.settings.target_version, checker.settings.target_version,
&checker.from_imports, &checker.from_imports,
@ -14,8 +14,8 @@ pub fn unnecessary_lru_cache_params(checker: &mut Checker, decorator_list: &[Exp
) else { ) else {
return; return;
}; };
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::deletion(check.location, check.end_location)); diagnostic.amend(Fix::deletion(diagnostic.location, diagnostic.end_location));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -75,7 +75,7 @@ pub fn unpack_list_comprehension(checker: &mut Checker, targets: &[Expr], value:
return; return;
} }
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::RewriteListComprehension, violations::RewriteListComprehension,
Range::from_located(value), Range::from_located(value),
); );
@ -88,13 +88,13 @@ pub fn unpack_list_comprehension(checker: &mut Checker, targets: &[Expr], value:
content.push('('); content.push('(');
content.push_str(&existing[1..existing.len() - 1]); content.push_str(&existing[1..existing.len() - 1]);
content.push(')'); content.push(')');
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
value.location, value.location,
value.end_location.unwrap(), value.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }
} }

View File

@ -9,16 +9,16 @@ use crate::violations;
/// UP006 /// UP006
pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr, id: &str) { pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr, id: &str) {
let replacement = *checker.import_aliases.get(id).unwrap_or(&id); let replacement = *checker.import_aliases.get(id).unwrap_or(&id);
let mut check = Diagnostic::new( let mut diagnostic = Diagnostic::new(
violations::UsePEP585Annotation(replacement.to_string()), violations::UsePEP585Annotation(replacement.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
replacement.to_lowercase(), replacement.to_lowercase(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -64,20 +64,22 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
let call_path = dealias_call_path(collect_call_paths(value), &checker.import_aliases); let call_path = dealias_call_path(collect_call_paths(value), &checker.import_aliases);
if checker.match_typing_call_path(&call_path, "Optional") { if checker.match_typing_call_path(&call_path, "Optional") {
let mut check = Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&optional(slice), 0); generator.unparse_expr(&optional(slice), 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
)); ));
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} else if checker.match_typing_call_path(&call_path, "Union") { } else if checker.match_typing_call_path(&call_path, "Union") {
let mut check = Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr)); let mut diagnostic =
if checker.patch(check.kind.code()) { Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
match &slice.node { match &slice.node {
ExprKind::Slice { .. } => { ExprKind::Slice { .. } => {
// Invalid type annotation. // Invalid type annotation.
@ -85,7 +87,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
ExprKind::Tuple { elts, .. } => { ExprKind::Tuple { elts, .. } => {
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&union(elts), 0); generator.unparse_expr(&union(elts), 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
@ -95,7 +97,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
// Single argument. // Single argument.
let mut generator: SourceCodeGenerator = checker.style.into(); let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(slice, 0); generator.unparse_expr(slice, 0);
check.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
generator.generate(), generator.generate(),
expr.location, expr.location,
expr.end_location.unwrap(), expr.end_location.unwrap(),
@ -103,6 +105,6 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
} }
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }
} }

View File

@ -8,11 +8,11 @@ use crate::pyupgrade::checks;
/// UP001 /// UP001
pub fn useless_metaclass_type(checker: &mut Checker, stmt: &Stmt, value: &Expr, targets: &[Expr]) { pub fn useless_metaclass_type(checker: &mut Checker, stmt: &Stmt, value: &Expr, targets: &[Expr]) {
let Some(mut check) = let Some(mut diagnostic) =
checks::useless_metaclass_type(targets, value, Range::from_located(stmt)) else { checks::useless_metaclass_type(targets, value, Range::from_located(stmt)) else {
return; return;
}; };
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
let deleted: Vec<&Stmt> = checker let deleted: Vec<&Stmt> = checker
.deletions .deletions
.iter() .iter()
@ -30,10 +30,10 @@ pub fn useless_metaclass_type(checker: &mut Checker, stmt: &Stmt, value: &Expr,
if fix.content.is_empty() || fix.content == "pass" { if fix.content.is_empty() || fix.content == "pass" {
checker.deletions.insert(defined_by.clone()); checker.deletions.insert(defined_by.clone());
} }
check.amend(fix); diagnostic.amend(fix);
} }
Err(e) => error!("Failed to fix remove metaclass type: {e}"), Err(e) => error!("Failed to fix remove metaclass type: {e}"),
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }

View File

@ -12,19 +12,19 @@ pub fn useless_object_inheritance(
bases: &[Expr], bases: &[Expr],
keywords: &[Keyword], keywords: &[Keyword],
) { ) {
let Some(mut check) = checks::useless_object_inheritance(name, bases, checker.current_scope(), &checker.bindings) else { let Some(mut diagnostic) = checks::useless_object_inheritance(name, bases, checker.current_scope(), &checker.bindings) else {
return; return;
}; };
if checker.patch(check.kind.code()) { if checker.patch(diagnostic.kind.code()) {
if let Some(fix) = pyupgrade::fixes::remove_class_def_base( if let Some(fix) = pyupgrade::fixes::remove_class_def_base(
checker.locator, checker.locator,
stmt.location, stmt.location,
check.location, diagnostic.location,
bases, bases,
keywords, keywords,
) { ) {
check.amend(fix); diagnostic.amend(fix);
} }
} }
checker.diagnostics.push(check); checker.diagnostics.push(diagnostic);
} }