-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Format PatternMatchClass
#6860
Merged
charliermarsh
merged 3 commits into
astral-sh:main
from
LaBatata101:format-pattern-match-class
Aug 25, 2023
Merged
Format PatternMatchClass
#6860
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
146 changes: 134 additions & 12 deletions
146
crates/ruff_python_formatter/src/pattern/pattern_match_class.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,154 @@ | ||
use ruff_formatter::{write, Buffer, FormatResult}; | ||
use crate::comments::{dangling_comments, SourceComment}; | ||
use ruff_formatter::write; | ||
use ruff_python_ast::node::AnyNodeRef; | ||
use ruff_python_ast::PatternMatchClass; | ||
use ruff_python_ast::{Pattern, PatternMatchClass, Ranged}; | ||
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; | ||
use ruff_text_size::{TextRange, TextSize}; | ||
|
||
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; | ||
use crate::expression::parentheses::{ | ||
empty_parenthesized, parenthesized, NeedsParentheses, OptionalParentheses, Parentheses, | ||
}; | ||
use crate::prelude::*; | ||
use crate::{not_yet_implemented_custom_text, FormatNodeRule, PyFormatter}; | ||
|
||
#[derive(Default)] | ||
pub struct FormatPatternMatchClass; | ||
|
||
impl FormatNodeRule<PatternMatchClass> for FormatPatternMatchClass { | ||
fn fmt_fields(&self, item: &PatternMatchClass, f: &mut PyFormatter) -> FormatResult<()> { | ||
write!( | ||
f, | ||
[not_yet_implemented_custom_text( | ||
"NOT_YET_IMPLEMENTED_PatternMatchClass(0, 0)", | ||
item | ||
)] | ||
) | ||
let PatternMatchClass { | ||
range, | ||
cls, | ||
patterns, | ||
kwd_attrs, | ||
kwd_patterns, | ||
} = item; | ||
|
||
let comments = f.context().comments().clone(); | ||
let dangling = comments.dangling(item); | ||
|
||
// Identify the dangling comments before and after the open parenthesis. | ||
let (before_parenthesis, after_parenthesis) = if let Some(left_paren) = | ||
SimpleTokenizer::starts_at(cls.end(), f.context().source()) | ||
.find(|token| token.kind() == SimpleTokenKind::LParen) | ||
{ | ||
dangling | ||
.split_at(dangling.partition_point(|comment| comment.start() < left_paren.start())) | ||
} else { | ||
(dangling, [].as_slice()) | ||
}; | ||
|
||
write!(f, [cls.format(), dangling_comments(before_parenthesis)])?; | ||
|
||
match (patterns.as_slice(), kwd_attrs.as_slice()) { | ||
([], []) => { | ||
// No patterns; render parentheses with any dangling comments. | ||
write!(f, [empty_parenthesized("(", after_parenthesis, ")")]) | ||
} | ||
([pattern], []) => { | ||
// A single pattern. We need to take care not to re-parenthesize it, since our standard | ||
// parenthesis detection will false-positive here. | ||
let parentheses = if is_single_argument_parenthesized( | ||
pattern, | ||
item.end(), | ||
f.context().source(), | ||
) { | ||
Parentheses::Always | ||
} else { | ||
Parentheses::Never | ||
}; | ||
write!( | ||
f, | ||
[ | ||
parenthesized("(", &pattern.format().with_options(parentheses), ")") | ||
.with_dangling_comments(after_parenthesis) | ||
] | ||
) | ||
} | ||
_ => { | ||
// Multiple patterns: standard logic. | ||
let items = format_with(|f| { | ||
let mut join = f.join_comma_separated(range.end()); | ||
join.nodes(patterns.iter()); | ||
for (key, value) in kwd_attrs.iter().zip(kwd_patterns.iter()) { | ||
join.entry( | ||
key, | ||
&format_with(|f| write!(f, [key.format(), text("="), value.format()])), | ||
); | ||
} | ||
join.finish() | ||
}); | ||
write!( | ||
f, | ||
[parenthesized("(", &group(&items), ")") | ||
.with_dangling_comments(after_parenthesis)] | ||
) | ||
} | ||
} | ||
} | ||
|
||
fn fmt_dangling_comments( | ||
&self, | ||
_dangling_comments: &[SourceComment], | ||
_f: &mut PyFormatter, | ||
) -> FormatResult<()> { | ||
Ok(()) | ||
} | ||
} | ||
|
||
impl NeedsParentheses for PatternMatchClass { | ||
fn needs_parentheses( | ||
&self, | ||
_parent: AnyNodeRef, | ||
_context: &PyFormatContext, | ||
context: &PyFormatContext, | ||
) -> OptionalParentheses { | ||
// If there are any comments outside of the class parentheses, break: | ||
// ```python | ||
// case ( | ||
// Pattern | ||
// # dangling | ||
// (...) | ||
// ): ... | ||
// ``` | ||
let dangling = context.comments().dangling(self); | ||
if !dangling.is_empty() { | ||
if let Some(left_paren) = SimpleTokenizer::starts_at(self.cls.end(), context.source()) | ||
.find(|token| token.kind() == SimpleTokenKind::LParen) | ||
{ | ||
if dangling | ||
.iter() | ||
.any(|comment| comment.start() < left_paren.start()) | ||
{ | ||
return OptionalParentheses::Multiline; | ||
}; | ||
} | ||
} | ||
OptionalParentheses::Never | ||
} | ||
} | ||
|
||
/// Returns `true` if the pattern (which is the only argument to a [`PatternMatchClass`]) is | ||
/// parenthesized. Used to avoid falsely assuming that `x` is parenthesized in cases like: | ||
/// ```python | ||
/// case Point2D(x): ... | ||
/// ``` | ||
fn is_single_argument_parenthesized(pattern: &Pattern, call_end: TextSize, source: &str) -> bool { | ||
let mut has_seen_r_paren = false; | ||
for token in SimpleTokenizer::new(source, TextRange::new(pattern.end(), call_end)).skip_trivia() | ||
{ | ||
match token.kind() { | ||
SimpleTokenKind::RParen => { | ||
if has_seen_r_paren { | ||
return true; | ||
} | ||
has_seen_r_paren = true; | ||
} | ||
// Skip over any trailing comma | ||
SimpleTokenKind::Comma => continue, | ||
_ => { | ||
// Passed the arguments | ||
break; | ||
} | ||
} | ||
} | ||
false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you add something like
with the left hand side and the right hand side split of the assignment split by comment? I wanted to add an additional comment before the
b
but that's blocked by #6866