MCPcopy Create free account
hub / github.com/astral-sh/ruff / fmt_fields

Method fmt_fields

crates/ruff_python_formatter/src/expression/expr_subscript.rs:27–80  ·  view source on GitHub ↗
(&self, item: &ExprSubscript, f: &mut PyFormatter)

Source from the content-addressed store, hash-verified

25
26impl FormatNodeRule<ExprSubscript> for FormatExprSubscript {
27 fn fmt_fields(&self, item: &ExprSubscript, f: &mut PyFormatter) -> FormatResult<()> {
28 let ExprSubscript {
29 range: _,
30 node_index: _,
31 value,
32 slice,
33 ctx: _,
34 } = item;
35
36 let call_chain_layout = self.call_chain_layout.apply_in_node(item, f);
37
38 let comments = f.context().comments().clone();
39 let dangling_comments = comments.dangling(item);
40 debug_assert!(
41 dangling_comments.len() <= 1,
42 "A subscript expression can only have a single dangling comment, the one after the bracket"
43 );
44
45 let format_inner = format_with(|f: &mut PyFormatter| {
46 if f.context().is_expression_parenthesized(value.into()) {
47 value.format().with_options(Parentheses::Always).fmt(f)
48 } else {
49 match value.as_ref() {
50 Expr::Attribute(expr) => expr
51 .format()
52 .with_options(call_chain_layout.decrement_call_like_count())
53 .fmt(f),
54 Expr::Call(expr) => expr.format().with_options(call_chain_layout).fmt(f),
55 Expr::Subscript(expr) => expr.format().with_options(call_chain_layout).fmt(f),
56 _ => value.format().with_options(Parentheses::Never).fmt(f),
57 }
58 }?;
59
60 let format_slice = format_with(|f: &mut PyFormatter| {
61 if let Expr::Tuple(tuple) = slice.as_ref() {
62 write!(f, [tuple.format().with_options(TupleParentheses::Preserve)])
63 } else {
64 write!(f, [slice.format()])
65 }
66 });
67
68 parenthesized("[", &format_slice, "]")
69 .with_dangling_comments(dangling_comments)
70 .fmt(f)
71 });
72
73 let is_call_chain_root =
74 self.call_chain_layout == CallChainLayout::Default && call_chain_layout.is_fluent();
75 if is_call_chain_root {
76 write!(f, [group(&format_inner)])
77 } else {
78 write!(f, [format_inner])
79 }
80 }
81}
82
83impl NeedsParentheses for ExprSubscript {

Callers

nothing calls this directly

Calls 15

format_withFunction · 0.85
apply_in_nodeMethod · 0.80
is_fluentMethod · 0.80
parenthesizedFunction · 0.70
cloneMethod · 0.45
commentsMethod · 0.45
contextMethod · 0.45
danglingMethod · 0.45
fmtMethod · 0.45

Tested by

no test coverage detected