Move unparse utility methods onto Generator (#4497)

This commit is contained in:
Charlie Marsh 2023-05-18 11:00:46 -04:00 committed by GitHub
parent d3b18345c5
commit e9c6f16c56
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
40 changed files with 137 additions and 157 deletions

View file

@ -4,7 +4,7 @@ use rustpython_parser::ast::{self, Expr, Operator, Ranged};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{any_over_expr, unparse_expr}; use ruff_python_ast::helpers::any_over_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -62,14 +62,14 @@ fn unparse_string_format_expression(checker: &mut Checker, expr: &Expr) -> Optio
}) => { }) => {
let Some(parent) = checker.ctx.expr_parent() else { let Some(parent) = checker.ctx.expr_parent() else {
if any_over_expr(expr, &has_string_literal) { if any_over_expr(expr, &has_string_literal) {
return Some(unparse_expr(expr, checker.generator())); return Some(checker.generator().expr(expr));
} }
return None; return None;
}; };
// Only evaluate the full BinOp, not the nested components. // Only evaluate the full BinOp, not the nested components.
let Expr::BinOp(_ )= parent else { let Expr::BinOp(_ )= parent else {
if any_over_expr(expr, &has_string_literal) { if any_over_expr(expr, &has_string_literal) {
return Some(unparse_expr(expr, checker.generator())); return Some(checker.generator().expr(expr));
} }
return None; return None;
}; };
@ -81,12 +81,12 @@ fn unparse_string_format_expression(checker: &mut Checker, expr: &Expr) -> Optio
}; };
// "select * from table where val = {}".format(...) // "select * from table where val = {}".format(...)
if attr == "format" && string_literal(value).is_some() { if attr == "format" && string_literal(value).is_some() {
return Some(unparse_expr(expr, checker.generator())); return Some(checker.generator().expr(expr));
}; };
None None
} }
// f"select * from table where val = {val}" // f"select * from table where val = {val}"
Expr::JoinedStr(_) => Some(unparse_expr(expr, checker.generator())), Expr::JoinedStr(_) => Some(checker.generator().expr(expr)),
_ => None, _ => None,
} }
} }

View file

@ -2,7 +2,7 @@ use rustpython_parser::ast::{self, Constant, Expr, Keyword, Ranged};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{unparse_constant, SimpleCallArgs}; use ruff_python_ast::helpers::SimpleCallArgs;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -48,7 +48,7 @@ pub(crate) fn request_without_timeout(
Expr::Constant(ast::ExprConstant { Expr::Constant(ast::ExprConstant {
value: value @ Constant::None, value: value @ Constant::None,
.. ..
}) => Some(unparse_constant(value, checker.generator())), }) => Some(checker.generator().constant(value)),
_ => None, _ => None,
} { } {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Stmt};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -56,7 +55,7 @@ pub(crate) fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg:
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_stmt(&assertion_error(msg), checker.generator()), checker.generator().stmt(&assertion_error(msg)),
stmt.range(), stmt.range(),
))); )));
} }

View file

@ -8,7 +8,6 @@ use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path; use ruff_python_ast::call_path;
use ruff_python_ast::call_path::CallPath; use ruff_python_ast::call_path::CallPath;
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{AsRule, Rule}; use crate::registry::{AsRule, Rule};
@ -97,9 +96,9 @@ fn duplicate_handler_exceptions<'a>(
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
if unique_elts.len() == 1 { if unique_elts.len() == 1 {
unparse_expr(unique_elts[0], checker.generator()) checker.generator().expr(unique_elts[0])
} else { } else {
unparse_expr(&type_pattern(unique_elts), checker.generator()) checker.generator().expr(&type_pattern(unique_elts))
}, },
expr.range(), expr.range(),
))); )));

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -69,7 +69,7 @@ pub(crate) fn getattr_with_constant(
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&attribute(obj, value), checker.generator()), checker.generator().expr(&attribute(obj, value)),
expr.range(), expr.range(),
))); )));
} }

View file

