diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs index 5e322d9e3ad76..d238c5dbe0635 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs @@ -4,7 +4,7 @@ use rustpython_parser::ast::{self, Expr, Operator, Ranged}; use ruff_diagnostics::{Diagnostic, 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; @@ -62,14 +62,14 @@ fn unparse_string_format_expression(checker: &mut Checker, expr: &Expr) -> Optio }) => { let Some(parent) = checker.ctx.expr_parent() else { if any_over_expr(expr, &has_string_literal) { - return Some(unparse_expr(expr, checker.generator())); + return Some(checker.generator().expr(expr)); } return None; }; // Only evaluate the full BinOp, not the nested components. let Expr::BinOp(_ )= parent else { if any_over_expr(expr, &has_string_literal) { - return Some(unparse_expr(expr, checker.generator())); + return Some(checker.generator().expr(expr)); } return None; }; @@ -81,12 +81,12 @@ fn unparse_string_format_expression(checker: &mut Checker, expr: &Expr) -> Optio }; // "select * from table where val = {}".format(...) if attr == "format" && string_literal(value).is_some() { - return Some(unparse_expr(expr, checker.generator())); + return Some(checker.generator().expr(expr)); }; None } // f"select * from table where val = {val}" - Expr::JoinedStr(_) => Some(unparse_expr(expr, checker.generator())), + Expr::JoinedStr(_) => Some(checker.generator().expr(expr)), _ => None, } } diff --git a/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs b/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs index 50229bd6d25c6..fee08cd188292 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs @@ -2,7 +2,7 @@ use rustpython_parser::ast::{self, Constant, Expr, Keyword, Ranged}; use ruff_diagnostics::{Diagnostic, 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; @@ -48,7 +48,7 @@ pub(crate) fn request_without_timeout( Expr::Constant(ast::ExprConstant { value: value @ Constant::None, .. - }) => Some(unparse_constant(value, checker.generator())), + }) => Some(checker.generator().constant(value)), _ => None, } { checker.diagnostics.push(Diagnostic::new( diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs index 86b69766549cc..de7f05ef51b28 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs @@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Stmt}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_stmt; use crate::checkers::ast::Checker; 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()) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_stmt(&assertion_error(msg), checker.generator()), + checker.generator().stmt(&assertion_error(msg)), stmt.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs b/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs index 721b3b30eae82..3a4c8c1f69ca4 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs @@ -8,7 +8,6 @@ use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_ast::call_path; use ruff_python_ast::call_path::CallPath; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::{AsRule, Rule}; @@ -97,9 +96,9 @@ fn duplicate_handler_exceptions<'a>( #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( if unique_elts.len() == 1 { - unparse_expr(unique_elts[0], checker.generator()) + checker.generator().expr(unique_elts[0]) } else { - unparse_expr(&type_pattern(unique_elts), checker.generator()) + checker.generator().expr(&type_pattern(unique_elts)) }, expr.range(), ))); diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs b/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs index a4b80ee933920..0c150609afa29 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; 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 crate::checkers::ast::Checker; @@ -69,7 +69,7 @@ pub(crate) fn getattr_with_constant( if checker.patch(diagnostic.kind.rule()) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&attribute(obj, value), checker.generator()), + checker.generator().expr(&attribute(obj, value)), expr.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs b/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs index 1576d5295ed50..3781b306e904f 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs @@ -2,7 +2,6 @@ use rustpython_parser::ast::{self, Excepthandler, Expr, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::AsRule; @@ -45,14 +44,14 @@ pub(crate) fn redundant_tuple_in_exception_handler( }; let mut diagnostic = Diagnostic::new( RedundantTupleInExceptionHandler { - name: unparse_expr(elt, checker.generator()), + name: checker.generator().expr(elt), }, type_.range(), ); if checker.patch(diagnostic.kind.rule()) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(elt, checker.generator()), + checker.generator().expr(elt), type_.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs b/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs index 8a2ab65e57ce6..e68d2db100d4e 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Stmt}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_stmt; + use ruff_python_ast::source_code::Generator; 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, range: TextRange::default(), }); - unparse_stmt(&stmt, generator) + generator.stmt(&stmt) } /// B010 diff --git a/crates/ruff/src/rules/flake8_errmsg/rules.rs b/crates/ruff/src/rules/flake8_errmsg/rules.rs index b0eb37b3f5626..4d749806b6046 100644 --- a/crates/ruff/src/rules/flake8_errmsg/rules.rs +++ b/crates/ruff/src/rules/flake8_errmsg/rules.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Ranged, Stmt}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, 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::whitespace; @@ -201,7 +201,7 @@ fn generate_fix( type_comment: None, range: TextRange::default(), }); - let assignment = unparse_stmt(&node1, generator); + let assignment = generator.stmt(&node1); #[allow(deprecated)] Fix::unspecified_edits( 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 Some(first) = args.first() { match first { - // Check for string literals + // Check for string literals. Expr::Constant(ast::ExprConstant { 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(_) => { if checker.settings.rules.enabled(Rule::FStringInException) { 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); } } - // Check for .format() calls + // Check for .format() calls. Expr::Call(ast::ExprCall { func, .. }) => { if checker.settings.rules.enabled(Rule::DotFormatInException) { if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = diff --git a/crates/ruff/src/rules/flake8_pie/rules.rs b/crates/ruff/src/rules/flake8_pie/rules.rs index 040c5d7769fdc..77c04131d8c0a 100644 --- a/crates/ruff/src/rules/flake8_pie/rules.rs +++ b/crates/ruff/src/rules/flake8_pie/rules.rs @@ -13,7 +13,7 @@ use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; 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_stdlib::identifiers::is_identifier; @@ -443,7 +443,7 @@ pub(crate) fn non_unique_enums<'a, 'b>( if !seen_targets.insert(ComparableExpr::from(value)) { let diagnostic = Diagnostic::new( NonUniqueEnums { - value: unparse_expr(value, checker.generator()), + value: checker.generator().expr(value), }, stmt.range(), ); @@ -612,7 +612,7 @@ pub(crate) fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) { let bool_op = node; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&bool_op, checker.generator()), + checker.generator().expr(&bool_op), expr.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs b/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs index d5e7ff983bbf5..cdf2987c19321 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs @@ -4,7 +4,6 @@ use rustpython_parser::ast::{self, Expr, Operator, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_ast::comparable::ComparableExpr; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::AsRule; @@ -61,7 +60,7 @@ fn traverse_union<'a>( if !seen_nodes.insert(expr.into()) { let mut diagnostic = Diagnostic::new( DuplicateUnionMember { - duplicate_name: unparse_expr(expr, checker.generator()), + duplicate_name: checker.generator().expr(expr), }, expr.range(), ); @@ -80,10 +79,9 @@ fn traverse_union<'a>( // Replace the parent with its non-duplicate child. #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr( - if expr == left.as_ref() { right } else { left }, - checker.generator(), - ), + checker + .generator() + .expr(if expr == left.as_ref() { right } else { left }), parent.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs index 721844d95f0ae..d59faa9d4317d 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs @@ -10,7 +10,7 @@ use std::borrow::Cow; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, 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::visitor::Visitor; 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) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_stmt(&stmt, checker.generator()), + checker.generator().stmt(&stmt), expr.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs index 14b045522aa79..4d225f422bf9c 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs @@ -4,7 +4,6 @@ use rustpython_parser::{lexer, Mode, Tok}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::{AsRule, Rule}; @@ -78,7 +77,7 @@ fn elts_to_csv(elts: &[Expr], checker: &Checker) -> Option { kind: None, 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`. @@ -164,7 +163,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) { }); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - format!("({})", unparse_expr(&node, checker.generator())), + format!("({})", checker.generator().expr(&node)), name_range, ))); } @@ -195,7 +194,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) { }); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node, checker.generator()), + checker.generator().expr(&node), name_range, ))); } @@ -228,7 +227,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) { }); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node, checker.generator()), + checker.generator().expr(&node), expr.range(), ))); } @@ -278,7 +277,7 @@ fn check_names(checker: &mut Checker, decorator: &Expr, expr: &Expr) { }); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - format!("({})", unparse_expr(&node, checker.generator())), + format!("({})", checker.generator().expr(&node)), expr.range(), ))); } @@ -373,7 +372,7 @@ fn handle_single_name(checker: &mut Checker, expr: &Expr, value: &Expr) { let node = value.clone(); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node, checker.generator()), + checker.generator().expr(&node), expr.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs index a7bfb6f7a56b0..76cc3db4cbf65 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs @@ -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_macros::{derive_message_formats, violation}; 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::registry::AsRule; @@ -368,7 +368,7 @@ pub(crate) fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) { // multiple duplicates, the fixes will conflict. #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&bool_op, checker.generator()), + checker.generator().expr(&bool_op), expr.range(), ))); } @@ -455,7 +455,7 @@ pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) { let in_expr = node2.into(); let mut diagnostic = Diagnostic::new( CompareWithTuple { - replacement: unparse_expr(&in_expr, checker.generator()), + replacement: checker.generator().expr(&in_expr), }, expr.range(), ); @@ -479,7 +479,7 @@ pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) { }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&in_expr, checker.generator()), + checker.generator().expr(&in_expr), expr.range(), ))); } @@ -613,7 +613,7 @@ pub(crate) fn get_short_circuit_edit( } } } else { - unparse_expr(expr, checker.generator()) + checker.generator().expr(expr) }; Edit::range_replacement(content, range) } diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs index cc25435ae0765..c9ba60dc20782 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs @@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::AsRule; @@ -149,7 +148,7 @@ fn check_os_environ_subscript(checker: &mut Checker, expr: &Expr) { let new_env_var = node.into(); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&new_env_var, checker.generator()), + checker.generator().expr(&new_env_var), slice.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs index 04e7490437647..1449957c8093c 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs @@ -8,8 +8,7 @@ use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_ast::comparable::{ComparableConstant, ComparableExpr, ComparableStmt}; use ruff_python_ast::helpers::{ - any_over_expr, contains_effect, first_colon_range, has_comments, has_comments_in, unparse_expr, - unparse_stmt, + any_over_expr, contains_effect, first_colon_range, has_comments, has_comments_in, }; use ruff_python_ast::newlines::StrExt; use ruff_python_semantic::context::Context; @@ -348,7 +347,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) { return; } - let condition = unparse_expr(test, checker.generator()); + let condition = checker.generator().expr(test); let fixable = matches!(if_return, Bool::True) && matches!(else_return, Bool::False) && !has_comments(stmt, checker.locator) @@ -364,7 +363,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) { }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_stmt(&node.into(), checker.generator()), + checker.generator().stmt(&node.into()), stmt.range(), ))); } else { @@ -387,7 +386,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) { }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_stmt(&node2.into(), checker.generator()), + checker.generator().stmt(&node2.into()), 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 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. let line_start = checker.locator.line_start(stmt.start()); @@ -859,7 +858,7 @@ pub(crate) fn use_dict_get_with_default( type_comment: None, 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. let line_start = checker.locator.line_start(stmt.start()); diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs index 3d3c2d0d5920a..2879fb5798f7e 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs @@ -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_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::AsRule; @@ -97,7 +96,7 @@ pub(crate) fn explicit_true_false_in_ifexpr( let mut diagnostic = Diagnostic::new( IfExprWithTrueFalse { - expr: unparse_expr(test, checker.generator()), + expr: checker.generator().expr(test), }, expr.range(), ); @@ -105,7 +104,7 @@ pub(crate) fn explicit_true_false_in_ifexpr( if matches!(test, Expr::Compare(_)) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&test.clone(), checker.generator()), + checker.generator().expr(&test.clone()), expr.range(), ))); } else if checker.ctx.is_builtin("bool") { @@ -122,7 +121,7 @@ pub(crate) fn explicit_true_false_in_ifexpr( }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node1.into(), checker.generator()), + checker.generator().expr(&node1.into()), expr.range(), ))); }; @@ -153,7 +152,7 @@ pub(crate) fn explicit_false_true_in_ifexpr( let mut diagnostic = Diagnostic::new( IfExprWithFalseTrue { - expr: unparse_expr(test, checker.generator()), + expr: checker.generator().expr(test), }, expr.range(), ); @@ -166,7 +165,7 @@ pub(crate) fn explicit_false_true_in_ifexpr( }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node1.into(), checker.generator()), + checker.generator().expr(&node1.into()), expr.range(), ))); } @@ -201,8 +200,8 @@ pub(crate) fn twisted_arms_in_ifexpr( let mut diagnostic = Diagnostic::new( IfExprWithTwistedArms { - expr_body: unparse_expr(body, checker.generator()), - expr_else: unparse_expr(orelse, checker.generator()), + expr_body: checker.generator().expr(body), + expr_else: checker.generator().expr(orelse), }, expr.range(), ); @@ -218,7 +217,7 @@ pub(crate) fn twisted_arms_in_ifexpr( }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node3.into(), checker.generator()), + checker.generator().expr(&node3.into()), expr.range(), ))); } diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs index e804cd0c1e6f3..39128b5f9c46b 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Cmpop, Expr, ExprContext, Ranged, Stmt, Unary use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; + use ruff_python_semantic::scope::ScopeKind; use crate::checkers::ast::Checker; @@ -107,8 +107,8 @@ pub(crate) fn negation_with_equal_op( let mut diagnostic = Diagnostic::new( NegateEqualOp { - left: unparse_expr(left, checker.generator()), - right: unparse_expr(&comparators[0], checker.generator()), + left: checker.generator().expr(left), + right: checker.generator().expr(&comparators[0]), }, expr.range(), ); @@ -121,7 +121,7 @@ pub(crate) fn negation_with_equal_op( }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node.into(), checker.generator()), + checker.generator().expr(&node.into()), expr.range(), ))); } @@ -157,8 +157,8 @@ pub(crate) fn negation_with_not_equal_op( let mut diagnostic = Diagnostic::new( NegateNotEqualOp { - left: unparse_expr(left, checker.generator()), - right: unparse_expr(&comparators[0], checker.generator()), + left: checker.generator().expr(left), + right: checker.generator().expr(&comparators[0]), }, expr.range(), ); @@ -171,7 +171,7 @@ pub(crate) fn negation_with_not_equal_op( }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node.into(), checker.generator()), + checker.generator().expr(&node.into()), expr.range(), ))); } @@ -192,7 +192,7 @@ pub(crate) fn double_negation(checker: &mut Checker, expr: &Expr, op: Unaryop, o let mut diagnostic = Diagnostic::new( DoubleNegation { - expr: unparse_expr(operand, checker.generator()), + expr: checker.generator().expr(operand), }, 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() { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(operand, checker.generator()), + checker.generator().expr(operand), expr.range(), ))); } 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)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&node1.into(), checker.generator()), + checker.generator().expr(&node1.into()), expr.range(), ))); }; diff --git a/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs b/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs index 940a2659300cb..2bbc5740daeec 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs @@ -6,7 +6,7 @@ use unicode_width::UnicodeWidthStr; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_stmt; + use ruff_python_ast::source_code::Generator; 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())), range: TextRange::default(), }; - unparse_stmt(&node3.into(), generator) + generator.stmt(&node3.into()) } /// SIM110, SIM111 diff --git a/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs b/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs index 35e1317c7ec79..c98b9fd4856d2 100644 --- a/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs +++ b/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; 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_stdlib::identifiers::is_identifier; @@ -112,7 +112,7 @@ fn fix_banned_relative_import( level: Some(Int::new(0)), range: TextRange::default(), }; - let content = unparse_stmt(&node.into(), generator); + let content = generator.stmt(&node.into()); #[allow(deprecated)] Some(Fix::unspecified(Edit::range_replacement( content, diff --git a/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs b/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs index 7332175cd2442..cd05bace7cfe6 100644 --- a/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs +++ b/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs @@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Expr, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; 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). 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( StaticJoinToFString { diff --git a/crates/ruff/src/rules/pycodestyle/helpers.rs b/crates/ruff/src/rules/pycodestyle/helpers.rs index 4c328b79179b8..40b0314e9a3cf 100644 --- a/crates/ruff/src/rules/pycodestyle/helpers.rs +++ b/crates/ruff/src/rules/pycodestyle/helpers.rs @@ -2,7 +2,6 @@ use ruff_text_size::{TextLen, TextRange}; use rustpython_parser::ast::{self, Cmpop, Expr}; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; -use ruff_python_ast::helpers::unparse_expr; use ruff_python_ast::newlines::Line; use ruff_python_ast::source_code::Generator; @@ -22,7 +21,7 @@ pub(crate) fn compare( comparators: comparators.to_vec(), range: TextRange::default(), }; - unparse_expr(&node.into(), generator) + generator.expr(&node.into()) } pub(super) fn is_overlong( diff --git a/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs b/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs index 088bda4c2a8d9..3defc9b456a3a 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs @@ -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_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::source_code::Generator; use ruff_python_ast::whitespace::leading_space; @@ -210,7 +210,7 @@ fn function( type_comment: None, range: TextRange::default(), }); - return unparse_stmt(&func, generator); + return generator.stmt(&func); } } let func = Stmt::FunctionDef(ast::StmtFunctionDef { @@ -222,5 +222,5 @@ fn function( type_comment: None, range: TextRange::default(), }); - unparse_stmt(&func, generator) + generator.stmt(&func) } diff --git a/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs b/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs index 0be958c6b38c7..85dbf62dcbdc5 100644 --- a/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs +++ b/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs @@ -6,7 +6,6 @@ use rustpython_parser::ast::{self, Expr, Ranged}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_ast::comparable::{ComparableConstant, ComparableExpr}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::{AsRule, Rule}; @@ -106,7 +105,7 @@ pub(crate) fn repeated_keys(checker: &mut Checker, keys: &[Option], values let is_duplicate_value = seen_values.contains(&comparable_value); let mut diagnostic = Diagnostic::new( MultiValueRepeatedKeyLiteral { - name: unparse_expr(key, checker.generator()), + name: checker.generator().expr(key), repeated_value: is_duplicate_value, }, key.range(), diff --git a/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs b/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs index de73b561439de..1501c53253d7c 100644 --- a/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs +++ b/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs @@ -4,7 +4,6 @@ use rustpython_parser::ast::{self, Cmpop, Constant, Expr, Ranged}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::{unparse_constant, unparse_expr}; 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 Constant::Str(s) = value { if s.is_empty() { - let constant = unparse_constant(value, checker.generator()); - let expr = unparse_expr(rhs, checker.generator()); + let constant = checker.generator().constant(value); + let expr = checker.generator().expr(rhs); let existing = format!("{constant} {op} {expr}"); let replacement = format!("{}{expr}", op.into_unary()); 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 Constant::Str(s) = value { if s.is_empty() { - let expr = unparse_expr(lhs, checker.generator()); - let constant = unparse_constant(value, checker.generator()); + let expr = checker.generator().expr(lhs); + let constant = checker.generator().constant(value); let existing = format!("{expr} {op} {constant}"); let replacement = format!("{}{expr}", op.into_unary()); checker.diagnostics.push(Diagnostic::new( diff --git a/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs b/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs index 24e3db500c013..5897200301d91 100644 --- a/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs +++ b/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs @@ -5,7 +5,6 @@ use rustpython_parser::ast::{self, Cmpop, Expr, Ranged}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_constant; use crate::checkers::ast::Checker; @@ -106,9 +105,9 @@ pub(crate) fn comparison_of_constant( { let diagnostic = Diagnostic::new( ComparisonOfConstant { - left_constant: unparse_constant(left_constant, checker.generator()), + left_constant: checker.generator().constant(left_constant), op: op.into(), - right_constant: unparse_constant(right_constant, checker.generator()), + right_constant: checker.generator().constant(right_constant), }, left.range(), ); diff --git a/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs b/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs index ad8d026b6d06e..3128777707744 100644 --- a/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs +++ b/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs @@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Constant, Expr, Ranged, Unaryop}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; 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) { checker.diagnostics.push(Diagnostic::new( MagicValueComparison { - value: unparse_expr(comparison_expr, checker.generator()), + value: checker.generator().expr(comparison_expr), }, comparison_expr.range(), )); diff --git a/crates/ruff/src/rules/pylint/rules/manual_import_from.rs b/crates/ruff/src/rules/pylint/rules/manual_import_from.rs index ffe41671ecac9..30f8e218e0dcb 100644 --- a/crates/ruff/src/rules/pylint/rules/manual_import_from.rs +++ b/crates/ruff/src/rules/pylint/rules/manual_import_from.rs @@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Alias, Int, Ranged, Stmt}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_stmt; use crate::checkers::ast::Checker; use crate::registry::AsRule; @@ -67,7 +66,7 @@ pub(crate) fn manual_from_import( }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_stmt(&node.into(), checker.generator()), + checker.generator().stmt(&node.into()), stmt.range(), ))); } diff --git a/crates/ruff/src/rules/pylint/rules/nested_min_max.rs b/crates/ruff/src/rules/pylint/rules/nested_min_max.rs index 9f897486358d5..7c34721325a04 100644 --- a/crates/ruff/src/rules/pylint/rules/nested_min_max.rs +++ b/crates/ruff/src/rules/pylint/rules/nested_min_max.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Expr, Keyword, Ranged}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, 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 crate::{checkers::ast::Checker, registry::AsRule}; @@ -149,7 +149,7 @@ pub(crate) fn nested_min_max( }); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&flattened_expr, checker.generator()), + checker.generator().expr(&flattened_expr), expr.range(), ))); } diff --git a/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs b/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs index 202677a7e51dd..6e89473b70c59 100644 --- a/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs +++ b/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs @@ -6,7 +6,7 @@ use rustpython_parser::ast::{self, Expr, ExprContext, Ranged, Stmt, Withitem}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; 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::types::Node; 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( 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, inner_kind: inner_assignment_target.binding_kind, }, diff --git a/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs b/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs index 6995c200d8fa6..f8bb082c836e1 100644 --- a/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs +++ b/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs @@ -5,7 +5,6 @@ use rustpython_parser::ast::{self, Boolop, Expr, Ranged}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_ast::hashable::HashableExpr; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; @@ -66,11 +65,11 @@ pub(crate) fn repeated_isinstance_calls( if num_calls > 1 && types.len() > 1 { checker.diagnostics.push(Diagnostic::new( RepeatedIsinstanceCalls { - obj: unparse_expr(obj.as_expr(), checker.generator()), + obj: checker.generator().expr(obj.as_expr()), types: types .iter() .map(HashableExpr::as_expr) - .map(|expr| unparse_expr(expr, checker.generator())) + .map(|expr| checker.generator().expr(expr)) .sorted() .collect(), }, diff --git a/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs b/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs index 699d2324d9d17..0143fa4a2e91c 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs @@ -5,7 +5,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Keyword, Ranged, use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, 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_stdlib::identifiers::is_identifier; @@ -175,10 +175,7 @@ fn convert_to_class( ) -> Fix { #[allow(deprecated)] Fix::unspecified(Edit::range_replacement( - unparse_stmt( - &create_class_def_stmt(typename, body, base_class), - generator, - ), + generator.stmt(&create_class_def_stmt(typename, body, base_class)), stmt.range(), )) } diff --git a/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs b/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs index 9455e9a8162b0..79921376127b0 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs @@ -5,7 +5,7 @@ use rustpython_parser::ast::{self, Constant, Expr, ExprContext, Keyword, Ranged, use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, 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_stdlib::identifiers::is_identifier; @@ -226,10 +226,12 @@ fn convert_to_class( ) -> Fix { #[allow(deprecated)] Fix::unspecified(Edit::range_replacement( - unparse_stmt( - &create_class_def_stmt(class_name, body, total_keyword, base_class), - generator, - ), + generator.stmt(&create_class_def_stmt( + class_name, + body, + total_keyword, + base_class, + )), stmt.range(), )) } diff --git a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs index 9f3dcb7910207..3675ecfc09ffc 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs @@ -3,7 +3,6 @@ use rustpython_parser::ast::{self, Expr, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; 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()) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(func, checker.generator()), + checker.generator().expr(func), expr.range(), ))); } diff --git a/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs b/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs index 4647e6fb9ec64..4d154bb761197 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs @@ -4,7 +4,7 @@ use rustpython_parser::ast::{self, Constant, Expr, Keyword, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_constant; + use ruff_python_ast::str::is_implicit_concatenation; use crate::checkers::ast::Checker; @@ -70,7 +70,7 @@ pub(crate) fn native_literals( } else { Constant::Str(String::new()) }; - let content = unparse_constant(&constant, checker.generator()); + let content = checker.generator().constant(&constant); #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( content, diff --git a/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs index c47aac8d1c061..c269474b2843d 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs @@ -4,7 +4,7 @@ use rustpython_parser::ast::{self, Excepthandler, Expr, ExprContext, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; use ruff_python_ast::call_path::compose_call_path; -use ruff_python_ast::helpers::unparse_expr; + use ruff_python_semantic::context::Context; use crate::checkers::ast::Checker; @@ -117,7 +117,7 @@ fn tuple_diagnostic(checker: &mut Checker, target: &Expr, aliases: &[&Expr]) { }; #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - format!("({})", unparse_expr(&node.into(), checker.generator())), + format!("({})", checker.generator().expr(&node.into())), target.range(), ))); } diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs index 36855b6bd4164..75149e13493e2 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Constant, Expr, Operator, Ranged}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; + use ruff_python_semantic::analyze::typing::Pep604Operator; use crate::checkers::ast::Checker; @@ -67,7 +67,7 @@ pub(crate) fn use_pep604_annotation( if fixable && checker.patch(diagnostic.kind.rule()) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&optional(slice), checker.generator()), + checker.generator().expr(&optional(slice)), expr.range(), ))); } @@ -83,7 +83,7 @@ pub(crate) fn use_pep604_annotation( Expr::Tuple(ast::ExprTuple { elts, .. }) => { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&union(elts), checker.generator()), + checker.generator().expr(&union(elts)), expr.range(), ))); } @@ -91,7 +91,7 @@ pub(crate) fn use_pep604_annotation( // Single argument. #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(slice, checker.generator()), + checker.generator().expr(slice), expr.range(), ))); } diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs index 03f5c690d769d..04c585aa0c4fc 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs @@ -5,7 +5,6 @@ use rustpython_parser::ast::{self, Expr, Operator, Ranged}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; -use ruff_python_ast::helpers::unparse_expr; use crate::checkers::ast::Checker; use crate::registry::AsRule; @@ -94,7 +93,7 @@ pub(crate) fn use_pep604_isinstance( if checker.patch(diagnostic.kind.rule()) { #[allow(deprecated)] diagnostic.set_fix(Fix::unspecified(Edit::range_replacement( - unparse_expr(&union(elts), checker.generator()), + checker.generator().expr(&union(elts)), types.range(), ))); } diff --git a/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs b/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs index 30c5b9de6057d..4f868b30838e6 100644 --- a/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs +++ b/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs @@ -3,7 +3,7 @@ use rustpython_parser::ast::{self, Expr, ExprContext, Operator, Ranged}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, 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::registry::AsRule; @@ -130,8 +130,8 @@ pub(crate) fn collection_literal_concatenation(checker: &mut Checker, expr: &Exp let contents = match kind { // Wrap the new expression in parentheses if it was a tuple - Kind::Tuple => format!("({})", unparse_expr(&new_expr, checker.generator())), - Kind::List => unparse_expr(&new_expr, checker.generator()), + Kind::Tuple => format!("({})", checker.generator().expr(&new_expr)), + Kind::List => checker.generator().expr(&new_expr), }; let fixable = !has_comments(expr, checker.locator); diff --git a/crates/ruff_python_ast/src/helpers.rs b/crates/ruff_python_ast/src/helpers.rs index 0cc38fb7932f5..d064c8f15fb7c 100644 --- a/crates/ruff_python_ast/src/helpers.rs +++ b/crates/ruff_python_ast/src/helpers.rs @@ -17,27 +17,9 @@ use smallvec::SmallVec; use crate::call_path::CallPath; 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}; -/// 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(id: &str, is_builtin: F) -> bool where F: Fn(&str) -> bool, diff --git a/crates/ruff_python_ast/src/source_code/generator.rs b/crates/ruff_python_ast/src/source_code/generator.rs index 0f7573a501d27..f7806335ef74a 100644 --- a/crates/ruff_python_ast/src/source_code/generator.rs +++ b/crates/ruff_python_ast/src/source_code/generator.rs @@ -101,8 +101,22 @@ impl<'a> Generator<'a> { } } - pub fn generate(self) -> String { - self.buffer + /// Generate source code from a [`Stmt`]. + 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) { @@ -165,13 +179,17 @@ impl<'a> Generator<'a> { self.p_if(!std::mem::take(first), s); } - pub fn unparse_suite(&mut self, suite: &Suite) { + pub(crate) fn generate(self) -> String { + self.buffer + } + + pub(crate) fn unparse_suite(&mut self, suite: &Suite) { for stmt in suite { self.unparse_stmt(stmt); } } - pub fn unparse_stmt(&mut self, ast: &Stmt) { + pub(crate) fn unparse_stmt(&mut self, ast: &Stmt) { macro_rules! statement { ($body:block) => {{ self.newline(); @@ -824,7 +842,7 @@ impl<'a> Generator<'a> { self.body(&ast.body); } - pub fn unparse_expr(&mut self, ast: &Expr, level: u8) { + pub(crate) fn unparse_expr(&mut self, ast: &Expr, level: u8) { macro_rules! opprec { ($opty:ident, $x:expr, $enu:path, $($var:ident($op:literal, $prec:ident)),*$(,)?) => { 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); let inf_str = "1e309"; match constant {