From 84e96cdcd991ec8d219fa420bbb11385ae84e566 Mon Sep 17 00:00:00 2001 From: Jeong YunWon <69878+youknowone@users.noreply.github.com> Date: Sun, 26 Feb 2023 01:40:16 +0900 Subject: [PATCH] More enum work (#3212) --- Cargo.lock | 1 + .../rules/unused_loop_control_variable.rs | 22 +-- crates/ruff_python_formatter/Cargo.toml | 1 + crates/ruff_python_formatter/src/builders.rs | 6 +- .../ruff_python_formatter/src/format/alias.rs | 9 +- .../src/format/excepthandler.rs | 9 +- .../ruff_python_formatter/src/format/expr.rs | 154 +++++------------- .../ruff_python_formatter/src/format/stmt.rs | 67 ++------ .../src/format/strings.rs | 5 +- crates/ruff_python_formatter/src/newlines.rs | 24 +-- .../ruff_python_formatter/src/parentheses.rs | 13 +- crates/ruff_python_formatter/src/trivia.rs | 6 +- 12 files changed, 93 insertions(+), 224 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a5c93dfe18..02c6ee71fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2140,6 +2140,7 @@ dependencies = [ "anyhow", "clap 4.1.6", "insta", + "is-macro", "once_cell", "ruff_formatter", "ruff_python", diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs index 3b301b4186..16011c4f9a 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs @@ -31,7 +31,7 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, result_like::BoolLike)] pub enum Certainty { Certain, Uncertain, @@ -59,7 +59,7 @@ impl Violation for UnusedLoopControlVariable { let UnusedLoopControlVariable { name, certainty, .. } = self; - if matches!(certainty, Certainty::Certain) { + if certainty.to_bool() { format!("Loop control variable `{name}` not used within loop body") } else { format!("Loop control variable `{name}` may not be used within loop body") @@ -70,7 +70,7 @@ impl Violation for UnusedLoopControlVariable { let UnusedLoopControlVariable { certainty, rename, .. } = self; - if matches!(certainty, Certainty::Certain) && rename.is_some() { + if certainty.to_bool() && rename.is_some() { Some(|UnusedLoopControlVariable { name, rename, .. }| { let rename = rename.as_ref().unwrap(); format!("Rename unused `{name}` to `{rename}`") @@ -140,25 +140,17 @@ pub fn unused_loop_control_variable( } // Avoid fixing any variables that _may_ be used, but undetectably so. - let certainty = if helpers::uses_magic_variable_access(checker, body) { - Certainty::Uncertain - } else { - Certainty::Certain - }; + let certainty = Certainty::from(!helpers::uses_magic_variable_access(checker, body)); // Attempt to rename the variable by prepending an underscore, but avoid // applying the fix if doing so wouldn't actually cause us to ignore the // violation in the next pass. let rename = format!("_{name}"); - let rename = if checker + let rename = checker .settings .dummy_variable_rgx .is_match(rename.as_str()) - { - Some(rename) - } else { - None - }; + .then_some(rename); let mut diagnostic = Diagnostic::new( UnusedLoopControlVariable { @@ -169,7 +161,7 @@ pub fn unused_loop_control_variable( Range::from_located(expr), ); if let Some(rename) = rename { - if matches!(certainty, Certainty::Certain) && checker.patch(diagnostic.kind.rule()) { + if certainty.into() && checker.patch(diagnostic.kind.rule()) { // Find the `BindingKind::LoopVar` corresponding to the name. let scope = checker.current_scope(); let binding = scope diff --git a/crates/ruff_python_formatter/Cargo.toml b/crates/ruff_python_formatter/Cargo.toml index 5894322556..b75c1d968e 100644 --- a/crates/ruff_python_formatter/Cargo.toml +++ b/crates/ruff_python_formatter/Cargo.toml @@ -13,6 +13,7 @@ ruff_text_size = { path = "../ruff_text_size" } anyhow = { workspace = true } clap = { workspace = true } +is-macro = { workspace = true } once_cell = { workspace = true } rustc-hash = { workspace = true } rustpython-common = { workspace = true } diff --git a/crates/ruff_python_formatter/src/builders.rs b/crates/ruff_python_formatter/src/builders.rs index 9cc15be412..5ba0814446 100644 --- a/crates/ruff_python_formatter/src/builders.rs +++ b/crates/ruff_python_formatter/src/builders.rs @@ -4,7 +4,7 @@ use ruff_text_size::TextRange; use crate::context::ASTFormatContext; use crate::core::types::Range; -use crate::trivia::{Relationship, Trivia, TriviaKind}; +use crate::trivia::{Trivia, TriviaKind}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Literal { @@ -36,7 +36,7 @@ pub struct LeadingComments<'a> { impl Format> for LeadingComments<'_> { fn fmt(&self, f: &mut Formatter>) -> FormatResult<()> { for comment in self.comments { - if matches!(comment.relationship, Relationship::Leading) { + if comment.relationship.is_leading() { if let TriviaKind::OwnLineComment(range) = comment.kind { write!(f, [hard_line_break()])?; write!(f, [literal(range)])?; @@ -60,7 +60,7 @@ pub struct TrailingComments<'a> { impl Format> for TrailingComments<'_> { fn fmt(&self, f: &mut Formatter>) -> FormatResult<()> { for comment in self.comments { - if matches!(comment.relationship, Relationship::Trailing) { + if comment.relationship.is_trailing() { if let TriviaKind::OwnLineComment(range) = comment.kind { write!(f, [hard_line_break()])?; write!(f, [literal(range)])?; diff --git a/crates/ruff_python_formatter/src/format/alias.rs b/crates/ruff_python_formatter/src/format/alias.rs index c0ae052a10..39a77aed16 100644 --- a/crates/ruff_python_formatter/src/format/alias.rs +++ b/crates/ruff_python_formatter/src/format/alias.rs @@ -6,7 +6,6 @@ use crate::builders::literal; use crate::context::ASTFormatContext; use crate::cst::Alias; use crate::shared_traits::AsFormat; -use crate::trivia::{Relationship, TriviaKind}; pub struct FormatAlias<'a> { item: &'a Alias, @@ -33,12 +32,8 @@ impl Format> for FormatAlias<'_> { // Format any end-of-line comments. let mut first = true; for range in alias.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } diff --git a/crates/ruff_python_formatter/src/format/excepthandler.rs b/crates/ruff_python_formatter/src/format/excepthandler.rs index dfcb688f6d..a9b50e6c2d 100644 --- a/crates/ruff_python_formatter/src/format/excepthandler.rs +++ b/crates/ruff_python_formatter/src/format/excepthandler.rs @@ -7,7 +7,6 @@ use crate::context::ASTFormatContext; use crate::cst::{Excepthandler, ExcepthandlerKind}; use crate::format::builders::block; use crate::shared_traits::AsFormat; -use crate::trivia::{Relationship, TriviaKind}; pub struct FormatExcepthandler<'a> { item: &'a Excepthandler, @@ -46,12 +45,8 @@ impl Format> for FormatExcepthandler<'_> { // Format any end-of-line comments. let mut first = true; for range in excepthandler.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } diff --git a/crates/ruff_python_formatter/src/format/expr.rs b/crates/ruff_python_formatter/src/format/expr.rs index 3c1dd93fc2..57cb200831 100644 --- a/crates/ruff_python_formatter/src/format/expr.rs +++ b/crates/ruff_python_formatter/src/format/expr.rs @@ -17,7 +17,7 @@ use crate::format::helpers::{is_self_closing, is_simple_power, is_simple_slice}; use crate::format::numbers::{complex_literal, float_literal, int_literal}; use crate::format::strings::string_literal; use crate::shared_traits::AsFormat; -use crate::trivia::{Parenthesize, Relationship, TriviaKind}; +use crate::trivia::{Parenthesize, TriviaKind}; pub struct FormatExpr<'a> { item: &'a Expr, @@ -33,12 +33,8 @@ fn format_starred( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -62,12 +58,8 @@ fn format_name( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -96,7 +88,7 @@ fn format_subscript( // Apply any dangling comments. for trivia in &expr.trivia { - if matches!(trivia.relationship, Relationship::Dangling) { + if trivia.relationship.is_dangling() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [hard_line_break()])?; @@ -136,7 +128,7 @@ fn format_tuple( write!( f, [group(&format_with(|f| { - if matches!(expr.parentheses, Parenthesize::IfExpanded) { + if expr.parentheses.is_if_expanded() { write!(f, [if_group_breaks(&text("("))])?; } if matches!( @@ -146,10 +138,8 @@ fn format_tuple( write!( f, [soft_block_indent(&format_with(|f| { - let magic_trailing_comma = expr - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = + expr.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); let is_unbroken = expr.location.row() == expr.end_location.unwrap().row(); if magic_trailing_comma { @@ -170,10 +160,8 @@ fn format_tuple( }))] )?; } else { - let magic_trailing_comma = expr - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = + expr.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); let is_unbroken = expr.location.row() == expr.end_location.unwrap().row(); if magic_trailing_comma { write!(f, [expand_parent()])?; @@ -190,7 +178,7 @@ fn format_tuple( } } } - if matches!(expr.parentheses, Parenthesize::IfExpanded) { + if expr.parentheses.is_if_expanded() { write!(f, [if_group_breaks(&text(")"))])?; } Ok(()) @@ -236,7 +224,7 @@ fn format_slice( // Apply any dangling comments. for trivia in &lower.trivia { - if matches!(trivia.relationship, Relationship::Dangling) { + if trivia.relationship.is_dangling() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [hard_line_break()])?; @@ -256,12 +244,8 @@ fn format_slice( // Format any end-of-line comments. let mut first = true; for range in lower.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -282,7 +266,7 @@ fn format_slice( // Apply any dangling comments. for trivia in &upper.trivia { - if matches!(trivia.relationship, Relationship::Dangling) { + if trivia.relationship.is_dangling() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [hard_line_break()])?; @@ -295,12 +279,8 @@ fn format_slice( // Format any end-of-line comments. let mut first = true; for range in upper.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -329,7 +309,7 @@ fn format_slice( // Apply any dangling comments. for trivia in &step.trivia { - if matches!(trivia.relationship, Relationship::Dangling) { + if trivia.relationship.is_dangling() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [hard_line_break()])?; @@ -342,12 +322,8 @@ fn format_slice( // Format any end-of-line comments. let mut first = true; for range in step.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -365,12 +341,8 @@ fn format_slice( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -391,10 +363,7 @@ fn format_list( ) -> FormatResult<()> { write!(f, [text("[")])?; if !elts.is_empty() { - let magic_trailing_comma = expr - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = expr.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); write!( f, [group(&format_args![soft_block_indent(&format_with(|f| { @@ -429,10 +398,7 @@ fn format_set( } else { write!(f, [text("{")])?; if !elts.is_empty() { - let magic_trailing_comma = expr - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = expr.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); write!( f, [group(&format_args![soft_block_indent(&format_with(|f| { @@ -474,12 +440,8 @@ fn format_call( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -495,12 +457,8 @@ fn format_call( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -511,10 +469,7 @@ fn format_call( write!(f, [line_suffix(&literal(range))])?; } - let magic_trailing_comma = expr - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = expr.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); write!( f, [group(&format_args![soft_block_indent(&format_with(|f| { @@ -560,7 +515,7 @@ fn format_call( // Apply any dangling trailing comments. for trivia in &expr.trivia { - if matches!(trivia.relationship, Relationship::Dangling) { + if trivia.relationship.is_dangling() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [hard_line_break()])?; @@ -757,12 +712,8 @@ fn format_compare( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -819,10 +770,7 @@ fn format_dict( ) -> FormatResult<()> { write!(f, [text("{")])?; if !keys.is_empty() { - let magic_trailing_comma = expr - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = expr.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); write!( f, [soft_block_indent(&format_with(|f| { @@ -889,12 +837,8 @@ fn format_attribute( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -929,12 +873,8 @@ fn format_bool_op( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -971,12 +911,8 @@ fn format_bin_op( // Format any end-of-line comments. let mut first = true; for range in expr.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -1004,7 +940,7 @@ fn format_unary_op( ExprKind::BoolOp { .. } | ExprKind::Compare { .. } | ExprKind::BinOp { .. } ) { - let parenthesized = matches!(operand.parentheses, Parenthesize::Always); + let parenthesized = operand.parentheses.is_always(); if !parenthesized { write!(f, [text("(")])?; } @@ -1056,13 +992,13 @@ fn format_if_exp( impl Format> for FormatExpr<'_> { fn fmt(&self, f: &mut Formatter>) -> FormatResult<()> { - if matches!(self.item.parentheses, Parenthesize::Always) { + if self.item.parentheses.is_always() { write!(f, [text("(")])?; } // Any leading comments come on the line before. for trivia in &self.item.trivia { - if matches!(trivia.relationship, Relationship::Leading) { + if trivia.relationship.is_leading() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [literal(range)])?; @@ -1130,7 +1066,7 @@ impl Format> for FormatExpr<'_> { // Any trailing comments come on the lines after. for trivia in &self.item.trivia { - if matches!(trivia.relationship, Relationship::Trailing) { + if trivia.relationship.is_trailing() { if let TriviaKind::OwnLineComment(range) = trivia.kind { write!(f, [expand_parent()])?; write!(f, [literal(range)])?; @@ -1139,7 +1075,7 @@ impl Format> for FormatExpr<'_> { } } - if matches!(self.item.parentheses, Parenthesize::Always) { + if self.item.parentheses.is_always() { write!(f, [text(")")])?; } diff --git a/crates/ruff_python_formatter/src/format/stmt.rs b/crates/ruff_python_formatter/src/format/stmt.rs index e2393a0a46..b180dad2e0 100644 --- a/crates/ruff_python_formatter/src/format/stmt.rs +++ b/crates/ruff_python_formatter/src/format/stmt.rs @@ -12,7 +12,7 @@ use crate::cst::{ use crate::format::builders::{block, join_names}; use crate::format::helpers::is_self_closing; use crate::shared_traits::AsFormat; -use crate::trivia::{Parenthesize, Relationship, TriviaKind}; +use crate::trivia::TriviaKind; fn format_break(f: &mut Formatter>) -> FormatResult<()> { write!(f, [text("break")]) @@ -25,12 +25,8 @@ fn format_pass(f: &mut Formatter>, stmt: &Stmt) -> FormatRe // Format any end-of-line comments. let mut first = true; for range in stmt.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -189,11 +185,7 @@ fn format_func_def( dynamic_text(name, TextSize::default()), text("("), group(&soft_block_indent(&format_with(|f| { - if stmt - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)) - { + if stmt.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()) { write!(f, [expand_parent()])?; } write!(f, [args.format()]) @@ -211,12 +203,8 @@ fn format_func_def( // Format any end-of-line comments. let mut first = true; for range in stmt.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -260,12 +248,8 @@ fn format_assign( // Format any end-of-line comments. let mut first = true; for range in stmt.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -436,12 +420,8 @@ fn format_return( // Format any end-of-line comments. let mut first = true; for range in stmt.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -585,10 +565,7 @@ fn format_import_from( if names.iter().any(|name| name.node.name == "*") { write!(f, [text("*")])?; } else { - let magic_trailing_comma = stmt - .trivia - .iter() - .any(|c| matches!(c.kind, TriviaKind::MagicTrailingComma)); + let magic_trailing_comma = stmt.trivia.iter().any(|c| c.kind.is_magic_trailing_comma()); write!( f, [group(&format_args![ @@ -616,12 +593,8 @@ fn format_import_from( // Format any end-of-line comments. let mut first = true; for range in stmt.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -640,7 +613,7 @@ fn format_expr( stmt: &Stmt, expr: &Expr, ) -> FormatResult<()> { - if matches!(stmt.parentheses, Parenthesize::Always) { + if stmt.parentheses.is_always() { write!( f, [group(&format_args![ @@ -665,12 +638,8 @@ fn format_expr( // Format any end-of-line comments. let mut first = true; for range in stmt.trivia.iter().filter_map(|trivia| { - if matches!(trivia.relationship, Relationship::Trailing) { - if let TriviaKind::EndOfLineComment(range) = trivia.kind { - Some(range) - } else { - None - } + if trivia.relationship.is_trailing() { + trivia.kind.end_of_line_comment() } else { None } @@ -730,7 +699,7 @@ impl Format> for FormatStmt<'_> { fn fmt(&self, f: &mut Formatter>) -> FormatResult<()> { // Any leading comments come on the line before. for trivia in &self.item.trivia { - if matches!(trivia.relationship, Relationship::Leading) { + if trivia.relationship.is_leading() { match trivia.kind { TriviaKind::EmptyLine => { write!(f, [empty_line()])?; @@ -886,7 +855,7 @@ impl Format> for FormatStmt<'_> { // Any trailing comments come on the lines after. for trivia in &self.item.trivia { - if matches!(trivia.relationship, Relationship::Trailing) { + if trivia.relationship.is_trailing() { match trivia.kind { TriviaKind::EmptyLine => { write!(f, [empty_line()])?; diff --git a/crates/ruff_python_formatter/src/format/strings.rs b/crates/ruff_python_formatter/src/format/strings.rs index 59797aec28..633efc076d 100644 --- a/crates/ruff_python_formatter/src/format/strings.rs +++ b/crates/ruff_python_formatter/src/format/strings.rs @@ -8,7 +8,6 @@ use crate::context::ASTFormatContext; use crate::core::helpers::{leading_quote, trailing_quote}; use crate::core::types::Range; use crate::cst::Expr; -use crate::trivia::Parenthesize; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct StringLiteralPart { @@ -142,7 +141,7 @@ impl Format> for StringLiteral<'_> { write!( f, [group(&format_with(|f| { - if matches!(expr.parentheses, Parenthesize::IfExpanded) { + if expr.parentheses.is_if_expanded() { write!(f, [if_group_breaks(&text("("))])?; } for (i, elt) in elts.iter().enumerate() { @@ -151,7 +150,7 @@ impl Format> for StringLiteral<'_> { write!(f, [soft_line_break_or_space()])?; } } - if matches!(expr.parentheses, Parenthesize::IfExpanded) { + if expr.parentheses.is_if_expanded() { write!(f, [if_group_breaks(&text(")"))])?; } Ok(()) diff --git a/crates/ruff_python_formatter/src/newlines.rs b/crates/ruff_python_formatter/src/newlines.rs index 70cb86b844..c59f2e9ec6 100644 --- a/crates/ruff_python_formatter/src/newlines.rs +++ b/crates/ruff_python_formatter/src/newlines.rs @@ -49,10 +49,7 @@ impl<'a> Visitor<'a> for NewlineNormalizer { // Remove any runs of empty lines greater than two in a row. let mut count = 0; stmt.trivia.retain(|c| { - if matches!( - (c.kind, c.relationship), - (TriviaKind::EmptyLine, Relationship::Leading) - ) { + if c.kind.is_empty_line() && c.relationship.is_leading() { count += 1; count <= self.depth.max_newlines() } else { @@ -78,10 +75,7 @@ impl<'a> Visitor<'a> for NewlineNormalizer { if seen_non_empty { true } else { - if matches!( - (c.kind, c.relationship), - (TriviaKind::EmptyLine, Relationship::Leading) - ) { + if c.kind.is_empty_line() && c.relationship.is_leading() { false } else { seen_non_empty = true; @@ -104,12 +98,7 @@ impl<'a> Visitor<'a> for NewlineNormalizer { let present_newlines = stmt .trivia .iter() - .take_while(|c| { - matches!( - (c.kind, c.relationship), - (TriviaKind::EmptyLine, Relationship::Leading) - ) - }) + .take_while(|c| c.kind.is_empty_line() && c.relationship.is_leading()) .count(); if present_newlines < required_newlines { for _ in 0..(required_newlines - present_newlines) { @@ -135,12 +124,7 @@ impl<'a> Visitor<'a> for NewlineNormalizer { - stmt .trivia .iter() - .take_while(|c| { - matches!( - (c.kind, c.relationship), - (TriviaKind::EmptyLine, Relationship::Leading) - ) - }) + .take_while(|c| c.kind.is_empty_line() && c.relationship.is_leading()) .count(); for _ in 0..num_to_insert { stmt.trivia.insert( diff --git a/crates/ruff_python_formatter/src/parentheses.rs b/crates/ruff_python_formatter/src/parentheses.rs index ba9ecabf47..809da63296 100644 --- a/crates/ruff_python_formatter/src/parentheses.rs +++ b/crates/ruff_python_formatter/src/parentheses.rs @@ -4,15 +4,14 @@ use crate::core::types::Range; use crate::core::visitor; use crate::core::visitor::Visitor; use crate::cst::{Expr, ExprKind, Stmt, StmtKind}; -use crate::trivia::{Parenthesize, TriviaKind}; +use crate::trivia::Parenthesize; use rustpython_parser::ast::Constant; /// Modify an [`Expr`] to infer parentheses, rather than respecting any user-provided trivia. fn use_inferred_parens(expr: &mut Expr) { // Remove parentheses, unless it's a generator expression, in which case, keep them. if !matches!(expr.node, ExprKind::GeneratorExp { .. }) { - expr.trivia - .retain(|trivia| !matches!(trivia.kind, TriviaKind::Parentheses)); + expr.trivia.retain(|trivia| !trivia.kind.is_parentheses()); } // If it's a tuple, add parentheses if it's a singleton; otherwise, we only need parentheses @@ -35,8 +34,7 @@ impl<'a> Visitor<'a> for ParenthesesNormalizer<'_> { // Always remove parentheses around statements, unless it's an expression statement, // in which case, remove parentheses around the expression. let before = stmt.trivia.len(); - stmt.trivia - .retain(|trivia| !matches!(trivia.kind, TriviaKind::Parentheses)); + stmt.trivia.retain(|trivia| !trivia.kind.is_parentheses()); let after = stmt.trivia.len(); if let StmtKind::Expr { value } = &mut stmt.node { if before != after { @@ -112,8 +110,7 @@ impl<'a> Visitor<'a> for ParenthesesNormalizer<'_> { fn visit_expr(&mut self, expr: &'a mut Expr) { // Always retain parentheses around expressions. let before = expr.trivia.len(); - expr.trivia - .retain(|trivia| !matches!(trivia.kind, TriviaKind::Parentheses)); + expr.trivia.retain(|trivia| !trivia.kind.is_parentheses()); let after = expr.trivia.len(); if before != after { expr.parentheses = Parenthesize::Always; @@ -169,7 +166,7 @@ impl<'a> Visitor<'a> for ParenthesesNormalizer<'_> { if !slice .trivia .iter() - .any(|trivia| matches!(trivia.kind, TriviaKind::Parentheses)) + .any(|trivia| trivia.kind.is_parentheses()) { value.parentheses = Parenthesize::Never; } diff --git a/crates/ruff_python_formatter/src/trivia.rs b/crates/ruff_python_formatter/src/trivia.rs index 7eb9c03fd8..de6f2422f5 100644 --- a/crates/ruff_python_formatter/src/trivia.rs +++ b/crates/ruff_python_formatter/src/trivia.rs @@ -48,7 +48,7 @@ pub struct TriviaToken { pub kind: TriviaTokenKind, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, is_macro::Is)] pub enum TriviaKind { /// A Comment that is separated by at least one line break from the /// preceding token. @@ -77,14 +77,14 @@ pub enum TriviaKind { Parentheses, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, is_macro::Is)] pub enum Relationship { Leading, Trailing, Dangling, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, is_macro::Is)] pub enum Parenthesize { /// Always parenthesize the statement or expression. Always,