@ -2,7 +2,6 @@ use rustpython_parser::ast::{self, Excepthandler, Expr, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -45,14 +44,14 @@ pub(crate) fn redundant_tuple_in_exception_handler(
}; };
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
RedundantTupleInExceptionHandler { RedundantTupleInExceptionHandler {
name: unparse_expr(elt, checker.generator()), name: checker.generator().expr(elt),
}, },
type_.range(), type_.range(),
); );
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(elt, checker.generator()), checker.generator().expr(elt),
type_.range(), type_.range(),
))); )));
} }

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Stmt};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private};
@ -39,7 +39,7 @@ fn assignment(obj: &Expr, name: &str, value: &Expr, generator: Generator) -> Str
type_comment: None, type_comment: None,
range: TextRange::default(), range: TextRange::default(),
}); });
unparse_stmt(&stmt, generator) generator.stmt(&stmt)
} }
/// B010 /// B010

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Stmt};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use ruff_python_ast::source_code::{Generator, Stylist}; use ruff_python_ast::source_code::{Generator, Stylist};
use ruff_python_ast::whitespace; use ruff_python_ast::whitespace;
@ -201,7 +201,7 @@ fn generate_fix(
type_comment: None, type_comment: None,
range: TextRange::default(), range: TextRange::default(),
}); });
let assignment = unparse_stmt(&node1, generator); let assignment = generator.stmt(&node1);
#[allow(deprecated)] #[allow(deprecated)]
Fix::unspecified_edits( Fix::unspecified_edits(
Edit::insertion( Edit::insertion(
@ -225,7 +225,7 @@ pub(crate) fn string_in_exception(checker: &mut Checker, stmt: &Stmt, exc: &Expr
if let Expr::Call(ast::ExprCall { args, .. }) = exc { if let Expr::Call(ast::ExprCall { args, .. }) = exc {
if let Some(first) = args.first() { if let Some(first) = args.first() {
match first { match first {
// Check for string literals // Check for string literals.
Expr::Constant(ast::ExprConstant { Expr::Constant(ast::ExprConstant {
value: Constant::Str(string), value: Constant::Str(string),
.. ..
@ -257,7 +257,7 @@ pub(crate) fn string_in_exception(checker: &mut Checker, stmt: &Stmt, exc: &Expr
} }
} }
} }
// Check for f-strings // Check for f-strings.
Expr::JoinedStr(_) => { Expr::JoinedStr(_) => {
if checker.settings.rules.enabled(Rule::FStringInException) { if checker.settings.rules.enabled(Rule::FStringInException) {
let indentation = whitespace::indentation(checker.locator, stmt).and_then( let indentation = whitespace::indentation(checker.locator, stmt).and_then(
@ -284,7 +284,7 @@ pub(crate) fn string_in_exception(checker: &mut Checker, stmt: &Stmt, exc: &Expr
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
} }
// Check for .format() calls // Check for .format() calls.
Expr::Call(ast::ExprCall { func, .. }) => { Expr::Call(ast::ExprCall { func, .. }) => {
if checker.settings.rules.enabled(Rule::DotFormatInException) { if checker.settings.rules.enabled(Rule::DotFormatInException) {
if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) =

View file

@ -13,7 +13,7 @@ use ruff_diagnostics::{AlwaysAutofixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::{trailing_comment_start_offset, unparse_expr}; use ruff_python_ast::helpers::trailing_comment_start_offset;
use ruff_python_ast::types::RefEquality; use ruff_python_ast::types::RefEquality;
use ruff_python_stdlib::identifiers::is_identifier; use ruff_python_stdlib::identifiers::is_identifier;
@ -443,7 +443,7 @@ pub(crate) fn non_unique_enums<'a, 'b>(
if !seen_targets.insert(ComparableExpr::from(value)) { if !seen_targets.insert(ComparableExpr::from(value)) {
let diagnostic = Diagnostic::new( let diagnostic = Diagnostic::new(
NonUniqueEnums { NonUniqueEnums {
value: unparse_expr(value, checker.generator()), value: checker.generator().expr(value),
}, },
stmt.range(), stmt.range(),
); );
@ -612,7 +612,7 @@ pub(crate) fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) {
let bool_op = node; let bool_op = node;
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&bool_op, checker.generator()), checker.generator().expr(&bool_op),
expr.range(), expr.range(),
))); )));
} }

View file

@ -4,7 +4,6 @@ use rustpython_parser::ast::{self, Expr, Operator, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -61,7 +60,7 @@ fn traverse_union<'a>(
if !seen_nodes.insert(expr.into()) { if !seen_nodes.insert(expr.into()) {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
DuplicateUnionMember { DuplicateUnionMember {
duplicate_name: unparse_expr(expr, checker.generator()), duplicate_name: checker.generator().expr(expr),
}, },
expr.range(), expr.range(),
); );
@ -80,10 +79,9 @@ fn traverse_union<'a>(
// Replace the parent with its non-duplicate child. // Replace the parent with its non-duplicate child.
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr( checker
if expr == left.as_ref() { right } else { left }, .generator()
checker.generator(), .expr(if expr == left.as_ref() { right } else { left }),
),
parent.range(), parent.range(),
))); )));
} }

View file

@ -10,7 +10,7 @@ use std::borrow::Cow;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{has_comments_in, unparse_stmt, Truthiness}; use ruff_python_ast::helpers::{has_comments_in, Truthiness};
use ruff_python_ast::source_code::{Locator, Stylist}; use ruff_python_ast::source_code::{Locator, Stylist};
use ruff_python_ast::visitor::Visitor; use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{visitor, whitespace}; use ruff_python_ast::{visitor, whitespace};
@ -198,7 +198,7 @@ pub(crate) fn unittest_assertion(
if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) { if let Ok(stmt) = unittest_assert.generate_assert(args, keywords) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_stmt(&stmt, checker.generator()), checker.generator().stmt(&stmt),
expr.range(), expr.range(),
))); )));
} }

View file

