-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
expr_named_expr.rs
46 lines (43 loc) · 1.42 KB
/
expr_named_expr.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use crate::context::PyFormatContext;
use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize,
};
use crate::{AsFormat, FormatNodeRule, PyFormatter};
use ruff_formatter::prelude::{space, text};
use ruff_formatter::{write, Buffer, FormatResult};
use rustpython_parser::ast::ExprNamedExpr;
#[derive(Default)]
pub struct FormatExprNamedExpr;
impl FormatNodeRule<ExprNamedExpr> for FormatExprNamedExpr {
fn fmt_fields(&self, item: &ExprNamedExpr, f: &mut PyFormatter) -> FormatResult<()> {
let ExprNamedExpr {
target,
value,
range: _,
} = item;
write!(
f,
[
target.format(),
space(),
text(":="),
space(),
value.format(),
]
)
}
}
impl NeedsParentheses for ExprNamedExpr {
fn needs_parentheses(
&self,
parenthesize: Parenthesize,
context: &PyFormatContext,
) -> Parentheses {
match default_expression_needs_parentheses(self.into(), parenthesize, context) {
// Unlike tuples, named expression parentheses are not part of the range even when
// mandatory. See [PEP 572](https://peps.python.org/pep-0572/) for details.
Parentheses::Optional => Parentheses::Always,
parentheses => parentheses,
}
}
}