rule 2/8: Rename DiagnosticKind::code to rule

This commit is contained in:
Martin Fischer 2023-01-18 00:35:09 +01:00 committed by Charlie Marsh
parent 3c1c1e1dd3
commit 3810250bb6
55 changed files with 181 additions and 125 deletions

View File

@ -143,7 +143,7 @@ impl<'a> Printer<'a> {
.messages .messages
.iter() .iter()
.map(|message| ExpandedMessage { .map(|message| ExpandedMessage {
code: message.kind.code(), code: message.kind.rule(),
message: message.kind.body(), message: message.kind.body(),
fix: message.fix.as_ref().map(|fix| ExpandedFix { fix: message.fix.as_ref().map(|fix| ExpandedFix {
content: &fix.content, content: &fix.content,
@ -178,7 +178,7 @@ impl<'a> Printer<'a> {
message.kind.body() message.kind.body()
)); ));
let mut case = let mut case =
TestCase::new(format!("org.ruff.{}", message.kind.code()), status); TestCase::new(format!("org.ruff.{}", message.kind.rule()), status);
let file_path = Path::new(filename); let file_path = Path::new(filename);
let file_stem = file_path.file_stem().unwrap().to_str().unwrap(); let file_stem = file_path.file_stem().unwrap().to_str().unwrap();
let classname = file_path.parent().unwrap().join(file_stem); let classname = file_path.parent().unwrap().join(file_stem);
@ -248,14 +248,14 @@ impl<'a> Printer<'a> {
":", ":",
message.location.column(), message.location.column(),
":", ":",
message.kind.code().as_ref(), message.kind.rule().as_ref(),
message.kind.body(), message.kind.body(),
); );
writeln!( writeln!(
stdout, stdout,
"::error title=Ruff \ "::error title=Ruff \
({}),file={},line={},col={},endLine={},endColumn={}::{}", ({}),file={},line={},col={},endLine={},endColumn={}::{}",
message.kind.code(), message.kind.rule(),
message.filename, message.filename,
message.location.row(), message.location.row(),
message.location.column(), message.location.column(),
@ -276,9 +276,9 @@ impl<'a> Printer<'a> {
.iter() .iter()
.map(|message| { .map(|message| {
json!({ json!({
"description": format!("({}) {}", message.kind.code(), message.kind.body()), "description": format!("({}) {}", message.kind.rule(), message.kind.body()),
"severity": "major", "severity": "major",
"fingerprint": message.kind.code(), "fingerprint": message.kind.rule(),
"location": { "location": {
"path": message.filename, "path": message.filename,
"lines": { "lines": {
@ -361,7 +361,7 @@ fn print_message<T: Write>(stdout: &mut T, message: &Message) -> Result<()> {
":".cyan(), ":".cyan(),
message.location.column(), message.location.column(),
":".cyan(), ":".cyan(),
message.kind.code().as_ref().red().bold(), message.kind.rule().as_ref().red().bold(),
message.kind.body(), message.kind.body(),
); );
writeln!(stdout, "{label}")?; writeln!(stdout, "{label}")?;
@ -388,7 +388,7 @@ fn print_message<T: Write>(stdout: &mut T, message: &Message) -> Result<()> {
source: &source.contents, source: &source.contents,
line_start: message.location.row(), line_start: message.location.row(),
annotations: vec![SourceAnnotation { annotations: vec![SourceAnnotation {
label: message.kind.code().as_ref(), label: message.kind.rule().as_ref(),
annotation_type: AnnotationType::Error, annotation_type: AnnotationType::Error,
range: source.range, range: source.range,
}], }],
@ -425,7 +425,7 @@ fn print_grouped_message<T: Write>(
":".cyan(), ":".cyan(),
message.location.column(), message.location.column(),
" ".repeat(column_length - num_digits(message.location.column())), " ".repeat(column_length - num_digits(message.location.column())),
message.kind.code().as_ref().red().bold(), message.kind.rule().as_ref().red().bold(),
message.kind.body(), message.kind.body(),
); );
writeln!(stdout, "{label}")?; writeln!(stdout, "{label}")?;
@ -452,7 +452,7 @@ fn print_grouped_message<T: Write>(
source: &source.contents, source: &source.contents,
line_start: message.location.row(), line_start: message.location.row(),
annotations: vec![SourceAnnotation { annotations: vec![SourceAnnotation {
label: message.kind.code().as_ref(), label: message.kind.rule().as_ref(),
annotation_type: AnnotationType::Error, annotation_type: AnnotationType::Error,
range: source.range, range: source.range,
}], }],

View File

@ -30,7 +30,7 @@ fn generate_table(table_out: &mut String, prefix: &RuleCodePrefix) {
let fix_token = if kind.fixable() { "🛠" } else { "" }; let fix_token = if kind.fixable() { "🛠" } else { "" };
table_out.push_str(&format!( table_out.push_str(&format!(
"| {} | {} | {} | {} |", "| {} | {} | {} | {} |",
kind.code().as_ref(), kind.rule().as_ref(),
kind.as_ref(), kind.as_ref(),
kind.summary().replace('|', r"\|"), kind.summary().replace('|', r"\|"),
fix_token fix_token

View File

@ -80,8 +80,8 @@ pub fn define_rule_mapping(mapping: &Mapping) -> proc_macro2::TokenStream {
impl DiagnosticKind { impl DiagnosticKind {
/// A four-letter shorthand code for the diagnostic. /// The rule of the diagnostic.
pub fn code(&self) -> &'static RuleCode { pub fn rule(&self) -> &'static Rule {
match self { #diagkind_code_match_arms } match self { #diagkind_code_match_arms }
} }

View File

@ -56,13 +56,13 @@ pub fn check_noqa(
}); });
match noqa { match noqa {
(Directive::All(..), matches) => { (Directive::All(..), matches) => {
matches.push(diagnostic.kind.code().as_ref()); matches.push(diagnostic.kind.rule().as_ref());
ignored.push(index); ignored.push(index);
continue; continue;
} }
(Directive::Codes(.., codes), matches) => { (Directive::Codes(.., codes), matches) => {
if noqa::includes(diagnostic.kind.code(), codes) { if noqa::includes(diagnostic.kind.rule(), codes) {
matches.push(diagnostic.kind.code().as_ref()); matches.push(diagnostic.kind.rule().as_ref());
ignored.push(index); ignored.push(index);
continue; continue;
} }
@ -83,12 +83,12 @@ pub fn check_noqa(
.or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno - 1]), vec![])); .or_insert_with(|| (noqa::extract_noqa_directive(lines[noqa_lineno - 1]), vec![]));
match noqa { match noqa {
(Directive::All(..), matches) => { (Directive::All(..), matches) => {
matches.push(diagnostic.kind.code().as_ref()); matches.push(diagnostic.kind.rule().as_ref());
ignored.push(index); ignored.push(index);
} }
(Directive::Codes(.., codes), matches) => { (Directive::Codes(.., codes), matches) => {
if noqa::includes(diagnostic.kind.code(), codes) { if noqa::includes(diagnostic.kind.rule(), codes) {
matches.push(diagnostic.kind.code().as_ref()); matches.push(diagnostic.kind.rule().as_ref());
ignored.push(index); ignored.push(index);
} }
} }
@ -108,7 +108,7 @@ pub fn check_noqa(
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)), Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
); );
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.rules.should_fix(diagnostic.kind.code()) && settings.rules.should_fix(diagnostic.kind.rule())
{ {
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(row + 1, start - spaces), Location::new(row + 1, start - spaces),
@ -172,7 +172,7 @@ pub fn check_noqa(
Range::new(Location::new(row + 1, start), Location::new(row + 1, end)), Range::new(Location::new(row + 1, start), Location::new(row + 1, end)),
); );
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.rules.should_fix(diagnostic.kind.code()) && settings.rules.should_fix(diagnostic.kind.rule())
{ {
if valid_codes.is_empty() { if valid_codes.is_empty() {
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(

View File

@ -75,7 +75,7 @@ pub fn check_tokens(
settings, settings,
autofix, autofix,
) { ) {
if settings.rules.enabled(diagnostic.kind.code()) { if settings.rules.enabled(diagnostic.kind.rule()) {
diagnostics.push(diagnostic); diagnostics.push(diagnostic);
} }
} }
@ -112,7 +112,7 @@ pub fn check_tokens(
diagnostics.extend( diagnostics.extend(
flake8_implicit_str_concat::rules::implicit(tokens) flake8_implicit_str_concat::rules::implicit(tokens)
.into_iter() .into_iter()
.filter(|diagnostic| settings.rules.enabled(diagnostic.kind.code())), .filter(|diagnostic| settings.rules.enabled(diagnostic.kind.rule())),
); );
} }
@ -121,7 +121,7 @@ pub fn check_tokens(
diagnostics.extend( diagnostics.extend(
flake8_commas::rules::trailing_commas(tokens, settings, autofix) flake8_commas::rules::trailing_commas(tokens, settings, autofix)
.into_iter() .into_iter()
.filter(|diagnostic| settings.rules.enabled(diagnostic.kind.code())), .filter(|diagnostic| settings.rules.enabled(diagnostic.kind.rule())),
); );
} }

View File

@ -182,7 +182,7 @@ pub fn check(contents: &str, options: JsValue) -> Result<JsValue, JsValue> {
let messages: Vec<ExpandedMessage> = diagnostics let messages: Vec<ExpandedMessage> = diagnostics
.into_iter() .into_iter()
.map(|diagnostic| ExpandedMessage { .map(|diagnostic| ExpandedMessage {
code: diagnostic.kind.code().clone(), code: diagnostic.kind.rule().clone(),
message: diagnostic.kind.body(), message: diagnostic.kind.body(),
location: diagnostic.location, location: diagnostic.location,
end_location: diagnostic.end_location, end_location: diagnostic.end_location,

View File

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

View File

@ -115,7 +115,7 @@ fn add_noqa_inner(
// duplication, whereby some parent `noqa` directives become // duplication, whereby some parent `noqa` directives become
// redundant. // redundant.
if diagnostic.location.row() == lineno + 1 { if diagnostic.location.row() == lineno + 1 {
codes.insert(diagnostic.kind.code()); codes.insert(diagnostic.kind.rule());
} }
} }

View File

@ -330,7 +330,7 @@ pub fn definition(checker: &mut Checker, definition: &Definition, visibility: &V
violations::MissingReturnTypeSpecialMethod(name.to_string()), violations::MissingReturnTypeSpecialMethod(name.to_string()),
helpers::identifier_range(stmt, checker.locator), helpers::identifier_range(stmt, checker.locator),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
match fixes::add_return_none_annotation(checker.locator, stmt) { match fixes::add_return_none_annotation(checker.locator, stmt) {
Ok(fix) => { Ok(fix) => {
diagnostic.amend(fix); diagnostic.amend(fix);

View File

@ -47,7 +47,7 @@ pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option
}; };
let mut diagnostic = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test)); let mut diagnostic = Diagnostic::new(violations::DoNotAssertFalse, Range::from_located(test));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_stmt(&assertion_error(msg)); generator.unparse_stmt(&assertion_error(msg));
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(

View File

@ -54,7 +54,7 @@ fn duplicate_handler_exceptions<'a>(
), ),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
if unique_elts.len() == 1 { if unique_elts.len() == 1 {
generator.unparse_expr(unique_elts[0], 0); generator.unparse_expr(unique_elts[0], 0);

View File

@ -47,7 +47,7 @@ pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr)); Diagnostic::new(violations::GetAttrWithConstant, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr(&attribute(obj, value), 0); generator.unparse_expr(&attribute(obj, value), 0);
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(

View File

@ -23,7 +23,7 @@ pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[E
violations::RedundantTupleInExceptionHandler(elt.to_string()), violations::RedundantTupleInExceptionHandler(elt.to_string()),
Range::from_located(type_), Range::from_located(type_),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr(elt, 0); generator.unparse_expr(elt, 0);
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(

View File

@ -62,7 +62,7 @@ pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
if expr == child.as_ref() { if expr == child.as_ref() {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::SetAttrWithConstant, Range::from_located(expr)); Diagnostic::new(violations::SetAttrWithConstant, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
assignment(obj, name, value, checker.stylist), assignment(obj, name, value, checker.stylist),
expr.location, expr.location,

View File

@ -66,7 +66,7 @@ pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body:
violations::UnusedLoopControlVariable(name.to_string()), violations::UnusedLoopControlVariable(name.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Prefix the variable name with an underscore. // Prefix the variable name with an underscore.
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("_{name}"), format!("_{name}"),

View File

@ -44,11 +44,11 @@ pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) {
} }
}; };
if !checker.settings.rules.enabled(diagnostic.kind.code()) { if !checker.settings.rules.enabled(diagnostic.kind.rule()) {
return; return;
} }
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let defined_by = checker.current_stmt(); let defined_by = checker.current_stmt();
let defined_in = checker.current_stmt_parent(); let defined_in = checker.current_stmt_parent();
if matches!(defined_by.node, StmtKind::Expr { .. }) { if matches!(defined_by.node, StmtKind::Expr { .. }) {

View File

@ -103,7 +103,7 @@ pub fn unittest_assertion(
violations::UnittestAssertion(unittest_assert.to_string()), violations::UnittestAssertion(unittest_assert.to_string()),
Range::from_located(func), Range::from_located(func),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) { if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_stmt(&stmt, checker.stylist), unparse_stmt(&stmt, checker.stylist),

View File

@ -83,7 +83,7 @@ fn pytest_fixture_parentheses(
violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()), violations::IncorrectFixtureParenthesesStyle(preferred.to_string(), actual.to_string()),
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(fix); diagnostic.amend(fix);
} }
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
@ -180,7 +180,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
violations::UselessYieldFixture(func_name.to_string()), violations::UselessYieldFixture(func_name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"return".to_string(), "return".to_string(),
stmt.location, stmt.location,
@ -252,7 +252,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) {
violations::UnnecessaryAsyncioMarkOnFixture, violations::UnnecessaryAsyncioMarkOnFixture,
Range::from_located(mark), Range::from_located(mark),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let start = Location::new(mark.location.row(), 0); let start = Location::new(mark.location.row(), 0);
let end = Location::new(mark.end_location.unwrap().row() + 1, 0); let end = Location::new(mark.end_location.unwrap().row() + 1, 0);
diagnostic.amend(Fix::deletion(start, end)); diagnostic.amend(Fix::deletion(start, end));
@ -267,7 +267,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) {
violations::ErroneousUseFixturesOnFixture, violations::ErroneousUseFixturesOnFixture,
Range::from_located(mark), Range::from_located(mark),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let start = Location::new(mark.location.row(), 0); let start = Location::new(mark.location.row(), 0);
let end = Location::new(mark.end_location.unwrap().row() + 1, 0); let end = Location::new(mark.end_location.unwrap().row() + 1, 0);
diagnostic.amend(Fix::deletion(start, end)); diagnostic.amend(Fix::deletion(start, end));

View File

@ -22,7 +22,7 @@ fn pytest_mark_parentheses(
), ),
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(fix); diagnostic.amend(fix);
} }
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
@ -75,7 +75,7 @@ fn check_useless_usefixtures(checker: &mut Checker, decorator: &Expr) {
violations::UseFixturesWithoutParameters, violations::UseFixturesWithoutParameters,
Range::from_located(decorator), Range::from_located(decorator),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let at_start = Location::new(decorator.location.row(), decorator.location.column() - 1); let at_start = Location::new(decorator.location.row(), decorator.location.column() - 1);
diagnostic.amend(Fix::deletion(at_start, decorator.end_location.unwrap())); diagnostic.amend(Fix::deletion(at_start, decorator.end_location.unwrap()));
} }

View File

@ -84,7 +84,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::Tuple { &create_expr(ExprKind::Tuple {
@ -114,7 +114,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::List { &create_expr(ExprKind::List {
@ -156,7 +156,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::List { &create_expr(ExprKind::List {
@ -178,7 +178,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(content) = elts_to_csv(elts, checker) { if let Some(content) = elts_to_csv(elts, checker) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
@ -205,7 +205,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr( generator.unparse_expr(
&create_expr(ExprKind::Tuple { &create_expr(ExprKind::Tuple {
@ -227,7 +227,7 @@ fn check_names(checker: &mut Checker, expr: &Expr) {
violations::ParametrizeNamesWrongType(names_type), violations::ParametrizeNamesWrongType(names_type),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(content) = elts_to_csv(elts, checker) { if let Some(content) = elts_to_csv(elts, checker) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,
@ -283,7 +283,7 @@ fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr(&create_expr(value.node.clone()), 0); generator.unparse_expr(&create_expr(value.node.clone()), 0);
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(

View File

@ -32,7 +32,7 @@ pub fn explicit_true_false_in_ifexpr(
violations::IfExprWithTrueFalse(unparse_expr(test, checker.stylist)), violations::IfExprWithTrueFalse(unparse_expr(test, checker.stylist)),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::Call { &create_expr(ExprKind::Call {
@ -77,7 +77,7 @@ pub fn explicit_false_true_in_ifexpr(
violations::IfExprWithFalseTrue(unparse_expr(test, checker.stylist)), violations::IfExprWithFalseTrue(unparse_expr(test, checker.stylist)),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::UnaryOp { &create_expr(ExprKind::UnaryOp {
@ -126,7 +126,7 @@ pub fn twisted_arms_in_ifexpr(
), ),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::IfExp { &create_expr(ExprKind::IfExp {

View File

@ -42,7 +42,7 @@ pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop,
), ),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::Compare { &create_expr(ExprKind::Compare {
@ -86,7 +86,7 @@ pub fn negation_with_not_equal_op(
), ),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr( unparse_expr(
&create_expr(ExprKind::Compare { &create_expr(ExprKind::Compare {
@ -119,7 +119,7 @@ pub fn double_negation(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand
violations::DoubleNegation(operand.to_string()), violations::DoubleNegation(operand.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
unparse_expr(operand, checker.stylist), unparse_expr(operand, checker.stylist),
expr.location, expr.location,

View File

@ -38,7 +38,7 @@ fn key_in_dict(checker: &mut Checker, left: &Expr, right: &Expr, range: Range) {
violations::KeyInDict(left_content.to_string(), value_content.to_string()), violations::KeyInDict(left_content.to_string(), value_content.to_string()),
range, range,
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
value_content.to_string(), value_content.to_string(),
right.location, right.location,

View File

@ -57,7 +57,7 @@ pub fn yoda_conditions(
}, },
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
suggestion, suggestion,
left.location, left.location,

View File

@ -102,7 +102,7 @@ pub fn organize_imports(
} else { } else {
let mut diagnostic = Diagnostic::new(violations::UnsortedImports, range); let mut diagnostic = Diagnostic::new(violations::UnsortedImports, range);
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.rules.should_fix(diagnostic.kind.code()) && settings.rules.should_fix(diagnostic.kind.rule())
{ {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
indent(&expected, indentation), indent(&expected, indentation),

View File

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

View File

@ -151,7 +151,7 @@ pub fn literal_comparisons(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(diagnostic.kind.code()) && !helpers::is_constant_non_singleton(next) { if checker.patch(diagnostic.kind.rule()) && !helpers::is_constant_non_singleton(next) {
bad_ops.insert(0, Cmpop::Is); bad_ops.insert(0, Cmpop::Is);
} }
diagnostics.push(diagnostic); diagnostics.push(diagnostic);
@ -161,7 +161,7 @@ pub fn literal_comparisons(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(diagnostic.kind.code()) && !helpers::is_constant_non_singleton(next) { if checker.patch(diagnostic.kind.rule()) && !helpers::is_constant_non_singleton(next) {
bad_ops.insert(0, Cmpop::IsNot); bad_ops.insert(0, Cmpop::IsNot);
} }
diagnostics.push(diagnostic); diagnostics.push(diagnostic);
@ -179,7 +179,7 @@ pub fn literal_comparisons(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(diagnostic.kind.code()) if checker.patch(diagnostic.kind.rule())
&& !helpers::is_constant_non_singleton(next) && !helpers::is_constant_non_singleton(next)
{ {
bad_ops.insert(0, Cmpop::Is); bad_ops.insert(0, Cmpop::Is);
@ -191,7 +191,7 @@ pub fn literal_comparisons(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(comparator), Range::from_located(comparator),
); );
if checker.patch(diagnostic.kind.code()) if checker.patch(diagnostic.kind.rule())
&& !helpers::is_constant_non_singleton(next) && !helpers::is_constant_non_singleton(next)
{ {
bad_ops.insert(0, Cmpop::IsNot); bad_ops.insert(0, Cmpop::IsNot);
@ -217,7 +217,7 @@ pub fn literal_comparisons(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(diagnostic.kind.code()) if checker.patch(diagnostic.kind.rule())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::Is); bad_ops.insert(idx, Cmpop::Is);
@ -229,7 +229,7 @@ pub fn literal_comparisons(
violations::NoneComparison(op.into()), violations::NoneComparison(op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(diagnostic.kind.code()) if checker.patch(diagnostic.kind.rule())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::IsNot); bad_ops.insert(idx, Cmpop::IsNot);
@ -249,7 +249,7 @@ pub fn literal_comparisons(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(diagnostic.kind.code()) if checker.patch(diagnostic.kind.rule())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::Is); bad_ops.insert(idx, Cmpop::Is);
@ -261,7 +261,7 @@ pub fn literal_comparisons(
violations::TrueFalseComparison(value, op.into()), violations::TrueFalseComparison(value, op.into()),
Range::from_located(next), Range::from_located(next),
); );
if checker.patch(diagnostic.kind.code()) if checker.patch(diagnostic.kind.rule())
&& !helpers::is_constant_non_singleton(comparator) && !helpers::is_constant_non_singleton(comparator)
{ {
bad_ops.insert(idx, Cmpop::IsNot); bad_ops.insert(idx, Cmpop::IsNot);
@ -323,7 +323,7 @@ pub fn not_tests(
violations::NotInTest, violations::NotInTest,
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(diagnostic.kind.code()) && should_fix { if checker.patch(diagnostic.kind.rule()) && should_fix {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
compare(left, &[Cmpop::NotIn], comparators, checker.stylist), compare(left, &[Cmpop::NotIn], comparators, checker.stylist),
expr.location, expr.location,
@ -339,7 +339,7 @@ pub fn not_tests(
violations::NotIsTest, violations::NotIsTest,
Range::from_located(operand), Range::from_located(operand),
); );
if checker.patch(diagnostic.kind.code()) && should_fix { if checker.patch(diagnostic.kind.rule()) && should_fix {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
compare(left, &[Cmpop::IsNot], comparators, checker.stylist), compare(left, &[Cmpop::IsNot], comparators, checker.stylist),
expr.location, expr.location,
@ -455,7 +455,7 @@ pub fn do_not_assign_lambda(checker: &mut Checker, target: &Expr, value: &Expr,
violations::DoNotAssignLambda(id.to_string()), violations::DoNotAssignLambda(id.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if !match_leading_content(stmt, checker.locator) if !match_leading_content(stmt, checker.locator)
&& !match_trailing_content(stmt, checker.locator) && !match_trailing_content(stmt, checker.locator)
{ {

View File

@ -180,7 +180,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
violations::NoBlankLineBeforeFunction(blank_lines_before), violations::NoBlankLineBeforeFunction(blank_lines_before),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete the blank line before the docstring. // Delete the blank line before the docstring.
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(docstring.expr.location.row() - blank_lines_before, 0), Location::new(docstring.expr.location.row() - blank_lines_before, 0),
@ -221,7 +221,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
violations::NoBlankLineAfterFunction(blank_lines_after), violations::NoBlankLineAfterFunction(blank_lines_after),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete the blank line after the docstring. // Delete the blank line after the docstring.
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(docstring.expr.end_location.unwrap().row() + 1, 0), Location::new(docstring.expr.end_location.unwrap().row() + 1, 0),
@ -262,7 +262,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
violations::NoBlankLineBeforeClass(blank_lines_before), violations::NoBlankLineBeforeClass(blank_lines_before),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete the blank line before the class. // Delete the blank line before the class.
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new(docstring.expr.location.row() - blank_lines_before, 0), Location::new(docstring.expr.location.row() - blank_lines_before, 0),
@ -278,7 +278,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
violations::OneBlankLineBeforeClass(blank_lines_before), violations::OneBlankLineBeforeClass(blank_lines_before),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Insert one blank line before the class. // Insert one blank line before the class.
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"\n".to_string(), "\n".to_string(),
@ -315,7 +315,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
violations::OneBlankLineAfterClass(blank_lines_after), violations::OneBlankLineAfterClass(blank_lines_after),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Insert a blank line before the class (replacing any existing lines). // Insert a blank line before the class (replacing any existing lines).
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"\n".to_string(), "\n".to_string(),
@ -350,7 +350,7 @@ pub fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) {
violations::BlankLineAfterSummary(blanks_count), violations::BlankLineAfterSummary(blanks_count),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if blanks_count > 1 { if blanks_count > 1 {
// Find the "summary" line (defined as the first non-blank line). // Find the "summary" line (defined as the first non-blank line).
let mut summary_line = 0; let mut summary_line = 0;
@ -422,7 +422,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
), ),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
@ -472,7 +472,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
), ),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
@ -496,7 +496,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
), ),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
Location::new(docstring.expr.location.row() + i, 0), Location::new(docstring.expr.location.row() + i, 0),
@ -526,7 +526,7 @@ pub fn newline_after_last_paragraph(checker: &mut Checker, docstring: &Docstring
violations::NewLineAfterLastParagraph, violations::NewLineAfterLastParagraph,
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Insert a newline just before the end-quote(s). // Insert a newline just before the end-quote(s).
let num_trailing_quotes = "'''".len(); let num_trailing_quotes = "'''".len();
let num_trailing_spaces = last_line let num_trailing_spaces = last_line
@ -578,7 +578,7 @@ pub fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) {
violations::NoSurroundingWhitespace, violations::NoSurroundingWhitespace,
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(pattern) = leading_quote(contents) { if let Some(pattern) = leading_quote(contents) {
if let Some(quote) = pattern.chars().last() { if let Some(quote) = pattern.chars().last() {
// If removing whitespace would lead to an invalid string of quote // If removing whitespace would lead to an invalid string of quote
@ -988,7 +988,7 @@ fn blanks_and_section_underline(
violations::DashedUnderlineAfterSection(context.section_name.to_string()), violations::DashedUnderlineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Add a dashed line (of the appropriate length) under the section header. // Add a dashed line (of the appropriate length) under the section header.
let content = format!( let content = format!(
"{}{}\n", "{}{}\n",
@ -1026,7 +1026,7 @@ fn blanks_and_section_underline(
violations::SectionUnderlineAfterName(context.section_name.to_string()), violations::SectionUnderlineAfterName(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete any blank lines between the header and the underline. // Delete any blank lines between the header and the underline.
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
@ -1060,7 +1060,7 @@ fn blanks_and_section_underline(
), ),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Replace the existing underline with a line of the appropriate length. // Replace the existing underline with a line of the appropriate length.
let content = format!( let content = format!(
"{}{}\n", "{}{}\n",
@ -1097,7 +1097,7 @@ fn blanks_and_section_underline(
violations::SectionUnderlineNotOverIndented(context.section_name.to_string()), violations::SectionUnderlineNotOverIndented(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Replace the existing indentation with whitespace of the appropriate length. // Replace the existing indentation with whitespace of the appropriate length.
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
@ -1146,7 +1146,7 @@ fn blanks_and_section_underline(
), ),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete any blank lines between the header and content. // Delete any blank lines between the header and content.
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
@ -1184,7 +1184,7 @@ fn blanks_and_section_underline(
violations::DashedUnderlineAfterSection(context.section_name.to_string()), violations::DashedUnderlineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Add a dashed line (of the appropriate length) under the section header. // Add a dashed line (of the appropriate length) under the section header.
let content = format!( let content = format!(
"{}{}\n", "{}{}\n",
@ -1209,7 +1209,7 @@ fn blanks_and_section_underline(
), ),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete any blank lines between the header and content. // Delete any blank lines between the header and content.
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
Location::new( Location::new(
@ -1248,7 +1248,7 @@ fn common_section(
violations::CapitalizeSectionName(context.section_name.to_string()), violations::CapitalizeSectionName(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Replace the section title with the capitalized variant. This requires // Replace the section title with the capitalized variant. This requires
// locating the start and end of the section name. // locating the start and end of the section name.
if let Some(index) = context.line.find(context.section_name) { if let Some(index) = context.line.find(context.section_name) {
@ -1280,7 +1280,7 @@ fn common_section(
violations::SectionNotOverIndented(context.section_name.to_string()), violations::SectionNotOverIndented(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Replace the existing indentation with whitespace of the appropriate length. // Replace the existing indentation with whitespace of the appropriate length.
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
whitespace::clean(docstring.indentation), whitespace::clean(docstring.indentation),
@ -1306,7 +1306,7 @@ fn common_section(
violations::BlankLineAfterLastSection(context.section_name.to_string()), violations::BlankLineAfterLastSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Add a newline after the section. // Add a newline after the section.
diagnostic.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
"\n".to_string(), "\n".to_string(),
@ -1327,7 +1327,7 @@ fn common_section(
violations::BlankLineAfterSection(context.section_name.to_string()), violations::BlankLineAfterSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Add a newline after the section. // Add a newline after the section.
diagnostic.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
"\n".to_string(), "\n".to_string(),
@ -1351,7 +1351,7 @@ fn common_section(
violations::BlankLineBeforeSection(context.section_name.to_string()), violations::BlankLineBeforeSection(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Add a blank line before the section. // Add a blank line before the section.
diagnostic.amend(Fix::insertion( diagnostic.amend(Fix::insertion(
"\n".to_string(), "\n".to_string(),
@ -1540,7 +1540,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
violations::NewLineAfterSectionName(context.section_name.to_string()), violations::NewLineAfterSectionName(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Delete the suffix. This requires locating the end of the section name. // Delete the suffix. This requires locating the end of the section name.
if let Some(index) = context.line.find(context.section_name) { if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters. // Map from bytes to characters.
@ -1586,7 +1586,7 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
violations::SectionNameEndsInColon(context.section_name.to_string()), violations::SectionNameEndsInColon(context.section_name.to_string()),
Range::from_located(docstring.expr), Range::from_located(docstring.expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Replace the suffix. This requires locating the end of the section name. // Replace the suffix. This requires locating the end of the section name.
if let Some(index) = context.line.find(context.section_name) { if let Some(index) = context.line.find(context.section_name) {
// Map from bytes to characters. // Map from bytes to characters.

View File

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

View File

@ -26,7 +26,7 @@ pub fn invalid_literal_comparison(
|| helpers::is_constant_non_singleton(right)) || helpers::is_constant_non_singleton(right))
{ {
let mut diagnostic = Diagnostic::new(violations::IsLiteral(op.into()), location); let mut diagnostic = Diagnostic::new(violations::IsLiteral(op.into()), location);
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(located_op) = &located.get(index) { if let Some(located_op) = &located.get(index) {
assert_eq!(&located_op.node, op); assert_eq!(&located_op.node, op);
if let Some(content) = match &located_op.node { if let Some(content) = match &located_op.node {

View File

@ -32,7 +32,7 @@ pub fn raise_not_implemented(checker: &mut Checker, expr: &Expr) {
}; };
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::RaiseNotImplemented, Range::from_located(expr)); Diagnostic::new(violations::RaiseNotImplemented, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"NotImplementedError".to_string(), "NotImplementedError".to_string(),
expr.location, expr.location,

View File

@ -116,7 +116,7 @@ pub(crate) fn percent_format_extra_named_arguments(
), ),
location, location,
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
match remove_unused_format_arguments_from_dict(&missing, right, checker.locator) { match remove_unused_format_arguments_from_dict(&missing, right, checker.locator) {
Ok(fix) => { Ok(fix) => {
diagnostic.amend(fix); diagnostic.amend(fix);
@ -274,7 +274,7 @@ pub(crate) fn string_dot_format_extra_named_arguments(
), ),
location, location,
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
match remove_unused_keyword_arguments_from_format_call(&missing, location, checker.locator) match remove_unused_keyword_arguments_from_format_call(&missing, location, checker.locator)
{ {
Ok(fix) => { Ok(fix) => {

View File

@ -0,0 +1,56 @@
use rustpython_ast::{Cmpop, Expr, ExprKind};
use crate::ast::types::Range;
use crate::checkers::ast::Checker;
use crate::fix::Fix;
use crate::registry::Diagnostic;
use crate::violations;
/// PLC2201
pub fn misplaced_comparison_constant(
checker: &mut Checker,
expr: &Expr,
left: &Expr,
ops: &[Cmpop],
comparators: &[Expr],
) {
let ([op], [right]) = (ops, comparators) else {
return;
};
if !matches!(
op,
Cmpop::Eq | Cmpop::NotEq | Cmpop::Lt | Cmpop::LtE | Cmpop::Gt | Cmpop::GtE,
) {
return;
}
if !matches!(&left.node, &ExprKind::Constant { .. }) {
return;
}
if matches!(&right.node, &ExprKind::Constant { .. }) {
return;
}
let reversed_op = match op {
Cmpop::Eq => "==",
Cmpop::NotEq => "!=",
Cmpop::Lt => ">",
Cmpop::LtE => ">=",
Cmpop::Gt => "<",
Cmpop::GtE => "<=",
_ => unreachable!("Expected comparison operator"),
};
let suggestion = format!("{right} {reversed_op} {left}");
let mut diagnostic = Diagnostic::new(
violations::MisplacedComparisonConstant(suggestion.clone()),
Range::from_located(expr),
);
if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement(
suggestion,
expr.location,
expr.end_location.unwrap(),
));
}
checker.diagnostics.push(diagnostic);
}

View File

@ -95,7 +95,7 @@ pub fn use_sys_exit(checker: &mut Checker, func: &Expr) {
violations::UseSysExit(name.to_string()), violations::UseSysExit(name.to_string()),
Range::from_located(func), Range::from_located(func),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(content) = get_member_import_name_alias(checker, "sys", "exit") { if let Some(content) = get_member_import_name_alias(checker, "sys", "exit") {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,

View File

@ -20,7 +20,7 @@ pub fn useless_import_alias(checker: &mut Checker, alias: &Alias) {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::UselessImportAlias, Range::from_located(alias)); Diagnostic::new(violations::UselessImportAlias, Range::from_located(alias));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
asname.to_string(), asname.to_string(),
alias.location, alias.location,

View File

@ -157,7 +157,7 @@ pub fn convert_named_tuple_functional_to_class(
violations::ConvertNamedTupleFunctionalToClass(typename.to_string()), violations::ConvertNamedTupleFunctionalToClass(typename.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
match match_defaults(keywords) match match_defaults(keywords)
.and_then(|defaults| create_properties_from_args(args, defaults)) .and_then(|defaults| create_properties_from_args(args, defaults))
{ {

View File

@ -200,7 +200,7 @@ pub fn convert_typed_dict_functional_to_class(
violations::ConvertTypedDictFunctionalToClass(class_name.to_string()), violations::ConvertTypedDictFunctionalToClass(class_name.to_string()),
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
match match_properties_and_total(args, keywords) { match match_properties_and_total(args, keywords) {
Ok((body, total_keyword)) => { Ok((body, total_keyword)) => {
diagnostic.amend(convert_to_class( diagnostic.amend(convert_to_class(

View File

@ -46,7 +46,7 @@ pub fn deprecated_unittest_alias(checker: &mut Checker, expr: &Expr) {
violations::DeprecatedUnittestAlias(attr.to_string(), target.to_string()), violations::DeprecatedUnittestAlias(attr.to_string(), target.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
format!("self.{target}"), format!("self.{target}"),
expr.location, expr.location,

View File

@ -98,7 +98,7 @@ pub(crate) fn format_literals(checker: &mut Checker, summary: &FormatSummary, ex
} }
let mut diagnostic = Diagnostic::new(violations::FormatLiterals, Range::from_located(expr)); let mut diagnostic = Diagnostic::new(violations::FormatLiterals, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
// Currently, the only issue we know of is in LibCST: // Currently, the only issue we know of is in LibCST:
// https://github.com/Instagram/LibCST/issues/846 // https://github.com/Instagram/LibCST/issues/846
if let Ok(contents) = generate_call( if let Ok(contents) = generate_call(

View File

@ -148,7 +148,7 @@ fn handle_making_changes(
violations::OSErrorAlias(compose_call_path(target)), violations::OSErrorAlias(compose_call_path(target)),
Range::from_located(target), Range::from_located(target),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
final_str, final_str,
target.location, target.location,

View File

@ -108,7 +108,7 @@ pub fn replace_stdout_stderr(checker: &mut Checker, expr: &Expr, kwargs: &[Keywo
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::ReplaceStdoutStderr, Range::from_located(expr)); Diagnostic::new(violations::ReplaceStdoutStderr, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) = generate_fix(checker.locator, stdout, stderr) { if let Some(fix) = generate_fix(checker.locator, stdout, stderr) {
diagnostic.amend(fix); diagnostic.amend(fix);
}; };

View File

@ -21,7 +21,7 @@ pub fn replace_universal_newlines(checker: &mut Checker, expr: &Expr, kwargs: &[
), ),
); );
let mut diagnostic = Diagnostic::new(violations::ReplaceUniversalNewlines, range); let mut diagnostic = Diagnostic::new(violations::ReplaceUniversalNewlines, range);
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"text".to_string(), "text".to_string(),
range.location, range.location,

View File

@ -9,7 +9,7 @@ use crate::violations;
fn add_check_for_node<T>(checker: &mut Checker, node: &Located<T>) { fn add_check_for_node<T>(checker: &mut Checker, node: &Located<T>) {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::RewriteCElementTree, Range::from_located(node)); Diagnostic::new(violations::RewriteCElementTree, Range::from_located(node));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let contents = checker let contents = checker
.locator .locator
.slice_source_code_range(&Range::from_located(node)); .slice_source_code_range(&Range::from_located(node));

View File

@ -12,7 +12,7 @@ pub fn rewrite_unicode_literal(checker: &mut Checker, expr: &Expr, kind: Option<
if const_kind.to_lowercase() == "u" { if const_kind.to_lowercase() == "u" {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::RewriteUnicodeLiteral, Range::from_located(expr)); Diagnostic::new(violations::RewriteUnicodeLiteral, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::deletion( diagnostic.amend(Fix::deletion(
expr.location, expr.location,
Location::new(expr.location.row(), expr.location.column() + 1), Location::new(expr.location.row(), expr.location.column() + 1),

View File

@ -159,7 +159,7 @@ pub fn rewrite_yield_from(checker: &mut Checker, stmt: &Stmt) {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::RewriteYieldFrom, Range::from_located(item.stmt)); Diagnostic::new(violations::RewriteYieldFrom, Range::from_located(item.stmt));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let contents = checker let contents = checker
.locator .locator
.slice_source_code_range(&Range::from_located(item.iter)); .slice_source_code_range(&Range::from_located(item.iter));

View File

@ -20,7 +20,7 @@ pub fn super_call_with_parameters(checker: &mut Checker, expr: &Expr, func: &Exp
let Some(mut diagnostic) = super::super_args(scope, &parents, expr, func, args) else { let Some(mut diagnostic) = super::super_args(scope, &parents, expr, func, args) else {
return; return;
}; };
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) = fixes::remove_super_arguments(checker.locator, expr) { if let Some(fix) = fixes::remove_super_arguments(checker.locator, expr) {
diagnostic.amend(fix); diagnostic.amend(fix);
} }

View File

@ -28,7 +28,7 @@ pub fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args:
violations::TypeOfPrimitive(primitive), violations::TypeOfPrimitive(primitive),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
primitive.builtin(), primitive.builtin(),
expr.location, expr.location,

View File

@ -13,7 +13,7 @@ pub fn typing_text_str_alias(checker: &mut Checker, expr: &Expr) {
}) { }) {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::TypingTextStrAlias, Range::from_located(expr)); Diagnostic::new(violations::TypingTextStrAlias, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
"str".to_string(), "str".to_string(),
expr.location, expr.location,

View File

@ -79,7 +79,7 @@ pub fn unnecessary_builtin_import(
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let deleted: Vec<&Stmt> = checker let deleted: Vec<&Stmt> = checker
.deletions .deletions
.iter() .iter()

View File

@ -64,7 +64,7 @@ pub fn unnecessary_future_import(checker: &mut Checker, stmt: &Stmt, names: &[Lo
Range::from_located(stmt), Range::from_located(stmt),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let deleted: Vec<&Stmt> = checker let deleted: Vec<&Stmt> = checker
.deletions .deletions
.iter() .iter()

View File

@ -16,7 +16,7 @@ pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr) {
violations::UsePEP585Annotation(binding.to_string()), violations::UsePEP585Annotation(binding.to_string()),
Range::from_located(expr), Range::from_located(expr),
); );
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
binding.to_lowercase(), binding.to_lowercase(),
expr.location, expr.location,

View File

@ -82,7 +82,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
TypingMember::Optional => { TypingMember::Optional => {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr)); Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let mut generator: Generator = checker.stylist.into(); let mut generator: Generator = checker.stylist.into();
generator.unparse_expr(&optional(slice), 0); generator.unparse_expr(&optional(slice), 0);
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
@ -96,7 +96,7 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
TypingMember::Union => { TypingMember::Union => {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr)); Diagnostic::new(violations::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
match &slice.node { match &slice.node {
ExprKind::Slice { .. } => { ExprKind::Slice { .. } => {
// Invalid type annotation. // Invalid type annotation.

View File

@ -32,7 +32,7 @@ pub fn useless_metaclass_type(checker: &mut Checker, stmt: &Stmt, value: &Expr,
rule(targets, value, Range::from_located(stmt)) else { rule(targets, value, Range::from_located(stmt)) else {
return; return;
}; };
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
let deleted: Vec<&Stmt> = checker let deleted: Vec<&Stmt> = checker
.deletions .deletions
.iter() .iter()

View File

@ -46,7 +46,7 @@ pub fn useless_object_inheritance(
let Some(mut diagnostic) = rule(name, bases, checker.current_scope(), &checker.bindings) else { let Some(mut diagnostic) = rule(name, bases, checker.current_scope(), &checker.bindings) else {
return; return;
}; };
if checker.patch(diagnostic.kind.code()) { if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) = fixes::remove_class_def_base( if let Some(fix) = fixes::remove_class_def_base(
checker.locator, checker.locator,
stmt.location, stmt.location,

View File

@ -1650,9 +1650,9 @@ pub fn ambiguous_unicode_character(
}, },
Range::new(location, end_location), Range::new(location, end_location),
); );
if settings.rules.enabled(diagnostic.kind.code()) { if settings.rules.enabled(diagnostic.kind.rule()) {
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.rules.should_fix(diagnostic.kind.code()) && settings.rules.should_fix(diagnostic.kind.rule())
{ {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
representant.to_string(), representant.to_string(),