@ -4,7 +4,6 @@ use rustpython_parser::{lexer, Mode, Tok};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{AsRule, Rule}; use crate::registry::{AsRule, Rule};
@ -78,7 +77,7 @@ fn elts_to_csv(elts: &[Expr], checker: &Checker) -> Option<String> {
kind: None, kind: None,
range: TextRange::default(), range: TextRange::default(),
}); });
Some(unparse_expr(&node, checker.generator())) Some(checker.generator().expr(&node))
} }
/// Returns the range of the `name` argument of `@pytest.mark.parametrize`. /// Returns the range of the `name` argument of `@pytest.mark.parametrize`.
@ -164,7 +163,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) {
}); });
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
format!("({})", unparse_expr(&node, checker.generator())), format!("({})", checker.generator().expr(&node)),
name_range, name_range,
))); )));
} }
@ -195,7 +194,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) {
}); });
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node, checker.generator()), checker.generator().expr(&node),
name_range, name_range,
))); )));
} }
@ -228,7 +227,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) {
}); });
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node, checker.generator()), checker.generator().expr(&node),
expr.range(), expr.range(),
))); )));
} }
@ -278,7 +277,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) {
}); });
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
format!("({})", unparse_expr(&node, checker.generator())), format!("({})", checker.generator().expr(&node)),
expr.range(), expr.range(),
))); )));
} }
@ -373,7 +372,7 @@ fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) {
let node = value.clone(); let node = value.clone();
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node, checker.generator()), checker.generator().expr(&node),
expr.range(), expr.range(),
))); )));
} }

View file

@ -10,7 +10,7 @@ use rustpython_parser::ast::{self, Boolop, Cmpop, Expr, ExprContext, Ranged, Una
use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::{contains_effect, has_comments, unparse_expr, Truthiness}; use ruff_python_ast::helpers::{contains_effect, has_comments, Truthiness};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -368,7 +368,7 @@ pub(crate) fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) {
// multiple duplicates, the fixes will conflict. // multiple duplicates, the fixes will conflict.
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&bool_op, checker.generator()), checker.generator().expr(&bool_op),
expr.range(), expr.range(),
))); )));
} }
@ -455,7 +455,7 @@ pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
let in_expr = node2.into(); let in_expr = node2.into();
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
CompareWithTuple { CompareWithTuple {
replacement: unparse_expr(&in_expr, checker.generator()), replacement: checker.generator().expr(&in_expr),
}, },
expr.range(), expr.range(),
); );
@ -479,7 +479,7 @@ pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&in_expr, checker.generator()), checker.generator().expr(&in_expr),
expr.range(), expr.range(),
))); )));
} }
@ -613,7 +613,7 @@ pub(crate) fn get_short_circuit_edit(
} }
} }
} else { } else {
unparse_expr(expr, checker.generator()) checker.generator().expr(expr)
}; };
Edit::range_replacement(content, range) Edit::range_replacement(content, range)
} }

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -149,7 +148,7 @@ fn check_os_environ_subscript(checker: &mut Checker, expr: &Expr) {
let new_env_var = node.into(); let new_env_var = node.into();
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&new_env_var, checker.generator()), checker.generator().expr(&new_env_var),
slice.range(), slice.range(),
))); )));
} }

View file

