mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-27 13:54:25 +00:00
Improve comment handling around PatternMatchAs
(#6797)
## Summary Follows up on https://github.com/astral-sh/ruff/pull/6652#discussion_r1300871033 with some modifications to the `PatternMatchAs` comment handling. Specifically, any comments between the `as` and the end are now formatted as dangling, and we now insert some newlines in the appropriate places. ## Test Plan `cargo test`
This commit is contained in:
parent
d08f697a04
commit
1e6d1182bf
4 changed files with 142 additions and 7 deletions
|
@ -1,6 +1,7 @@
|
|||
use ruff_formatter::{write, Buffer, FormatResult};
|
||||
use ruff_python_ast::{Pattern, PatternMatchAs};
|
||||
|
||||
use crate::comments::{dangling_comments, SourceComment};
|
||||
use crate::expression::parentheses::parenthesized;
|
||||
use crate::prelude::*;
|
||||
use crate::{FormatNodeRule, PyFormatter};
|
||||
|
@ -16,6 +17,8 @@ impl FormatNodeRule<PatternMatchAs> for FormatPatternMatchAs {
|
|||
name,
|
||||
} = item;
|
||||
|
||||
let comments = f.context().comments().clone();
|
||||
|
||||
if let Some(name) = name {
|
||||
if let Some(pattern) = pattern {
|
||||
// Parenthesize nested `PatternMatchAs` like `(a as b) as c`.
|
||||
|
@ -31,7 +34,24 @@ impl FormatNodeRule<PatternMatchAs> for FormatPatternMatchAs {
|
|||
pattern.format().fmt(f)?;
|
||||
}
|
||||
|
||||
write!(f, [space(), text("as"), space()])?;
|
||||
if comments.has_trailing(pattern.as_ref()) {
|
||||
write!(f, [hard_line_break()])?;
|
||||
} else {
|
||||
write!(f, [space()])?;
|
||||
}
|
||||
|
||||
write!(f, [text("as")])?;
|
||||
|
||||
let trailing_as_comments = comments.dangling(item);
|
||||
if trailing_as_comments.is_empty() {
|
||||
write!(f, [space()])?;
|
||||
} else if trailing_as_comments
|
||||
.iter()
|
||||
.all(|comment| comment.line_position().is_own_line())
|
||||
{
|
||||
write!(f, [hard_line_break()])?;
|
||||
}
|
||||
write!(f, [dangling_comments(trailing_as_comments)])?;
|
||||
}
|
||||
name.format().fmt(f)
|
||||
} else {
|
||||
|
@ -39,4 +59,12 @@ impl FormatNodeRule<PatternMatchAs> for FormatPatternMatchAs {
|
|||
text("_").fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_dangling_comments(
|
||||
&self,
|
||||
_dangling_comments: &[SourceComment],
|
||||
_f: &mut PyFormatter,
|
||||
) -> FormatResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue