Skip to content

Commit

Permalink
Support fmt: skip on compound statements (#6593)
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser authored Aug 17, 2023
1 parent 4dc32a0 commit fa7442d
Show file tree
Hide file tree
Showing 23 changed files with 1,384 additions and 624 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
def http_error(status):
match status : # fmt: skip
case 400 : # fmt: skip
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

# point is an (x, y) tuple
match point:
case (0, 0): # fmt: skip
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")

class Point:
x: int
y: int

def location(point):
match point:
case Point(x=0, y =0 ) : # fmt: skip
print("Origin is the point's location.")
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} and the point is on the x-axis.")
case Point():
print("The point is located somewhere else on the plane.")
case _:
print("Not a point")


match points:
case []:
print("No points in the list.")
case [
Point(0, 0)
]: # fmt: skip
print("The origin is the only point in the list.")
case [Point(x, y)]:
print(f"A single point {x}, {y} is in the list.")
case [Point(0, y1), Point(0, y2)]:
print(f"Two points on the Y axis at {y1}, {y2} are in the list.")
case _:
print("Something else is found in the list.")


match test_variable:
case (
'warning',
code,
40
): # fmt: skip
print("A warning has been received.")
case ('error', code, _):
print(f"An error {code} occurred.")


match point:
case Point(x, y) if x == y: # fmt: skip
print(f"The point is located on the diagonal Y=X at {x}.")
case Point(x, y):
print(f"Point is not on the diagonal.")
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
for item in container:
if search_something(item):
# Found it!
process(item)
break
# leading comment
else : #fmt: skip
# Didn't find anything..
not_found_in_container()


while i < 10:
print(i)

# leading comment
else : #fmt: skip
# Didn't find anything..
print("I was already larger than 9")


try : # fmt: skip
some_call()
except Exception : # fmt: skip
pass
except : # fmt: skip
handle_exception()

else : # fmt: skip
pass
finally : # fmt: skip
finally_call()
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
if (
# a leading condition comment
len([1, 23, 3, 4, 5]) > 2 # trailing condition comment
# trailing own line comment
): # fmt: skip
pass


if ( # trailing open parentheses comment
# a leading condition comment
len([1, 23, 3, 4, 5]) > 2
) and ((((y)))): # fmt: skip
pass


if ( # trailing open parentheses comment
# a leading condition comment
len([1, 23, 3, 4, 5]) > 2
) and y: # fmt: skip
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class TestTypeParam[ T ]: # fmt: skip
pass

class TestTypeParam [ # trailing open paren comment
# leading comment
T # trailing type param comment
# trailing type param own line comment
]: # fmt: skip
pass

class TestTrailingComment4[
T
] ( # trailing arguments open parenthesis comment
# leading argument comment
A # trailing argument comment
# trailing argument own line comment
): # fmt: skip
pass

def test [
# comment
A,

# another

B,
] (): # fmt: skip
...
1 change: 0 additions & 1 deletion crates/ruff_python_formatter/src/comments/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,6 @@ impl<'a> Comments<'a> {
}

/// Returns an iterator over the [leading](self#leading-comments) and [trailing comments](self#trailing-comments) of `node`.
#[allow(unused)]
pub(crate) fn leading_trailing_comments<T>(
&self,
node: T,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use crate::comments::{trailing_comments, SourceComment};
use ruff_formatter::FormatRuleWithOptions;
use ruff_formatter::{write, Buffer, FormatResult};
use ruff_python_ast::ExceptHandlerExceptHandler;

use crate::comments::SourceComment;
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::prelude::*;
use crate::statement::clause::{clause_header, ClauseHeader};
use crate::{FormatNodeRule, PyFormatter};
use ruff_formatter::FormatRuleWithOptions;
use ruff_formatter::{write, Buffer, FormatResult};
use ruff_python_ast::ExceptHandlerExceptHandler;

#[derive(Copy, Clone, Default)]
pub enum ExceptHandlerKind {
Expand Down Expand Up @@ -49,32 +51,42 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
write!(
f,
[
text("except"),
match self.except_handler_kind {
ExceptHandlerKind::Regular => None,
ExceptHandlerKind::Starred => Some(text("*")),
}
]
)?;
clause_header(
ClauseHeader::ExceptHandler(item),
dangling_comments,
&format_with(|f| {
write!(
f,
[
text("except"),
match self.except_handler_kind {
ExceptHandlerKind::Regular => None,
ExceptHandlerKind::Starred => Some(text("*")),
}
]
)?;

if let Some(type_) = type_ {
write!(
f,
[
space(),
maybe_parenthesize_expression(type_, item, Parenthesize::IfBreaks)
]
)?;
if let Some(name) = name {
write!(f, [space(), text("as"), space(), name.format()])?;
}
}
write!(
f,
[
text(":"),
trailing_comments(dangling_comments),
block_indent(&body.format()),
if let Some(type_) = type_ {
write!(
f,
[
space(),
maybe_parenthesize_expression(
type_,
item,
Parenthesize::IfBreaks
)
]
)?;
if let Some(name) = name {
write!(f, [space(), text("as"), space(), name.format()])?;
}
}

Ok(())
}),
),
block_indent(&body.format())
]
)
}
Expand Down
54 changes: 32 additions & 22 deletions crates/ruff_python_formatter/src/other/match_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ use ruff_python_ast::{MatchCase, Pattern, Ranged};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::TextRange;

use crate::comments::{leading_comments, trailing_comments, SourceComment};
use crate::comments::{leading_comments, SourceComment};
use crate::expression::parentheses::parenthesized;
use crate::prelude::*;
use crate::statement::clause::{clause_header, ClauseHeader};
use crate::{FormatError, FormatNodeRule, PyFormatter};

#[derive(Default)]
Expand All @@ -23,30 +24,39 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item);

write!(f, [text("case"), space()])?;
let leading_pattern_comments = comments.leading_comments(pattern);
if !leading_pattern_comments.is_empty() {
parenthesized(
"(",
&format_args![leading_comments(leading_pattern_comments), pattern.format()],
")",
)
.fmt(f)?;
} else if is_match_case_pattern_parenthesized(item, pattern, f.context())? {
parenthesized("(", &pattern.format(), ")").fmt(f)?;
} else {
pattern.format().fmt(f)?;
}

if let Some(guard) = guard {
write!(f, [space(), text("if"), space(), guard.format()])?;
}

write!(
f,
[
text(":"),
trailing_comments(dangling_item_comments),
clause_header(
ClauseHeader::MatchCase(item),
dangling_item_comments,
&format_with(|f| {
write!(f, [text("case"), space()])?;

let leading_pattern_comments = comments.leading_comments(pattern);
if !leading_pattern_comments.is_empty() {
parenthesized(
"(",
&format_args![
leading_comments(leading_pattern_comments),
pattern.format()
],
")",
)
.fmt(f)?;
} else if is_match_case_pattern_parenthesized(item, pattern, f.context())? {
parenthesized("(", &pattern.format(), ")").fmt(f)?;
} else {
pattern.format().fmt(f)?;
}

if let Some(guard) = guard {
write!(f, [space(), text("if"), space(), guard.format()])?;
}

Ok(())
}),
),
block_indent(&body.format())
]
)
Expand Down
Loading

0 comments on commit fa7442d

Please sign in to comment.