@ -8,8 +8,7 @@ use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::{ComparableConstant, ComparableExpr, ComparableStmt}; use ruff_python_ast::comparable::{ComparableConstant, ComparableExpr, ComparableStmt};
use ruff_python_ast::helpers::{ use ruff_python_ast::helpers::{
any_over_expr, contains_effect, first_colon_range, has_comments, has_comments_in, unparse_expr, any_over_expr, contains_effect, first_colon_range, has_comments, has_comments_in,
unparse_stmt,
}; };
use ruff_python_ast::newlines::StrExt; use ruff_python_ast::newlines::StrExt;
use ruff_python_semantic::context::Context; use ruff_python_semantic::context::Context;
@ -348,7 +347,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) {
return; return;
} }
let condition = unparse_expr(test, checker.generator()); let condition = checker.generator().expr(test);
let fixable = matches!(if_return, Bool::True) let fixable = matches!(if_return, Bool::True)
&& matches!(else_return, Bool::False) && matches!(else_return, Bool::False)
&& !has_comments(stmt, checker.locator) && !has_comments(stmt, checker.locator)
@ -364,7 +363,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) {
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_stmt(&node.into(), checker.generator()), checker.generator().stmt(&node.into()),
stmt.range(), stmt.range(),
))); )));
} else { } else {
@ -387,7 +386,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) {
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_stmt(&node2.into(), checker.generator()), checker.generator().stmt(&node2.into()),
stmt.range(), stmt.range(),
))); )));
}; };
@ -504,7 +503,7 @@ pub(crate) fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: O
let target_var = &body_targets[0]; let target_var = &body_targets[0];
let ternary = ternary(target_var, body_value, test, orelse_value); let ternary = ternary(target_var, body_value, test, orelse_value);
let contents = unparse_stmt(&ternary, checker.generator()); let contents = checker.generator().stmt(&ternary);
// Don't flag if the resulting expression would exceed the maximum line length. // Don't flag if the resulting expression would exceed the maximum line length.
let line_start = checker.locator.line_start(stmt.start()); let line_start = checker.locator.line_start(stmt.start());
@ -859,7 +858,7 @@ pub(crate) fn use_dict_get_with_default(
type_comment: None, type_comment: None,
range: TextRange::default(), range: TextRange::default(),
}; };
let contents = unparse_stmt(&node5.into(), checker.generator()); let contents = checker.generator().stmt(&node5.into());
// Don't flag if the resulting expression would exceed the maximum line length. // Don't flag if the resulting expression would exceed the maximum line length.
let line_start = checker.locator.line_start(stmt.start()); let line_start = checker.locator.line_start(stmt.start());

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Unaryop}
use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -97,7 +96,7 @@ pub(crate) fn explicit_true_false_in_ifexpr(
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
IfExprWithTrueFalse { IfExprWithTrueFalse {
expr: unparse_expr(test, checker.generator()), expr: checker.generator().expr(test),
}, },
expr.range(), expr.range(),
); );
@ -105,7 +104,7 @@ pub(crate) fn explicit_true_false_in_ifexpr(
if matches!(test, Expr::Compare(_)) { if matches!(test, Expr::Compare(_)) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&test.clone(), checker.generator()), checker.generator().expr(&test.clone()),
expr.range(), expr.range(),
))); )));
} else if checker.ctx.is_builtin("bool") { } else if checker.ctx.is_builtin("bool") {
@ -122,7 +121,7 @@ pub(crate) fn explicit_true_false_in_ifexpr(
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node1.into(), checker.generator()), checker.generator().expr(&node1.into()),
expr.range(), expr.range(),
))); )));
}; };
@ -153,7 +152,7 @@ pub(crate) fn explicit_false_true_in_ifexpr(
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
IfExprWithFalseTrue { IfExprWithFalseTrue {
expr: unparse_expr(test, checker.generator()), expr: checker.generator().expr(test),
}, },
expr.range(), expr.range(),
); );
@ -166,7 +165,7 @@ pub(crate) fn explicit_false_true_in_ifexpr(
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node1.into(), checker.generator()), checker.generator().expr(&node1.into()),
expr.range(), expr.range(),
))); )));
} }
@ -201,8 +200,8 @@ pub(crate) fn twisted_arms_in_ifexpr(
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
IfExprWithTwistedArms { IfExprWithTwistedArms {
expr_body: unparse_expr(body, checker.generator()), expr_body: checker.generator().expr(body),
expr_else: unparse_expr(orelse, checker.generator()), expr_else: checker.generator().expr(orelse),
}, },
expr.range(), expr.range(),
); );
@ -218,7 +217,7 @@ pub(crate) fn twisted_arms_in_ifexpr(
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node3.into(), checker.generator()), checker.generator().expr(&node3.into()),
expr.range(), expr.range(),
))); )));
} }

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Cmpop, Expr, ExprContext, Ranged, Stmt, Unary
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_semantic::scope::ScopeKind; use ruff_python_semantic::scope::ScopeKind;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -107,8 +107,8 @@ pub(crate) fn negation_with_equal_op(
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
NegateEqualOp { NegateEqualOp {
left: unparse_expr(left, checker.generator()), left: checker.generator().expr(left),
right: unparse_expr(&comparators[0], checker.generator()), right: checker.generator().expr(&comparators[0]),
}, },
expr.range(), expr.range(),
); );
@ -121,7 +121,7 @@ pub(crate) fn negation_with_equal_op(
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node.into(), checker.generator()), checker.generator().expr(&node.into()),
expr.range(), expr.range(),
))); )));
} }
@ -157,8 +157,8 @@ pub(crate) fn negation_with_not_equal_op(
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
NegateNotEqualOp { NegateNotEqualOp {
left: unparse_expr(left, checker.generator()), left: checker.generator().expr(left),
right: unparse_expr(&comparators[0], checker.generator()), right: checker.generator().expr(&comparators[0]),
}, },
expr.range(), expr.range(),
); );
@ -171,7 +171,7 @@ pub(crate) fn negation_with_not_equal_op(
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node.into(), checker.generator()), checker.generator().expr(&node.into()),
expr.range(), expr.range(),
))); )));
} }
@ -192,7 +192,7 @@ pub(crate) fn double_negation(checker: &mut Checker, expr: &Expr, op: Unaryop, o
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
DoubleNegation { DoubleNegation {
expr: unparse_expr(operand, checker.generator()), expr: checker.generator().expr(operand),
}, },
expr.range(), expr.range(),
); );
@ -200,7 +200,7 @@ pub(crate) fn double_negation(checker: &mut Checker, expr: &Expr, op: Unaryop, o
if checker.ctx.in_boolean_test() { if checker.ctx.in_boolean_test() {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(operand, checker.generator()), checker.generator().expr(operand),
expr.range(), expr.range(),
))); )));
} else if checker.ctx.is_builtin("bool") { } else if checker.ctx.is_builtin("bool") {
@ -217,7 +217,7 @@ pub(crate) fn double_negation(checker: &mut Checker, expr: &Expr, op: Unaryop, o
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&node1.into(), checker.generator()), checker.generator().expr(&node1.into()),
expr.range(), expr.range(),
))); )));
}; };

