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.
pub fn fix_file<'a>(
checks: &'a [Diagnostic],
diagnostics: &'a [Diagnostic],
locator: &'a SourceCodeLocator<'a>,
) -> 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;
}
Some(apply_fixes(
checks.iter().filter_map(|check| check.fix.as_ref()),
diagnostics.iter().filter_map(|check| check.fix.as_ref()),
locator,
))
}

View File

@ -4073,16 +4073,16 @@ impl<'a> Checker<'a> {
let defined_in = self.child_to_parent.get(defined_by);
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 { .. })
&& child.location.row() != check_lineno
&& child.location.row() != diagnostic_lineno
{
Some(child.location.row())
} else {
None
};
if self.is_ignored(&RuleCode::F401, check_lineno)
if self.is_ignored(&RuleCode::F401, diagnostic_lineno)
|| parent_lineno.map_or(false, |parent_lineno| {
self.is_ignored(&RuleCode::F401, parent_lineno)
})

View File

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

View File

@ -14,7 +14,7 @@ use crate::violations::UnusedCodes;
use crate::{noqa, violations};
pub fn check_noqa(
checks: &mut Vec<Diagnostic>,
diagnostics: &mut Vec<Diagnostic>,
contents: &str,
commented_lines: &[usize],
noqa_line_for: &IntMap<usize, usize>,
@ -30,7 +30,7 @@ pub fn check_noqa(
for lineno in commented_lines {
// If we hit an exemption for the entire file, bail.
if is_file_exempt(lines[lineno - 1]) {
checks.drain(..);
diagnostics.drain(..);
return;
}
@ -41,14 +41,14 @@ pub fn check_noqa(
}
}
// Remove any ignored checks.
for (index, check) in checks.iter().enumerate() {
if matches!(check.kind, DiagnosticKind::BlanketNOQA(..)) {
// Remove any ignored diagnostics.
for (index, diagnostic) in diagnostics.iter().enumerate() {
if matches!(diagnostic.kind, DiagnosticKind::BlanketNOQA(..)) {
continue;
}
// 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);
if commented_lines.contains(noqa_lineno) {
let noqa = noqa_directives.entry(noqa_lineno - 1).or_insert_with(|| {
@ -56,13 +56,13 @@ pub fn check_noqa(
});
match noqa {
(Directive::All(..), matches) => {
matches.push(check.kind.code().as_ref());
matches.push(diagnostic.kind.code().as_ref());
ignored.push(index);
continue;
}
(Directive::Codes(.., codes), matches) => {
if noqa::includes(check.kind.code(), codes) {
matches.push(check.kind.code().as_ref());
if noqa::includes(diagnostic.kind.code(), codes) {
matches.push(diagnostic.kind.code().as_ref());
ignored.push(index);
continue;
}
@ -72,21 +72,23 @@ pub fn check_noqa(
}
}
// Is the check ignored by a `noqa` directive on the same line?
let check_lineno = check.location.row();
let noqa_lineno = noqa_line_for.get(&check_lineno).unwrap_or(&check_lineno);
// Is the diagnostic ignored by a `noqa` directive on the same line?
let diagnostic_lineno = diagnostic.location.row();
let noqa_lineno = noqa_line_for
.get(&diagnostic_lineno)
.unwrap_or(&diagnostic_lineno);
if commented_lines.contains(noqa_lineno) {
let noqa = noqa_directives
.entry(noqa_lineno - 1)
.or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno - 1]), vec![]));
match noqa {
(Directive::All(..), matches) => {
matches.push(check.kind.code().as_ref());
matches.push(diagnostic.kind.code().as_ref());
ignored.push(index);
}
(Directive::Codes(.., codes), matches) => {
if noqa::includes(check.kind.code(), codes) {
matches.push(check.kind.code().as_ref());
if noqa::includes(diagnostic.kind.code(), codes) {
matches.push(diagnostic.kind.code().as_ref());
ignored.push(index);
}
}
@ -101,19 +103,19 @@ pub fn check_noqa(
match directive {
Directive::All(spaces, start, end) => {
if matches.is_empty() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnusedNOQA(None),
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
);
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, lines[row].chars().count()),
));
}
checks.push(check);
diagnostics.push(diagnostic);
}
}
Directive::Codes(spaces, start, end, codes) => {
@ -152,7 +154,7 @@ pub fn check_noqa(
&& unknown_codes.is_empty()
&& unmatched_codes.is_empty())
{
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnusedNOQA(Some(UnusedCodes {
disabled: disabled_codes
.iter()
@ -170,22 +172,22 @@ pub fn check_noqa(
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
);
if matches!(autofix, flags::Autofix::Enabled)
&& settings.fixable.contains(check.kind.code())
&& settings.fixable.contains(diagnostic.kind.code())
{
if valid_codes.is_empty() {
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
Location::new(row + 1, start - spaces),
Location::new(row + 1, lines[row].chars().count()),
));
} else {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
format!("# noqa: {}", valid_codes.join(", ")),
Location::new(row + 1, start),
Location::new(row + 1, lines[row].chars().count()),
));
}
}
checks.push(check);
diagnostics.push(diagnostic);
}
}
Directive::None => {}
@ -195,6 +197,6 @@ pub fn check_noqa(
ignored.sort_unstable();
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,
autofix: flags::Autofix,
) -> Vec<Diagnostic> {
let mut checks: Vec<Diagnostic> = vec![];
let mut diagnostics: Vec<Diagnostic> = vec![];
let enforce_ambiguous_unicode_character = settings.enabled.contains(&RuleCode::RUF001)
|| settings.enabled.contains(&RuleCode::RUF002)
@ -40,7 +40,7 @@ pub fn check_tokens(
// RUF001, RUF002, RUF003
if enforce_ambiguous_unicode_character {
if matches!(tok, Tok::String { .. } | Tok::Comment(_)) {
checks.extend(ruff::checks::ambiguous_unicode_character(
diagnostics.extend(ruff::checks::ambiguous_unicode_character(
locator,
start,
end,
@ -62,15 +62,15 @@ pub fn check_tokens(
// flake8-quotes
if enforce_quotes {
if matches!(tok, Tok::String { .. }) {
if let Some(check) = flake8_quotes::checks::quotes(
if let Some(diagnostic) = flake8_quotes::checks::quotes(
locator,
start,
end,
is_docstring,
&settings.flake8_quotes,
) {
if settings.enabled.contains(check.kind.code()) {
checks.push(check);
if settings.enabled.contains(diagnostic.kind.code()) {
diagnostics.push(diagnostic);
}
}
}
@ -79,10 +79,10 @@ pub fn check_tokens(
// eradicate
if enforce_commented_out_code {
if matches!(tok, Tok::Comment(_)) {
if let Some(check) =
if let Some(diagnostic) =
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
if enforce_invalid_escape_sequence {
if matches!(tok, Tok::String { .. }) {
checks.extend(pycodestyle::checks::invalid_escape_sequence(
diagnostics.extend(pycodestyle::checks::invalid_escape_sequence(
locator,
start,
end,
@ -103,12 +103,12 @@ pub fn check_tokens(
// ISC001, ISC002
if enforce_implicit_string_concatenation {
checks.extend(
diagnostics.extend(
flake8_implicit_str_concat::checks::implicit(tokens, locator)
.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.
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)
&& settings.fixable.contains(&RuleCode::ERA001)
{
check.amend(Fix::deletion(location, end_location));
diagnostic.amend(Fix::deletion(location, end_location));
}
Some(check)
Some(diagnostic)
} else {
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
&& has_any_typed_arg)
{
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::MissingReturnTypeSpecialMethod(name.to_string()),
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) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
} else if visibility::is_magic(stmt) {

View File

@ -19,7 +19,7 @@ fn check_password_kwarg(arg: &Located<ArgData>, default: &Expr) -> Option<Diagno
/// S107
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 =
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) {
let default = &arguments.defaults[i];
if let Some(check) = check_password_kwarg(arg, default) {
checks.push(check);
if let Some(diagnostic) = check_password_kwarg(arg, default) {
diagnostics.push(diagnostic);
}
}
}
@ -41,11 +41,11 @@ pub fn hardcoded_password_default(arguments: &Arguments) -> Vec<Diagnostic> {
for (i, kwarg) in arguments.kwonlyargs.iter().enumerate() {
if let Some(i) = i.checked_sub(defaults_start) {
let default = &arguments.kw_defaults[i];
if let Some(check) = check_password_kwarg(kwarg, default) {
checks.push(check);
if let Some(diagnostic) = check_password_kwarg(kwarg, default) {
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;
};
let mut check = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test));
if checker.patch(check.kind.code()) {
let mut diagnostic = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test));
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_stmt(&assertion_error(msg));
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
stmt.location,
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) {
// TODO(charlie): Handle "BaseException" and redundant exception aliases.
if !duplicates.is_empty() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DuplicateHandlerException(
duplicates
.into_iter()
@ -54,20 +54,20 @@ fn duplicate_handler_exceptions<'a>(
),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
if unique_elts.len() == 1 {
generator.unparse_expr(unique_elts[0], 0);
} else {
generator.unparse_expr(&type_pattern(unique_elts), 0);
}
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
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> {
checks: Vec<(DiagnosticKind, Range)>,
diagnostics: Vec<(DiagnosticKind, Range)>,
extend_immutable_calls: &'a [(&'a str, &'a str)],
from_imports: &'a FxHashMap<&'a str, FxHashSet<&'a str>>,
import_aliases: &'a FxHashMap<&'a str, &'a str>,
@ -58,7 +58,7 @@ where
)
&& !is_nan_or_infinity(func, args)
{
self.checks.push((
self.diagnostics.push((
violations::FunctionCallArgumentDefault(compose_call_path(expr)).into(),
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))
.collect();
let mut visitor = ArgumentDefaultVisitor {
checks: vec![],
diagnostics: vec![],
extend_immutable_calls: &extend_immutable_cells,
from_imports: &checker.from_imports,
import_aliases: &checker.import_aliases,
@ -117,7 +117,7 @@ pub fn function_call_argument_default(checker: &mut Checker, arguments: &Argumen
{
visitor.visit_expr(expr);
}
for (check, range) in visitor.checks {
for (check, range) in visitor.diagnostics {
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;
}
let mut check = Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) {
let mut diagnostic =
Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&attribute(obj, value), 0);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
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;
struct RaiseVisitor {
checks: Vec<Diagnostic>,
diagnostics: Vec<Diagnostic>,
}
impl<'a> Visitor<'a> for RaiseVisitor {
@ -20,7 +20,7 @@ impl<'a> Visitor<'a> for RaiseVisitor {
} => match &exc.node {
ExprKind::Name { id, .. } if is_lower(id) => {}
_ => {
self.checks.push(Diagnostic::new(
self.diagnostics.push(Diagnostic::new(
violations::RaiseWithoutFromInsideExcept,
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]) {
let mut visitor = RaiseVisitor { checks: vec![] };
let mut visitor = RaiseVisitor {
diagnostics: vec![],
};
for stmt in body {
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 {
continue;
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::RedundantTupleInExceptionHandler(elt.to_string()),
Range::from_located(type_),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(elt, 0);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
type_.location,
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`).
if let StmtKind::Expr { value: child } = &checker.current_stmt().node {
if expr == child.as_ref() {
let mut check =
let mut diagnostic =
Diagnostic::new(violations::SetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
assignment(obj, name, value, checker.style),
expr.location,
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;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnusedLoopControlVariable(name.to_string()),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// Prefix the variable name with an underscore.
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
format!("_{name}"),
expr.location,
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> {
let argument = exactly_one_argument_with_matching_function("list", func, args, keywords)?;
if let ExprKind::GeneratorExp { .. } = argument {
let mut check = Diagnostic::new(violations::UnnecessaryGeneratorList, location);
let mut diagnostic = Diagnostic::new(violations::UnnecessaryGeneratorList, location);
if fix {
match fixes::fix_unnecessary_generator_list(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
return Some(check);
return Some(diagnostic);
}
None
}
@ -85,16 +85,16 @@ pub fn unnecessary_generator_set(
) -> Option<Diagnostic> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
if let ExprKind::GeneratorExp { .. } = argument {
let mut check = Diagnostic::new(violations::UnnecessaryGeneratorSet, location);
let mut diagnostic = Diagnostic::new(violations::UnnecessaryGeneratorSet, location);
if fix {
match fixes::fix_unnecessary_generator_set(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
return Some(check);
return Some(diagnostic);
}
None
}
@ -113,16 +113,17 @@ pub fn unnecessary_generator_dict(
if let ExprKind::GeneratorExp { elt, .. } = argument {
match &elt.node {
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 {
match fixes::fix_unnecessary_generator_dict(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
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> {
let argument = exactly_one_argument_with_matching_function("set", func, args, keywords)?;
if let ExprKind::ListComp { .. } = &argument {
let mut check = Diagnostic::new(violations::UnnecessaryListComprehensionSet, location);
let mut diagnostic = Diagnostic::new(violations::UnnecessaryListComprehensionSet, location);
if fix {
match fixes::fix_unnecessary_list_comprehension_set(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
return Some(check);
return Some(diagnostic);
}
None
}
@ -176,16 +177,16 @@ pub fn unnecessary_list_comprehension_dict(
if elts.len() != 2 {
return None;
}
let mut check = Diagnostic::new(violations::UnnecessaryListComprehensionDict, location);
let mut diagnostic = Diagnostic::new(violations::UnnecessaryListComprehensionDict, location);
if fix {
match fixes::fix_unnecessary_list_comprehension_dict(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C405 (`set([1, 2])`)
@ -204,19 +205,19 @@ pub fn unnecessary_literal_set(
ExprKind::Tuple { .. } => "tuple",
_ => return None,
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralSet(kind.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_literal_set(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C406 (`dict([(1, 2)])`)
@ -242,19 +243,19 @@ pub fn unnecessary_literal_dict(
{
return None;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralDict(kind.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_literal_dict(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C408
@ -280,19 +281,19 @@ pub fn unnecessary_collection_call(
}
_ => return None,
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryCollectionCall(id.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_collection_call(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C409
@ -310,19 +311,19 @@ pub fn unnecessary_literal_within_tuple_call(
ExprKind::List { .. } => "list",
_ => return None,
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralWithinTupleCall(argument_kind.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_literal_within_tuple_call(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C410
@ -340,19 +341,19 @@ pub fn unnecessary_literal_within_list_call(
ExprKind::List { .. } => "list",
_ => return None,
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryLiteralWithinListCall(argument_kind.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_literal_within_list_call(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C411
@ -368,16 +369,16 @@ pub fn unnecessary_list_call(
if !matches!(argument, ExprKind::ListComp { .. }) {
return None;
}
let mut check = Diagnostic::new(violations::UnnecessaryListCall, location);
let mut diagnostic = Diagnostic::new(violations::UnnecessaryListCall, location);
if fix {
match fixes::fix_unnecessary_list_call(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C413
@ -400,19 +401,19 @@ pub fn unnecessary_call_around_sorted(
return None;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryCallAroundSorted(outer.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_call_around_sorted(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C414
@ -525,19 +526,19 @@ pub fn unnecessary_comprehension(
ExprKind::SetComp { .. } => "set",
_ => return None,
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryComprehension(expr_kind.to_string()),
location,
);
if fix {
match fixes::fix_unnecessary_comprehension(locator, expr) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to generate fix: {e}"),
}
}
Some(check)
Some(diagnostic)
}
/// C417

View File

@ -27,21 +27,21 @@ pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) {
}
) {
if matches!(pass_stmt.node, StmtKind::Pass) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoUnnecessaryPass,
Range::from_located(pass_stmt),
);
if checker.patch(&RuleCode::PIE790) {
match delete_stmt(pass_stmt, None, &[], checker.locator) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(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) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DupeClassFieldDefinitions(target.to_string()),
Range::from_located(stmt),
);
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 {
seen_targets.insert(target);
}
@ -100,16 +100,16 @@ pub fn prefer_list_builtin(checker: &mut Checker, expr: &Expr) {
if args.args.is_empty() {
if let ExprKind::List { elts, .. } = &body.node {
if elts.is_empty() {
let mut check =
let mut diagnostic =
Diagnostic::new(violations::PreferListBuiltin, Range::from_located(expr));
if checker.patch(&RuleCode::PIE807) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"list".to_string(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
}

View File

@ -10,7 +10,7 @@ use crate::violations;
/// T201, T203
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);
if match_call_path(&call_path, "", "print", &checker.from_imports) {
// 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;
}
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let defined_by = checker.current_stmt();
let defined_in = checker.current_stmt_parent();
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" {
checker.deletions.insert(defined_by.clone());
}
check.amend(fix);
diagnostic.amend(fix);
}
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 {
ExprKind::Attribute { attr, .. } => {
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()),
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
unparse_stmt(&stmt, checker.style),
call.location,
call.end_location.unwrap(),
));
}
}
Some(check)
Some(diagnostic)
} else {
None
}

View File

@ -79,14 +79,14 @@ fn pytest_fixture_parentheses(
preferred: &str,
actual: &str,
) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()),
Range::from_located(decorator),
);
if checker.patch(check.kind.code()) {
check.amend(fix);
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(fix);
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// 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 ExprKind::Yield { .. } = value.node {
if visitor.yield_statements.len() == 1 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UselessYieldFixture(func_name.to_string()),
Range::from_located(stmt),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
"return".to_string(),
stmt.location,
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,
actual: &str,
) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::IncorrectMarkParenthesesStyle(
get_mark_name(decorator).to_string(),
preferred.to_string(),
@ -22,10 +22,10 @@ fn pytest_mark_parentheses(
),
Range::from_located(decorator),
);
if checker.patch(check.kind.code()) {
check.amend(fix);
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(fix);
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
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 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UseFixturesWithoutParameters,
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);
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 {
match names_type {
types::ParametrizeNameType::Tuple => {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(
&create_expr(ExprKind::Tuple {
@ -101,20 +101,20 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}),
1,
);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::List => {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(
&create_expr(ExprKind::List {
@ -131,13 +131,13 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}),
0,
);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::CSV => {}
}
@ -152,11 +152,11 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
match names_type {
types::ParametrizeNameType::Tuple => {}
types::ParametrizeNameType::List => {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(
&create_expr(ExprKind::List {
@ -165,29 +165,29 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}),
0,
);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::CSV => {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type),
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
expr.location,
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 {
types::ParametrizeNameType::List => {}
types::ParametrizeNameType::Tuple => {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(
&create_expr(ExprKind::Tuple {
@ -214,29 +214,29 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
}),
1, // so tuple is generated with parentheses
);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
types::ParametrizeNameType::CSV => {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(names_type),
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
expr.location,
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) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ParametrizeNamesWrongType(types::ParametrizeNameType::CSV),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&create_expr(value.node.clone()), 0);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
fn handle_value_rows(

View File

@ -27,16 +27,16 @@ fn unnecessary_return_none(checker: &mut Checker, stack: &Stack) {
) {
continue;
}
let mut check =
let mut diagnostic =
Diagnostic::new(violations::UnnecessaryReturnNone, Range::from_located(stmt));
if checker.patch(&RuleCode::RET501) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"return".to_string(),
stmt.location,
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() {
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"return None".to_string(),
stmt.location,
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::Try { .. } => {}
_ => {
let mut check =
let mut diagnostic =
Diagnostic::new(violations::ImplicitReturn, Range::from_located(last_stmt));
if checker.patch(&RuleCode::RET503) {
let mut content = String::new();
content.push_str(&indentation(checker, last_stmt));
content.push_str("return None");
content.push('\n');
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
content,
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.
for (arg_name, indices) in duplicates {
if indices.len() > 1 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DuplicateIsinstanceCall(arg_name.to_string()),
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
// multiple duplicates, the fixes will conflict.
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
unparse_expr(&bool_op, checker.style),
expr.location,
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()
.map(|value| unparse_expr(value, checker.style))
.collect();
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::CompareWithTuple(
value.to_string(),
str_values,
@ -192,13 +192,13 @@ pub fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
ctx: ExprContext::Load,
})],
});
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
unparse_expr(&in_expr, checker.style),
expr.location,
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 non_negate_expr in &non_negated_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()),
Range::from_located(expr),
);
if checker.patch(&RuleCode::SIM220) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"False".to_string(),
expr.location,
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 non_negate_expr in &non_negated_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()),
Range::from_located(expr),
);
if checker.patch(&RuleCode::SIM220) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"True".to_string(),
expr.location,
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
{
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"True".to_string(),
expr.location,
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
{
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"False".to_string(),
expr.location,
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,
checker.style,
);
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ConvertLoopToAny(content.clone()),
Range::from_located(stmt),
);
if checker.patch(&RuleCode::SIM110) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
stmt.location,
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,
checker.style,
);
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ConvertLoopToAll(content.clone()),
Range::from_located(stmt),
);
if checker.patch(&RuleCode::SIM111) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
stmt.location,
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;
}
let condition = unparse_expr(test, checker.style);
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ReturnBoolConditionDirectly(condition),
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 {
value: Some(test.clone()),
});
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
unparse_stmt(&return_stmt, checker.style),
stmt.location,
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 {
@ -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 content = unparse_stmt(&ternary, checker.style);
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UseTernaryOperator(content.clone()),
Range::from_located(stmt),
);
if checker.patch(&RuleCode::SIM108) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
stmt.location,
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;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::IfExprWithTrueFalse(unparse_expr(test, checker.style)),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
unparse_expr(
&create_expr(ExprKind::Call {
func: Box::new(create_expr(ExprKind::Name {
@ -49,7 +49,7 @@ pub fn explicit_true_false_in_ifexpr(
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// SIM211
@ -73,12 +73,12 @@ pub fn explicit_false_true_in_ifexpr(
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::IfExprWithFalseTrue(unparse_expr(test, checker.style)),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
unparse_expr(
&create_expr(ExprKind::UnaryOp {
op: Unaryop::Not,
@ -90,7 +90,7 @@ pub fn explicit_false_true_in_ifexpr(
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// SIM212
@ -119,15 +119,15 @@ pub fn twisted_arms_in_ifexpr(
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::IfExprWithTwistedArms(
unparse_expr(body, checker.style),
unparse_expr(orelse, checker.style),
),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
unparse_expr(
&create_expr(ExprKind::IfExp {
test: Box::new(create_expr(orelse.node.clone())),
@ -140,5 +140,5 @@ pub fn twisted_arms_in_ifexpr(
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;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NegateEqualOp(
unparse_expr(left, checker.style),
unparse_expr(&comparators[0], checker.style),
),
Range::from_located(operand),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
unparse_expr(
&create_expr(ExprKind::Compare {
left: left.clone(),
@ -56,7 +56,7 @@ pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// SIM202
@ -79,15 +79,15 @@ pub fn negation_with_not_equal_op(
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NegateNotEqualOp(
unparse_expr(left, checker.style),
unparse_expr(&comparators[0], checker.style),
),
Range::from_located(operand),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
unparse_expr(
&create_expr(ExprKind::Compare {
left: left.clone(),
@ -100,7 +100,7 @@ pub fn negation_with_not_equal_op(
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// SIM208
@ -115,16 +115,16 @@ pub fn double_negation(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DoubleNegation(operand.to_string()),
Range::from_located(operand),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
unparse_expr(operand, checker.style),
expr.location,
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
.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()),
range,
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
value_content.to_string(),
right.location,
right.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// SIM118 in a for loop

View File

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

View File

@ -41,18 +41,18 @@ pub fn yoda_conditions(
.locator
.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()),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
format!("{right_content} == {left_content}"),
left.location,
right.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}

View File

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

View File

@ -92,16 +92,16 @@ pub fn check_imports(
if actual == dedent(&expected) {
None
} else {
let mut check = Diagnostic::new(violations::UnsortedImports, range);
let mut diagnostic = Diagnostic::new(violations::UnsortedImports, range);
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),
range.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())?;
let messages: Vec<ExpandedMessage> = checks
let messages: Vec<ExpandedMessage> = diagnostics
.into_iter()
.map(|check| ExpandedMessage {
code: check.kind.code().clone(),
message: check.kind.body(),
location: check.location,
end_location: check.end_location,
fix: check.fix.map(|fix| ExpandedFix {
.map(|diagnostic| ExpandedMessage {
code: diagnostic.kind.code().clone(),
message: diagnostic.kind.body(),
location: diagnostic.location,
end_location: diagnostic.end_location,
fix: diagnostic.fix.map(|fix| ExpandedFix {
content: fix.content,
message: check.kind.commit(),
message: diagnostic.kind.commit(),
location: fix.location,
end_location: fix.end_location,
}),

View File

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

View File

@ -54,7 +54,7 @@ pub fn line_too_long(lineno: usize, line: &str, settings: &Settings) -> Option<D
/// E721
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) {
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
}
) {
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 {
// Ex) types.IntType
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
@ -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() {
// Both locations are at the end of the file (and thus the same).
let location = Location::new(contents.lines().count(), line.len());
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoNewLineAtEndOfFile,
Range::new(location, location),
);
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

View File

@ -47,7 +47,7 @@ pub fn literal_comparisons(
// then replace the entire expression at the end with one "real" fix, to
// avoid conflicts.
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();
@ -64,24 +64,24 @@ pub fn literal_comparisons(
)
{
if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()),
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);
}
checks.push(check);
diagnostics.push(diagnostic);
}
if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()),
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);
}
checks.push(check);
diagnostics.push(diagnostic);
}
}
@ -92,24 +92,28 @@ pub fn literal_comparisons(
} = comparator.node
{
if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()),
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);
}
checks.push(check);
diagnostics.push(diagnostic);
}
if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()),
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);
}
checks.push(check);
diagnostics.push(diagnostic);
}
}
}
@ -126,28 +130,28 @@ pub fn literal_comparisons(
)
{
if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()),
Range::from_located(next),
);
if checker.patch(check.kind.code())
if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator)
{
bad_ops.insert(idx, Cmpop::Is);
}
checks.push(check);
diagnostics.push(diagnostic);
}
if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::NoneComparison(op.into()),
Range::from_located(next),
);
if checker.patch(check.kind.code())
if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator)
{
bad_ops.insert(idx, Cmpop::IsNot);
}
checks.push(check);
diagnostics.push(diagnostic);
}
}
@ -158,28 +162,28 @@ pub fn literal_comparisons(
} = next.node
{
if matches!(op, Cmpop::Eq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()),
Range::from_located(next),
);
if checker.patch(check.kind.code())
if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator)
{
bad_ops.insert(idx, Cmpop::Is);
}
checks.push(check);
diagnostics.push(diagnostic);
}
if matches!(op, Cmpop::NotEq) {
let check = Diagnostic::new(
let diagnostic = Diagnostic::new(
violations::TrueFalseComparison(value, op.into()),
Range::from_located(next),
);
if checker.patch(check.kind.code())
if checker.patch(diagnostic.kind.code())
&& !helpers::is_constant_non_singleton(comparator)
{
bad_ops.insert(idx, Cmpop::IsNot);
}
checks.push(check);
diagnostics.push(diagnostic);
}
}
}
@ -198,8 +202,8 @@ pub fn literal_comparisons(
.cloned()
.collect::<Vec<_>>();
let content = compare(left, &ops, comparators, checker.style);
for check in &mut checks {
check.amend(Fix::replacement(
for diagnostic in &mut diagnostics {
diagnostic.amend(Fix::replacement(
content.to_string(),
expr.location,
expr.end_location.unwrap(),
@ -207,7 +211,7 @@ pub fn literal_comparisons(
}
}
checker.diagnostics.extend(checks);
checker.diagnostics.extend(diagnostics);
}
/// E713, E714
@ -232,34 +236,34 @@ pub fn not_tests(
match op {
Cmpop::In => {
if check_not_in {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NotInTest,
Range::from_located(operand),
);
if checker.patch(check.kind.code()) && should_fix {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) && should_fix {
diagnostic.amend(Fix::replacement(
compare(left, &[Cmpop::NotIn], comparators, checker.style),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
Cmpop::Is => {
if check_not_is {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NotIsTest,
Range::from_located(operand),
);
if checker.patch(check.kind.code()) && should_fix {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) && should_fix {
diagnostic.amend(Fix::replacement(
compare(left, &[Cmpop::IsNot], comparators, checker.style),
expr.location,
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) {
if let ExprKind::Name { id, .. } = &target.node {
if let ExprKind::Lambda { args, body } = &value.node {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DoNotAssignLambda(id.to_string()),
Range::from_located(stmt),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
if !match_leading_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);
}
}
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
indented,
stmt.location,
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())
.count();
if blank_lines_before != 0 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoBlankLineBeforeFunction(blank_lines_before),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// 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(), 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 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoBlankLineAfterFunction(blank_lines_after),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// 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 + 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();
if checker.settings.enabled.contains(&RuleCode::D211) {
if blank_lines_before != 0 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoBlankLineBeforeClass(blank_lines_before),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// 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(), 0),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
if checker.settings.enabled.contains(&RuleCode::D203) {
if blank_lines_before != 1 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::OneBlankLineBeforeClass(blank_lines_before),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// Insert one blank line before the class.
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"\n".to_string(),
Location::new(docstring.expr.location.row() - blank_lines_before, 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())
.count();
if blank_lines_after != 1 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::OneBlankLineAfterClass(blank_lines_after),
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).
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"\n".to_string(),
Location::new(docstring.expr.end_location.unwrap().row() + 1, 0),
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 {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::BlankLineAfterSummary(blanks_count),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
if blanks_count > 1 {
// Find the "summary" line (defined as the first non-blank line).
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).
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"\n".to_string(),
Location::new(docstring.expr.location.row() + summary_line + 1, 0),
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)
&& line_indent.len() < docstring.indentation.len()
{
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoUnderIndentation,
Range::new(
Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, 0),
),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0),
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() {
// We report over-indentation on every line. This isn't great, but
// enables autofix.
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoOverIndentation,
Range::new(
Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, 0),
),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0),
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 line_indent = whitespace::leading_space(lines[i]);
if line_indent.len() > docstring.indentation.len() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoOverIndentation,
Range::new(
Location::new(docstring.expr.location.row() + i, 0),
Location::new(docstring.expr.location.row() + i, 0),
),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0),
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 let Some(last_line) = contents.lines().last().map(str::trim) {
if last_line != "\"\"\"" && last_line != "'''" {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NewLineAfterLastParagraph,
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).
let content = format!("\n{}", whitespace::clean(docstring.indentation));
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
content,
Location::new(
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;
@ -551,17 +551,17 @@ pub fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) {
if line == trimmed {
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoSurroundingWhitespace,
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(quote) = pattern.chars().last() {
// If removing whitespace would lead to an invalid string of quote
// characters, avoid applying the fix.
if !trimmed.ends_with(quote) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
trimmed.to_string(),
Location::new(
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
@ -696,7 +696,7 @@ pub fn ends_with_period(checker: &mut Checker, docstring: &Docstring) {
let trimmed = line.trim_end();
if !trimmed.ends_with('.') {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::EndsInPeriod,
Range::from_located(docstring.expr),
);
@ -718,10 +718,10 @@ pub fn ends_with_period(checker: &mut Checker, docstring: &Docstring) {
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 trimmed = line.trim_end();
if !(trimmed.ends_with('.') || trimmed.ends_with('!') || trimmed.ends_with('?')) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::EndsInPunctuation,
Range::from_located(docstring.expr),
);
@ -865,10 +865,10 @@ pub fn ends_with_punctuation(checker: &mut Checker, docstring: &Docstring) {
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.
if blank_lines_after_header == context.following_lines.len() {
if checker.settings.enabled.contains(&RuleCode::D407) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DashedUnderlineAfterSection(context.section_name.to_string()),
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.
let content = format!(
"{}{}\n",
whitespace::clean(docstring.indentation),
"-".repeat(context.section_name.len())
);
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
content,
Location::new(
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) {
checker.diagnostics.push(Diagnostic::new(
@ -999,13 +999,13 @@ fn blanks_and_section_underline(
if dash_line_found {
if blank_lines_after_header > 0 {
if checker.settings.enabled.contains(&RuleCode::D408) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::SectionUnderlineAfterName(context.section_name.to_string()),
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.
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
Location::new(
docstring.expr.location.row() + context.original_index + 1,
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()
{
if checker.settings.enabled.contains(&RuleCode::D409) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::SectionUnderlineMatchesSectionLength(
context.section_name.to_string(),
),
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.
let content = format!(
"{}{}\n",
whitespace::clean(docstring.indentation),
"-".repeat(context.section_name.len())
);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
Location::new(
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) {
let leading_space = whitespace::leading_space(non_empty_line);
if leading_space.len() > docstring.indentation.len() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::SectionUnderlineNotOverIndented(context.section_name.to_string()),
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.
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation),
Location::new(
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 {
if checker.settings.enabled.contains(&RuleCode::D412) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoBlankLinesBetweenHeaderAndContent(
context.section_name.to_string(),
),
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.
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
Location::new(
docstring.expr.location.row()
+ 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 {
if checker.settings.enabled.contains(&RuleCode::D407) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DashedUnderlineAfterSection(context.section_name.to_string()),
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.
let content = format!(
"{}{}\n",
whitespace::clean(docstring.indentation),
"-".repeat(context.section_name.len())
);
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
content,
Location::new(
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 checker.settings.enabled.contains(&RuleCode::D412) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NoBlankLinesBetweenHeaderAndContent(
context.section_name.to_string(),
),
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.
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
Location::new(
docstring.expr.location.row() + context.original_index + 1,
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()
.contains(capitalized_section_name.as_str())
{
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::CapitalizeSectionName(context.section_name.to_string()),
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
// locating the start and end of the section name.
if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters.
let section_name_start = &context.line[..index].chars().count();
let section_name_length = &context.section_name.chars().count();
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
capitalized_section_name,
Location::new(
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) {
let leading_space = whitespace::leading_space(context.line);
if leading_space.len() > docstring.indentation.len() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::SectionNotOverIndented(context.section_name.to_string()),
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.
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + context.original_index, 0),
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 checker.settings.enabled.contains(&RuleCode::D413) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::BlankLineAfterLastSection(context.section_name.to_string()),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// Add a newline after the section.
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
"\n".to_string(),
Location::new(
docstring.expr.location.row()
@ -1296,17 +1296,17 @@ fn common_section(
),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
} else {
if checker.settings.enabled.contains(&RuleCode::D410) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::BlankLineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// Add a newline after the section.
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
"\n".to_string(),
Location::new(
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 !context.previous_line.is_empty() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::BlankLineBeforeSection(context.section_name.to_string()),
Range::from_located(docstring.expr),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
// Add a blank line before the section.
check.amend(Fix::insertion(
diagnostic.amend(Fix::insertion(
"\n".to_string(),
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)
.unwrap();
if !suffix.is_empty() {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NewLineAfterSectionName(context.section_name.to_string()),
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.
if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters.
@ -1525,7 +1525,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
.chars()
.count();
let suffix_length = suffix.chars().count();
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
Location::new(
docstring.expr.location.row() + context.original_index,
*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)
.unwrap();
if suffix != ":" {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::SectionNameEndsInColon(context.section_name.to_string()),
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.
if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters.
@ -1571,7 +1571,7 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
.chars()
.count();
let suffix_length = suffix.chars().count();
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
":".to_string(),
Location::new(
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
pub fn assert_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) {
if let Some(check) = checks::assert_tuple(test, Range::from_located(stmt)) {
checker.diagnostics.push(check);
if let Some(diagnostic) = checks::assert_tuple(test, Range::from_located(stmt)) {
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 { .. }))
{
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) {
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
prefix_range.location,
prefix_range.end_location,
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
}

View File

@ -6,7 +6,7 @@ use crate::pyflakes::checks;
/// F634
pub fn if_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) {
if let Some(check) = checks::if_tuple(test, Range::from_located(stmt)) {
checker.diagnostics.push(check);
if let Some(diagnostic) = checks::if_tuple(test, Range::from_located(stmt)) {
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(right))
{
let mut check = Diagnostic::new(violations::IsLiteral(op.into()), location);
if checker.patch(check.kind.code()) {
let mut diagnostic = Diagnostic::new(violations::IsLiteral(op.into()), location);
if checker.patch(diagnostic.kind.code()) {
if let Some(located_op) = &located.get(index) {
assert_eq!(&located_op.node, op);
if let Some(content) = match &located_op.node {
@ -37,7 +37,7 @@ pub fn invalid_literal_comparison(
None
}
} {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
helpers::to_absolute(located_op.location, location.location),
helpers::to_absolute(
@ -50,7 +50,7 @@ pub fn invalid_literal_comparison(
eprintln!("Failed to fix invalid comparison due to missing op");
}
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
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 {
return;
};
let mut check = Diagnostic::new(violations::RaiseNotImplemented, Range::from_located(expr));
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
let mut diagnostic =
Diagnostic::new(violations::RaiseNotImplemented, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
"NotImplementedError".to_string(),
expr.location,
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) {
let comparable_value: ComparableExpr = (&values[i]).into();
let is_duplicate_value = seen_values.contains(&comparable_value);
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::MultiValueRepeatedKeyLiteral(
unparse_expr(&keys[i], checker.style),
is_duplicate_value,
@ -49,7 +49,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
);
if is_duplicate_value {
if checker.patch(&RuleCode::F601) {
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
values[i - 1].end_location.unwrap(),
values[i].end_location.unwrap(),
));
@ -57,14 +57,14 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
} else {
seen_values.insert(comparable_value);
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
DictionaryKey::Variable(key) => {
if checker.settings.enabled.contains(&RuleCode::F602) {
let comparable_value: ComparableExpr = (&values[i]).into();
let is_duplicate_value = seen_values.contains(&comparable_value);
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::MultiValueRepeatedKeyVariable(
key.to_string(),
is_duplicate_value,
@ -73,7 +73,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
);
if is_duplicate_value {
if checker.patch(&RuleCode::F602) {
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
values[i - 1].end_location.unwrap(),
values[i].end_location.unwrap(),
));
@ -81,7 +81,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Expr], values: &[Expr]) {
} else {
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;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::PercentFormatExtraNamedArguments(
missing.iter().map(|&arg| arg.to_string()).collect(),
),
location,
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
match remove_unused_format_arguments_from_dict(&missing, right, checker.locator) {
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to remove unused format arguments: {e}"),
}
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// F505
@ -268,22 +268,22 @@ pub(crate) fn string_dot_format_extra_named_arguments(
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::StringDotFormatExtraNamedArguments(
missing.iter().map(|&arg| arg.to_string()).collect(),
),
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)
{
Ok(fix) => {
check.amend(fix);
diagnostic.amend(fix);
}
Err(e) => error!("Failed to remove unused keyword arguments: {e}"),
}
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// F523

View File

@ -169,7 +169,7 @@ pub fn unused_variable(checker: &mut Checker, scope: usize) {
&& name != &"__traceback_info__"
&& name != &"__traceback_supplement__"
{
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnusedVariable((*name).to_string()),
binding.range,
);
@ -180,11 +180,11 @@ pub fn unused_variable(checker: &mut Checker, scope: usize) {
if matches!(kind, DeletionKind::Whole) {
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"),
};
let suggestion = format!("{right} {reversed_op} {left}");
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::MisplacedComparisonConstant(suggestion.clone()),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
suggestion,
expr.location,
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) {
continue;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UseSysExit(name.to_string()),
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") {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
func.location,
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;
}
let mut check = Diagnostic::new(violations::UselessImportAlias, Range::from_located(alias));
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
let mut diagnostic =
Diagnostic::new(violations::UselessImportAlias, Range::from_located(alias));
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
asname.to_string(),
alias.location,
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> {
// PEP3120 makes utf-8 the default encoding.
if CODING_COMMENT_REGEX.is_match(line) {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::PEP3120UnnecessaryCodingComment,
Range::new(Location::new(lineno + 1, 0), Location::new(lineno + 2, 0)),
);
if autofix {
check.amend(Fix::deletion(
diagnostic.amend(Fix::deletion(
Location::new(lineno + 1, 0),
Location::new(lineno + 2, 0),
));
}
Some(check)
Some(diagnostic)
} else {
None
}

View File

@ -157,16 +157,16 @@ pub fn convert_named_tuple_functional_to_class(
{
return;
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ConvertNamedTupleFunctionalToClass(typename.to_string()),
Range::from_located(stmt),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
match match_defaults(keywords)
.and_then(|defaults| create_properties_from_args(args, defaults))
{
Ok(properties) => {
check.amend(convert_to_class(
diagnostic.amend(convert_to_class(
stmt,
typename,
properties,
@ -177,5 +177,5 @@ pub fn convert_named_tuple_functional_to_class(
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;
};
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::ConvertTypedDictFunctionalToClass(class_name.to_string()),
Range::from_located(stmt),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
match match_properties_and_total(args, keywords) {
Ok((body, total_keyword)) => {
check.amend(convert_to_class(
diagnostic.amend(convert_to_class(
stmt,
class_name,
body,
@ -219,5 +219,5 @@ pub fn convert_typed_dict_functional_to_class(
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) {
let dealiased_call_path = dealias_call_path(collect_call_paths(expr), &checker.import_aliases);
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
compose_call_path(expr)
.unwrap()
.replace("timezone.utc", "UTC"),
@ -21,6 +22,6 @@ pub fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) {
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" {
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::DeprecatedUnittestAlias(attr.to_string(), target.to_string()),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
format!("self.{target}"),
expr.location,
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) {
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
} else {
LiteralType::Bytes
}), Range::from_located(expr));
if checker.patch(&RuleCode::UP018) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
if id == "bytes" {
let mut content = String::with_capacity(3);
content.push('b');
@ -48,7 +48,7 @@ pub fn native_literals(
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
return;
};
@ -93,7 +93,7 @@ pub fn native_literals(
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::NativeLiterals(if id == "str" {
LiteralType::Str
} else {
@ -102,12 +102,12 @@ pub fn native_literals(
Range::from_located(expr),
);
if checker.patch(&RuleCode::UP018) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
arg_code.to_string(),
expr.location,
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);
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) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"open".to_string(),
func.location,
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.push(')');
}
let mut check = Diagnostic::new(violations::OSErrorAlias(compose_call_path(target)), range);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
let mut diagnostic =
Diagnostic::new(violations::OSErrorAlias(compose_call_path(target)), range);
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
final_str,
range.location,
range.end_location,
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}

View File

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

View File

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

View File

@ -75,8 +75,9 @@ pub fn replace_stdout_stderr(checker: &mut Checker, expr: &Expr, kwargs: &[Keywo
return;
}
let mut check = Diagnostic::new(violations::ReplaceStdoutStderr, Range::from_located(expr));
if checker.patch(check.kind.code()) {
let mut diagnostic =
Diagnostic::new(violations::ReplaceStdoutStderr, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
let first = if stdout.location < stderr.location {
stdout
} else {
@ -104,12 +105,12 @@ pub fn replace_stdout_stderr(checker: &mut Checker, expr: &Expr, kwargs: &[Keywo
}
contents.push_str(middle.contents);
}
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
contents,
first.location,
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(),
),
);
let mut check = Diagnostic::new(violations::ReplaceUniversalNewlines, range);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
let mut diagnostic = Diagnostic::new(violations::ReplaceUniversalNewlines, range);
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
"text".to_string(),
range.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;
fn add_check_for_node<T>(checker: &mut Checker, node: &Located<T>) {
let mut check = Diagnostic::new(violations::RewriteCElementTree, Range::from_located(node));
if checker.patch(check.kind.code()) {
let mut diagnostic =
Diagnostic::new(violations::RewriteCElementTree, Range::from_located(node));
if checker.patch(diagnostic.kind.code()) {
let contents = checker
.locator
.slice_source_code_range(&Range::from_located(node));
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
contents.replacen("cElementTree", "ElementTree", 1),
node.location,
node.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
/// UP023

View File

@ -205,18 +205,18 @@ fn format_import_from(
pub fn rewrite_mock_attribute(checker: &mut Checker, expr: &Expr) {
if let ExprKind::Attribute { value, .. } = &expr.node {
if collect_call_paths(value) == ["mock", "mock"] {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::RewriteMockImport(MockReference::Attribute),
Range::from_located(value),
);
if checker.patch(&RuleCode::UP026) {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
"mock".to_string(),
value.location,
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.
for name in names {
if name.node.name == "mock" || name.node.name == "mock.mock" {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::RewriteMockImport(MockReference::Import),
Range::from_located(name),
);
if let Some(content) = content.as_ref() {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content.clone(),
stmt.location,
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" {
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::RewriteMockImport(MockReference::Import),
Range::from_located(stmt),
);
@ -281,7 +281,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) {
let indent = indentation(checker, stmt);
match format_import_from(stmt, &indent, checker.locator, checker.style) {
Ok(content) => {
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
stmt.location,
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}"),
}
}
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>) {
if let Some(const_kind) = kind {
if const_kind.to_lowercase() == "u" {
let mut check =
let mut diagnostic =
Diagnostic::new(violations::RewriteUnicodeLiteral, Range::from_located(expr));
if checker.patch(check.kind.code()) {
check.amend(Fix::deletion(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::deletion(
expr.location,
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;
}
let mut check =
let mut diagnostic =
Diagnostic::new(violations::RewriteYieldFrom, Range::from_located(item.stmt));
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let contents = checker
.locator
.slice_source_code_range(&Range::from_located(item.iter));
let contents = format!("yield from {contents}");
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
contents,
item.stmt.location,
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()
.map(std::convert::Into::into)
.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;
};
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
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
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;
};
if checker.patch(check.kind.code()) {
if let DiagnosticKind::TypeOfPrimitive(violations::TypeOfPrimitive(primitive)) = &check.kind
if checker.patch(diagnostic.kind.code()) {
if let DiagnosticKind::TypeOfPrimitive(violations::TypeOfPrimitive(primitive)) =
&diagnostic.kind
{
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
primitive.builtin(),
expr.location,
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.import_aliases,
) {
let mut check = Diagnostic::new(violations::TypingTextStrAlias, Range::from_located(expr));
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
let mut diagnostic =
Diagnostic::new(violations::TypingTextStrAlias, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
"str".to_string(),
expr.location,
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() {
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryBuiltinImport(
unused_imports
.iter()
@ -79,7 +79,7 @@ pub fn unnecessary_builtin_import(
Range::from_located(stmt),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let deleted: Vec<&Stmt> = checker
.deletions
.iter()
@ -102,10 +102,10 @@ pub fn unnecessary_builtin_import(
if fix.content.is_empty() || fix.content == "pass" {
checker.deletions.insert(defined_by.clone());
}
check.amend(fix);
diagnostic.amend(fix);
}
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,
) -> Option<Diagnostic> {
if let Some(arg) = args.get(0) {
let mut check =
let mut diagnostic =
Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr));
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) {
let mut check =
let mut diagnostic =
Diagnostic::new(violations::UnnecessaryEncodeUTF8, Range::from_located(expr));
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 {
None
}
@ -85,7 +85,8 @@ fn replace_with_bytes_literal(
locator: &SourceCodeLocator,
patch: bool,
) -> 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 {
let content = locator.slice_source_code_range(&Range::new(
constant.location,
@ -95,13 +96,13 @@ fn replace_with_bytes_literal(
"b{}",
content.trim_start_matches('u').trim_start_matches('U')
);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
));
}
check
diagnostic
}
/// UP012
@ -133,13 +134,13 @@ pub fn unnecessary_encode_utf8(
));
} else {
// "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,
args,
kwargs,
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)
ExprKind::JoinedStr { .. } => {
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,
args,
kwargs,
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() {
return;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::UnnecessaryFutureImport(
unused_imports
.iter()
@ -64,7 +64,7 @@ pub fn unnecessary_future_import(checker: &mut Checker, stmt: &Stmt, names: &[Lo
Range::from_located(stmt),
);
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let deleted: Vec<&Stmt> = checker
.deletions
.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" {
checker.deletions.insert(defined_by.clone());
}
check.amend(fix);
diagnostic.amend(fix);
}
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
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,
checker.settings.target_version,
&checker.from_imports,
@ -14,8 +14,8 @@ pub fn unnecessary_lru_cache_params(checker: &mut Checker, decorator_list: &[Exp
) else {
return;
};
if checker.patch(check.kind.code()) {
check.amend(Fix::deletion(check.location, check.end_location));
if checker.patch(diagnostic.kind.code()) {
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;
}
let mut check = Diagnostic::new(
let mut diagnostic = Diagnostic::new(
violations::RewriteListComprehension,
Range::from_located(value),
);
@ -88,13 +88,13 @@ pub fn unpack_list_comprehension(checker: &mut Checker, targets: &[Expr], value:
content.push('(');
content.push_str(&existing[1..existing.len() - 1]);
content.push(')');
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
content,
value.location,
value.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}
}
}

View File

@ -9,16 +9,16 @@ use crate::violations;
/// UP006
pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr, id: &str) {
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()),
Range::from_located(expr),
);
if checker.patch(check.kind.code()) {
check.amend(Fix::replacement(
if checker.patch(diagnostic.kind.code()) {
diagnostic.amend(Fix::replacement(
replacement.to_lowercase(),
expr.location,
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);
if checker.match_typing_call_path(&call_path, "Optional") {
let mut check = Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(check.kind.code()) {
let mut diagnostic =
Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&optional(slice), 0);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
} else if checker.match_typing_call_path(&call_path, "Union") {
let mut check = Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(check.kind.code()) {
let mut diagnostic =
Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) {
match &slice.node {
ExprKind::Slice { .. } => {
// Invalid type annotation.
@ -85,7 +87,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
ExprKind::Tuple { elts, .. } => {
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(&union(elts), 0);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
expr.end_location.unwrap(),
@ -95,7 +97,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
// Single argument.
let mut generator: SourceCodeGenerator = checker.style.into();
generator.unparse_expr(slice, 0);
check.amend(Fix::replacement(
diagnostic.amend(Fix::replacement(
generator.generate(),
expr.location,
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
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 {
return;
};
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
let deleted: Vec<&Stmt> = checker
.deletions
.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" {
checker.deletions.insert(defined_by.clone());
}
check.amend(fix);
diagnostic.amend(fix);
}
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],
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;
};
if checker.patch(check.kind.code()) {
if checker.patch(diagnostic.kind.code()) {
if let Some(fix) = pyupgrade::fixes::remove_class_def_base(
checker.locator,
stmt.location,
check.location,
diagnostic.location,
bases,
keywords,
) {
check.amend(fix);
diagnostic.amend(fix);
}
}
checker.diagnostics.push(check);
checker.diagnostics.push(diagnostic);
}