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

Method fmt_fields

crates/ruff_python_formatter/src/expression/expr_lambda.rs:18–145  ·  view source on GitHub ↗
(&self, item: &ExprLambda, f: &mut PyFormatter)

Source from the content-addressed store, hash-verified

16
17impl FormatNodeRule<ExprLambda> for FormatExprLambda {
18 fn fmt_fields(&self, item: &ExprLambda, f: &mut PyFormatter) -> FormatResult<()> {
19 let ExprLambda {
20 range: _,
21 node_index: _,
22 parameters,
23 body,
24 } = item;
25
26 let body = &**body;
27 let parameters = parameters.as_deref();
28
29 let comments = f.context().comments().clone();
30 let dangling = comments.dangling(item);
31
32 write!(f, [token("lambda")])?;
33
34 // Format any dangling comments before the parameters, but save any dangling comments after
35 // the parameters/after the header to be formatted with the body below.
36 let dangling_header_comments = if let Some(parameters) = parameters {
37 // In this context, a dangling comment can either be a comment between the `lambda` and the
38 // parameters, or a comment between the parameters and the body.
39 let (dangling_before_parameters, dangling_after_parameters) = dangling
40 .split_at(dangling.partition_point(|comment| comment.end() < parameters.start()));
41
42 if dangling_before_parameters.is_empty() {
43 // If the parameters have a leading comment, insert a hard line break. This
44 // comment is associated as a leading comment on the parameters:
45 //
46 // ```py
47 // (
48 // lambda
49 // * # comment
50 // x:
51 // x
52 // )
53 // ```
54 //
55 // so a hard line break is needed to avoid formatting it like:
56 //
57 // ```py
58 // (
59 // lambda # comment
60 // *x: x
61 // )
62 // ```
63 //
64 // which is unstable because it's missing the second space before the comment.
65 //
66 // Inserting the line break causes it to format like:
67 //
68 // ```py
69 // (
70 // lambda
71 // # comment
72 // *x :x
73 // )
74 // ```
75 //

Callers

nothing calls this directly

Calls 14

hard_line_breakFunction · 0.85
fits_expandedFunction · 0.85
split_atMethod · 0.80
has_leadingMethod · 0.80
contains_commentsMethod · 0.80
cloneMethod · 0.45
commentsMethod · 0.45
contextMethod · 0.45
danglingMethod · 0.45
endMethod · 0.45
startMethod · 0.45
is_emptyMethod · 0.45

Tested by

no test coverage detected