View file

@ -6,7 +6,7 @@ use unicode_width::UnicodeWidthStr;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -198,7 +198,7 @@ fn return_stmt(id: &str, test: &Expr, target: &Expr, iter: &Expr, generator: Gen
value: Some(Box::new(node2.into())), value: Some(Box::new(node2.into())),
range: TextRange::default(), range: TextRange::default(),
}; };
unparse_stmt(&node3.into(), generator) generator.stmt(&node3.into())
} }
/// SIM110, SIM111 /// SIM110, SIM111

View file

@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation, CacheKey}; use ruff_macros::{derive_message_formats, violation, CacheKey};
use ruff_python_ast::helpers::{resolve_imported_module_path, unparse_stmt}; use ruff_python_ast::helpers::resolve_imported_module_path;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
use ruff_python_stdlib::identifiers::is_identifier; use ruff_python_stdlib::identifiers::is_identifier;
@ -112,7 +112,7 @@ fn fix_banned_relative_import(
level: Some(Int::new(0)), level: Some(Int::new(0)),
range: TextRange::default(), range: TextRange::default(),
}; };
let content = unparse_stmt(&node.into(), generator); let content = generator.stmt(&node.into());
#[allow(deprecated)] #[allow(deprecated)]
Some(Fix::unspecified(Edit::range_replacement( Some(Fix::unspecified(Edit::range_replacement(
content, content,

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Expr, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -80,7 +79,7 @@ pub(crate) fn static_join_to_fstring(checker: &mut Checker, expr: &Expr, joiner:
// convertible to f-string parts). // convertible to f-string parts).
let Some(new_expr) = build_fstring(joiner, joinees) else { return }; let Some(new_expr) = build_fstring(joiner, joinees) else { return };
let contents = unparse_expr(&new_expr, checker.generator()); let contents = checker.generator().expr(&new_expr);
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
StaticJoinToFString { StaticJoinToFString {

View file

@ -2,7 +2,6 @@ use ruff_text_size::{TextLen, TextRange};
use rustpython_parser::ast::{self, Cmpop, Expr}; use rustpython_parser::ast::{self, Cmpop, Expr};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_ast::newlines::Line; use ruff_python_ast::newlines::Line;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
@ -22,7 +21,7 @@ pub(crate) fn compare(
comparators: comparators.to_vec(), comparators: comparators.to_vec(),
range: TextRange::default(), range: TextRange::default(),
}; };
unparse_expr(&node.into(), generator) generator.expr(&node.into())
} }
pub(super) fn is_overlong( pub(super) fn is_overlong(

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Arg, Arguments, Constant, Expr, Ranged, Stmt}
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{has_leading_content, has_trailing_content, unparse_stmt}; use ruff_python_ast::helpers::{has_leading_content, has_trailing_content};
use ruff_python_ast::newlines::StrExt; use ruff_python_ast::newlines::StrExt;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
use ruff_python_ast::whitespace::leading_space; use ruff_python_ast::whitespace::leading_space;
@ -210,7 +210,7 @@ fn function(
type_comment: None, type_comment: None,
range: TextRange::default(), range: TextRange::default(),
}); });
return unparse_stmt(&func, generator); return generator.stmt(&func);
} }
} }
let func = Stmt::FunctionDef(ast::StmtFunctionDef { let func = Stmt::FunctionDef(ast::StmtFunctionDef {
@ -222,5 +222,5 @@ fn function(
type_comment: None, type_comment: None,
range: TextRange::default(), range: TextRange::default(),
}); });
unparse_stmt(&func, generator) generator.stmt(&func)
} }

View file

@ -6,7 +6,6 @@ use rustpython_parser::ast::{self, Expr, Ranged};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::{ComparableConstant, ComparableExpr}; use ruff_python_ast::comparable::{ComparableConstant, ComparableExpr};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::{AsRule, Rule}; use crate::registry::{AsRule, Rule};
@ -106,7 +105,7 @@ pub(crate) fn repeated_keys(checker: &mut Checker, keys: &[Option<Expr>], values
let is_duplicate_value = seen_values.contains(&comparable_value); let is_duplicate_value = seen_values.contains(&comparable_value);
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
MultiValueRepeatedKeyLiteral { MultiValueRepeatedKeyLiteral {
name: unparse_expr(key, checker.generator()), name: checker.generator().expr(key),
repeated_value: is_duplicate_value, repeated_value: is_duplicate_value,
}, },
key.range(), key.range(),

View file

@ -4,7 +4,6 @@ use rustpython_parser::ast::{self, Cmpop, Constant, Expr, Ranged};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{unparse_constant, unparse_expr};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -117,8 +116,8 @@ pub(crate) fn compare_to_empty_string(
if let Expr::Constant(ast::ExprConstant { value, .. }) = &lhs { if let Expr::Constant(ast::ExprConstant { value, .. }) = &lhs {
if let Constant::Str(s) = value { if let Constant::Str(s) = value {
if s.is_empty() { if s.is_empty() {
let constant = unparse_constant(value, checker.generator()); let constant = checker.generator().constant(value);
let expr = unparse_expr(rhs, checker.generator()); let expr = checker.generator().expr(rhs);
let existing = format!("{constant} {op} {expr}"); let existing = format!("{constant} {op} {expr}");
let replacement = format!("{}{expr}", op.into_unary()); let replacement = format!("{}{expr}", op.into_unary());
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
@ -137,8 +136,8 @@ pub(crate) fn compare_to_empty_string(
if let Expr::Constant(ast::ExprConstant { value, .. }) = &rhs { if let Expr::Constant(ast::ExprConstant { value, .. }) = &rhs {
if let Constant::Str(s) = value { if let Constant::Str(s) = value {
if s.is_empty() { if s.is_empty() {
let expr = unparse_expr(lhs, checker.generator()); let expr = checker.generator().expr(lhs);
let constant = unparse_constant(value, checker.generator()); let constant = checker.generator().constant(value);
let existing = format!("{expr} {op} {constant}"); let existing = format!("{expr} {op} {constant}");
let replacement = format!("{}{expr}", op.into_unary()); let replacement = format!("{}{expr}", op.into_unary());
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(

View file

@ -5,7 +5,6 @@ use rustpython_parser::ast::{self, Cmpop, Expr, Ranged};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_constant;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -106,9 +105,9 @@ pub(crate) fn comparison_of_constant(
{ {
let diagnostic = Diagnostic::new( let diagnostic = Diagnostic::new(
ComparisonOfConstant { ComparisonOfConstant {
left_constant: unparse_constant(left_constant, checker.generator()), left_constant: checker.generator().constant(left_constant),
op: op.into(), op: op.into(),
right_constant: unparse_constant(right_constant, checker.generator()), right_constant: checker.generator().constant(right_constant),
}, },
left.range(), left.range(),
); );

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, Ranged, Unaryop};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::rules::pylint::settings::ConstantType; use crate::rules::pylint::settings::ConstantType;
@ -79,7 +78,7 @@ pub(crate) fn magic_value_comparison(checker: &mut Checker, left: &Expr, compara
if is_magic_value(value, &checker.settings.pylint.allow_magic_value_types) { if is_magic_value(value, &checker.settings.pylint.allow_magic_value_types) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
MagicValueComparison { MagicValueComparison {
value: unparse_expr(comparison_expr, checker.generator()), value: checker.generator().expr(comparison_expr),
}, },
comparison_expr.range(), comparison_expr.range(),
)); ));

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Alias, Int, Ranged, Stmt};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -67,7 +66,7 @@ pub(crate) fn manual_from_import(
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_stmt(&node.into(), checker.generator()), checker.generator().stmt(&node.into()),
stmt.range(), stmt.range(),
))); )));
} }

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Expr, Keyword, Ranged};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{has_comments, unparse_expr}; use ruff_python_ast::helpers::has_comments;
use ruff_python_semantic::context::Context; use ruff_python_semantic::context::Context;
use crate::{checkers::ast::Checker, registry::AsRule}; use crate::{checkers::ast::Checker, registry::AsRule};
@ -149,7 +149,7 @@ pub(crate) fn nested_min_max(
}); });
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&flattened_expr, checker.generator()), checker.generator().expr(&flattened_expr),
expr.range(), expr.range(),
))); )));
} }

View file

@ -6,7 +6,7 @@ use rustpython_parser::ast::{self, Expr, ExprContext, Ranged, Stmt, Withitem};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_ast::statement_visitor::{walk_stmt, StatementVisitor}; use ruff_python_ast::statement_visitor::{walk_stmt, StatementVisitor};
use ruff_python_ast::types::Node; use ruff_python_ast::types::Node;
use ruff_python_semantic::context::Context; use ruff_python_semantic::context::Context;
@ -393,7 +393,7 @@ pub(crate) fn redefined_loop_name<'a, 'b>(checker: &'a mut Checker<'b>, node: &N
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
RedefinedLoopName { RedefinedLoopName {
name: unparse_expr(outer_assignment_target.expr, checker.generator()), name: checker.generator().expr(outer_assignment_target.expr),
outer_kind: outer_assignment_target.binding_kind, outer_kind: outer_assignment_target.binding_kind,
inner_kind: inner_assignment_target.binding_kind, inner_kind: inner_assignment_target.binding_kind,
}, },

View file

@ -5,7 +5,6 @@ use rustpython_parser::ast::{self, Boolop, Expr, Ranged};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::hashable::HashableExpr; use ruff_python_ast::hashable::HashableExpr;
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -66,11 +65,11 @@ pub(crate) fn repeated_isinstance_calls(
if num_calls > 1 && types.len() > 1 { if num_calls > 1 && types.len() > 1 {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
RepeatedIsinstanceCalls { RepeatedIsinstanceCalls {
obj: unparse_expr(obj.as_expr(), checker.generator()), obj: checker.generator().expr(obj.as_expr()),
types: types types: types
.iter() .iter()
.map(HashableExpr::as_expr) .map(HashableExpr::as_expr)
.map(|expr| unparse_expr(expr, checker.generator())) .map(|expr| checker.generator().expr(expr))
.sorted() .sorted()
.collect(), .collect(),
}, },

View file

@ -5,7 +5,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Keyword, Ranged,
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
use ruff_python_stdlib::identifiers::is_identifier; use ruff_python_stdlib::identifiers::is_identifier;
@ -175,10 +175,7 @@ fn convert_to_class(
) -> Fix { ) -> Fix {
#[allow(deprecated)] #[allow(deprecated)]
Fix::unspecified(Edit::range_replacement( Fix::unspecified(Edit::range_replacement(
unparse_stmt( generator.stmt(&create_class_def_stmt(typename, body, base_class)),
&create_class_def_stmt(typename, body, base_class),
generator,
),
stmt.range(), stmt.range(),
)) ))
} }

View file

@ -5,7 +5,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Keyword, Ranged,
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_stmt;
use ruff_python_ast::source_code::Generator; use ruff_python_ast::source_code::Generator;
use ruff_python_stdlib::identifiers::is_identifier; use ruff_python_stdlib::identifiers::is_identifier;
@ -226,10 +226,12 @@ fn convert_to_class(
) -> Fix { ) -> Fix {
#[allow(deprecated)] #[allow(deprecated)]
Fix::unspecified(Edit::range_replacement( Fix::unspecified(Edit::range_replacement(
unparse_stmt( generator.stmt(&create_class_def_stmt(
&create_class_def_stmt(class_name, body, total_keyword, base_class), class_name,
generator, body,
), total_keyword,
base_class,
)),
stmt.range(), stmt.range(),
)) ))
} }

View file

@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Expr, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -51,7 +50,7 @@ pub(crate) fn lru_cache_without_parameters(checker: &mut Checker, decorator_list
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(func, checker.generator()), checker.generator().expr(func),
expr.range(), expr.range(),
))); )));
} }

View file

@ -4,7 +4,7 @@ use rustpython_parser::ast::{self, Constant, Expr, Keyword, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_constant;
use ruff_python_ast::str::is_implicit_concatenation; use ruff_python_ast::str::is_implicit_concatenation;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -70,7 +70,7 @@ pub(crate) fn native_literals(
} else { } else {
Constant::Str(String::new()) Constant::Str(String::new())
}; };
let content = unparse_constant(&constant, checker.generator()); let content = checker.generator().constant(&constant);
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
content, content,

View file

@ -4,7 +4,7 @@ use rustpython_parser::ast::{self, Excepthandler, Expr, ExprContext, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path::compose_call_path; use ruff_python_ast::call_path::compose_call_path;
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_semantic::context::Context; use ruff_python_semantic::context::Context;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -117,7 +117,7 @@ fn tuple_diagnostic(checker: &mut Checker, target: &Expr, aliases: &[&Expr]) {
}; };
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
format!("({})", unparse_expr(&node.into(), checker.generator())), format!("({})", checker.generator().expr(&node.into())),
target.range(), target.range(),
))); )));
} }

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, Operator, Ranged};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use ruff_python_semantic::analyze::typing::Pep604Operator; use ruff_python_semantic::analyze::typing::Pep604Operator;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
@ -67,7 +67,7 @@ pub(crate) fn use_pep604_annotation(
if fixable && checker.patch(diagnostic.kind.rule()) { if fixable && checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&optional(slice), checker.generator()), checker.generator().expr(&optional(slice)),
expr.range(), expr.range(),
))); )));
} }
@ -83,7 +83,7 @@ pub(crate) fn use_pep604_annotation(
Expr::Tuple(ast::ExprTuple { elts, .. }) => { Expr::Tuple(ast::ExprTuple { elts, .. }) => {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&union(elts), checker.generator()), checker.generator().expr(&union(elts)),
expr.range(), expr.range(),
))); )));
} }
@ -91,7 +91,7 @@ pub(crate) fn use_pep604_annotation(
// Single argument. // Single argument.
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(slice, checker.generator()), checker.generator().expr(slice),
expr.range(), expr.range(),
))); )));
} }

View file

@ -5,7 +5,6 @@ use rustpython_parser::ast::{self, Expr, Operator, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::unparse_expr;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -94,7 +93,7 @@ pub(crate) fn use_pep604_isinstance(
if checker.patch(diagnostic.kind.rule()) { if checker.patch(diagnostic.kind.rule()) {
#[allow(deprecated)] #[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( diagnostic.set_fix(Fix::unspecified(Edit::range_replacement(
unparse_expr(&union(elts), checker.generator()), checker.generator().expr(&union(elts)),
types.range(), types.range(),
))); )));
} }

View file

@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Expr, ExprContext, Operator, Ranged};
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::{has_comments, unparse_expr}; use ruff_python_ast::helpers::has_comments;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::registry::AsRule; use crate::registry::AsRule;
@ -130,8 +130,8 @@ pub(crate) fn collection_literal_concatenation(checker: &mut Checker, expr: &Exp
let contents = match kind { let contents = match kind {
// Wrap the new expression in parentheses if it was a tuple // Wrap the new expression in parentheses if it was a tuple
Kind::Tuple => format!("({})", unparse_expr(&new_expr, checker.generator())), Kind::Tuple => format!("({})", checker.generator().expr(&new_expr)),
Kind::List => unparse_expr(&new_expr, checker.generator()), Kind::List => checker.generator().expr(&new_expr),
}; };
let fixable = !has_comments(expr, checker.locator); let fixable = !has_comments(expr, checker.locator);

View file

@ -17,27 +17,9 @@ use smallvec::SmallVec;
use crate::call_path::CallPath; use crate::call_path::CallPath;
use crate::newlines::UniversalNewlineIterator; use crate::newlines::UniversalNewlineIterator;
use crate::source_code::{Generator, Indexer, Locator}; use crate::source_code::{Indexer, Locator};
use crate::statement_visitor::{walk_body, walk_stmt, StatementVisitor}; use crate::statement_visitor::{walk_body, walk_stmt, StatementVisitor};
/// Generate source code from an [`Expr`].
pub fn unparse_expr(expr: &Expr, mut generator: Generator) -> String {
generator.unparse_expr(expr, 0);
generator.generate()
}
/// Generate source code from a [`Stmt`].
pub fn unparse_stmt(stmt: &Stmt, mut generator: Generator) -> String {
generator.unparse_stmt(stmt);
generator.generate()
}
/// Generate source code from an [`Constant`].
pub fn unparse_constant(constant: &Constant, mut generator: Generator) -> String {
generator.unparse_constant(constant);
generator.generate()
}
fn is_iterable_initializer<F>(id: &str, is_builtin: F) -> bool fn is_iterable_initializer<F>(id: &str, is_builtin: F) -> bool
where where
F: Fn(&str) -> bool, F: Fn(&str) -> bool,

View file

@ -101,8 +101,22 @@ impl<'a> Generator<'a> {
} }
} }
pub fn generate(self) -> String { /// Generate source code from a [`Stmt`].
self.buffer pub fn stmt(mut self, stmt: &Stmt) -> String {
self.unparse_stmt(stmt);
self.generate()
}
/// Generate source code from an [`Expr`].
pub fn expr(mut self, expr: &Expr) -> String {
self.unparse_expr(expr, 0);
self.generate()
}
/// Generate source code from a [`Constant`].
pub fn constant(mut self, constant: &Constant) -> String {
self.unparse_constant(constant);
self.generate()
} }
fn newline(&mut self) { fn newline(&mut self) {
@ -165,13 +179,17 @@ impl<'a> Generator<'a> {
self.p_if(!std::mem::take(first), s); self.p_if(!std::mem::take(first), s);
} }
pub fn unparse_suite<U>(&mut self, suite: &Suite<U>) { pub(crate) fn generate(self) -> String {
self.buffer
}
pub(crate) fn unparse_suite<U>(&mut self, suite: &Suite<U>) {
for stmt in suite { for stmt in suite {
self.unparse_stmt(stmt); self.unparse_stmt(stmt);
} }
} }
pub fn unparse_stmt<U>(&mut self, ast: &Stmt<U>) { pub(crate) fn unparse_stmt<U>(&mut self, ast: &Stmt<U>) {
macro_rules! statement { macro_rules! statement {
($body:block) => {{ ($body:block) => {{
self.newline(); self.newline();
@ -824,7 +842,7 @@ impl<'a> Generator<'a> {
self.body(&ast.body); self.body(&ast.body);
} }
pub fn unparse_expr<U>(&mut self, ast: &Expr<U>, level: u8) { pub(crate) fn unparse_expr<U>(&mut self, ast: &Expr<U>, level: u8) {
macro_rules! opprec { macro_rules! opprec {
($opty:ident, $x:expr, $enu:path, $($var:ident($op:literal, $prec:ident)),*$(,)?) => { ($opty:ident, $x:expr, $enu:path, $($var:ident($op:literal, $prec:ident)),*$(,)?) => {
match $x { match $x {
@ -1218,7 +1236,7 @@ impl<'a> Generator<'a> {
} }
} }
pub fn unparse_constant(&mut self, constant: &Constant) { pub(crate) fn unparse_constant(&mut self, constant: &Constant) {
assert_eq!(f64::MAX_10_EXP, 308); assert_eq!(f64::MAX_10_EXP, 308);
let inf_str = "1e309"; let inf_str = "1e309";
match constant { match constant {