ruff_python_formatter 0.0.3

This is an internal component crate of Ruff
Documentation
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use ruff_formatter::{FormatRuleWithOptions, RemoveSoftLinesBuffer, format_args, write};
use ruff_python_ast::{AnyNodeRef, Expr, ExprLambda};
use ruff_text_size::Ranged;

use crate::builders::parenthesize_if_expands;
use crate::comments::{SourceComment, dangling_comments, leading_comments, trailing_comments};
use crate::expression::has_own_parentheses;
use crate::expression::parentheses::{
    NeedsParentheses, OptionalParentheses, Parentheses, is_expression_parenthesized,
};
use crate::other::parameters::ParametersParentheses;
use crate::prelude::*;

#[derive(Default)]
pub struct FormatExprLambda {
    layout: ExprLambdaLayout,
}

impl FormatNodeRule<ExprLambda> for FormatExprLambda {
    fn fmt_fields(&self, item: &ExprLambda, f: &mut PyFormatter) -> FormatResult<()> {
        let ExprLambda {
            range: _,
            node_index: _,
            parameters,
            body,
        } = item;

        let body = &**body;
        let parameters = parameters.as_deref();

        let comments = f.context().comments().clone();
        let dangling = comments.dangling(item);

        write!(f, [token("lambda")])?;

        // Format any dangling comments before the parameters, but save any dangling comments after
        // the parameters/after the header to be formatted with the body below.
        let dangling_header_comments = if let Some(parameters) = parameters {
            // In this context, a dangling comment can either be a comment between the `lambda` and the
            // parameters, or a comment between the parameters and the body.
            let (dangling_before_parameters, dangling_after_parameters) = dangling
                .split_at(dangling.partition_point(|comment| comment.end() < parameters.start()));

            if dangling_before_parameters.is_empty() {
                // If the parameters have a leading comment, insert a hard line break. This
                // comment is associated as a leading comment on the parameters:
                //
                // ```py
                // (
                //     lambda
                //     * # comment
                //     x:
                //     x
                // )
                // ```
                //
                // so a hard line break is needed to avoid formatting it like:
                //
                // ```py
                // (
                //     lambda # comment
                //     *x: x
                // )
                // ```
                //
                // which is unstable because it's missing the second space before the comment.
                //
                // Inserting the line break causes it to format like:
                //
                // ```py
                // (
                //     lambda
                //     # comment
                //     *x :x
                // )
                // ```
                //
                // which is also consistent with the formatting in the presence of an actual
                // dangling comment on the lambda:
                //
                // ```py
                // (
                //     lambda # comment 1
                //     * # comment 2
                //     x:
                //     x
                // )
                // ```
                //
                // formats to:
                //
                // ```py
                // (
                //     lambda  # comment 1
                //     # comment 2
                //     *x: x
                // )
                // ```
                if comments.has_leading(parameters) {
                    hard_line_break().fmt(f)?;
                } else {
                    write!(f, [space()])?;
                }
            } else {
                write!(f, [dangling_comments(dangling_before_parameters)])?;
            }

            // Try to keep the parameters on a single line, unless there are intervening comments.
            if !comments.contains_comments(parameters.into()) {
                let mut buffer = RemoveSoftLinesBuffer::new(f);
                write!(
                    buffer,
                    [parameters
                        .format()
                        .with_options(ParametersParentheses::Never)]
                )?;
            } else {
                write!(
                    f,
                    [parameters
                        .format()
                        .with_options(ParametersParentheses::Never)]
                )?;
            }

            dangling_after_parameters
        } else {
            dangling
        };

        write!(f, [token(":")])?;

        if dangling_header_comments.is_empty() {
            write!(f, [space()])?;
        }

        let fmt_body = FormatBody {
            body,
            dangling_header_comments,
            needs_parentheses: body.needs_parentheses(item.into(), f.context()),
        };

        match self.layout {
            ExprLambdaLayout::Assignment => fits_expanded(&fmt_body).fmt(f),
            ExprLambdaLayout::Default => fmt_body.fmt(f),
        }
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub enum ExprLambdaLayout {
    #[default]
    Default,

    /// The [`ExprLambda`] is the direct child of an assignment expression, so it needs to use
    /// `fits_expanded` to prefer parenthesizing its own body before the assignment tries to
    /// parenthesize the whole lambda. For example, we want this formatting:
    ///
    /// ```py
    /// long_assignment_target = lambda x, y, z: (
    ///     x + y + z
    /// )
    /// ```
    ///
    /// instead of either of these:
    ///
    /// ```py
    /// long_assignment_target = (
    ///     lambda x, y, z: (
    ///         x + y + z
    ///     )
    /// )
    ///
    /// long_assignment_target = (
    ///     lambda x, y, z: x + y + z
    /// )
    /// ```
    Assignment,
}

impl FormatRuleWithOptions<ExprLambda, PyFormatContext<'_>> for FormatExprLambda {
    type Options = ExprLambdaLayout;

    fn with_options(mut self, options: Self::Options) -> Self {
        self.layout = options;
        self
    }
}

impl NeedsParentheses for ExprLambda {
    fn needs_parentheses(
        &self,
        parent: AnyNodeRef,
        _context: &PyFormatContext,
    ) -> OptionalParentheses {
        if parent.is_expr_await() {
            OptionalParentheses::Always
        } else {
            OptionalParentheses::Multiline
        }
    }
}

struct FormatBody<'a> {
    body: &'a Expr,

    /// Dangling comments attached to the lambda header that should be formatted with the body.
    ///
    /// These can include both own-line and end-of-line comments. For lambdas with parameters, this
    /// means comments after the parameters:
    ///
    /// ```py
    /// (
    ///     lambda x, y  # 1
    ///         # 2
    ///         :  # 3
    ///         # 4
    ///         x + y
    /// )
    /// ```
    ///
    /// Or all dangling comments for lambdas without parameters:
    ///
    /// ```py
    /// (
    ///     lambda  # 1
    ///         # 2
    ///         :  # 3
    ///         # 4
    ///         1
    /// )
    /// ```
    ///
    /// In most cases these should formatted within the parenthesized body, as in:
    ///
    /// ```py
    /// (
    ///     lambda: (  # 1
    ///         # 2
    ///         # 3
    ///         # 4
    ///         1
    ///     )
    /// )
    /// ```
    ///
    /// or without `# 2`:
    ///
    /// ```py
    /// (
    ///     lambda: (  # 1  # 3
    ///         # 4
    ///         1
    ///     )
    /// )
    /// ```
    dangling_header_comments: &'a [SourceComment],
    needs_parentheses: OptionalParentheses,
}

impl Format<PyFormatContext<'_>> for FormatBody<'_> {
    #[expect(clippy::if_same_then_else)]
    fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> {
        let FormatBody {
            dangling_header_comments,
            body,
            needs_parentheses,
        } = self;

        let body = *body;
        let comments = f.context().comments().clone();
        let body_comments = comments.leading_dangling_trailing(body);

        if !dangling_header_comments.is_empty() {
            // Split the dangling header comments into trailing comments formatted with the lambda
            // header (1) and leading comments formatted with the body (2, 3, 4).
            //
            // ```python
            // (
            //     lambda  # 1
            //     # 2
            //     :  # 3
            //     # 4
            //     y
            // )
            // ```
            //
            // Note that these are split based on their line position rather than using
            // `partition_point` based on a range, for example.
            let (trailing_header_comments, leading_body_comments) = dangling_header_comments
                .split_at(
                    dangling_header_comments
                        .iter()
                        .position(|comment| comment.line_position().is_own_line())
                        .unwrap_or(dangling_header_comments.len()),
                );

            // If the body is parenthesized and has its own leading comments, preserve the
            // separation between the dangling lambda comments and the body comments. For
            // example, preserve this comment positioning:
            //
            // ```python
            // (
            //      lambda:  # 1
            //      # 2
            //      (  # 3
            //          x
            //      )
            // )
            // ```
            //
            // 1 and 2 are dangling on the lambda and emitted first, followed by a hard line
            // break and the parenthesized body with its leading comments.
            //
            // However, when removing 2, 1 and 3 can instead be formatted on the same line:
            //
            // ```python
            // (
            //      lambda: (  # 1  # 3
            //          x
            //      )
            // )
            // ```
            let comments = f.context().comments();
            if is_expression_parenthesized(body.into(), comments.ranges(), f.context().source())
                && comments.has_leading(body)
            {
                trailing_comments(dangling_header_comments).fmt(f)?;

                // Note that `leading_body_comments` have already been formatted as part of
                // `dangling_header_comments` above, but their presence still determines the spacing
                // here.
                if leading_body_comments.is_empty() {
                    space().fmt(f)?;
                } else {
                    hard_line_break().fmt(f)?;
                }

                body.format().with_options(Parentheses::Always).fmt(f)
            } else {
                write!(
                    f,
                    [
                        space(),
                        token("("),
                        trailing_comments(trailing_header_comments),
                        block_indent(&format_args!(
                            leading_comments(leading_body_comments),
                            body.format().with_options(Parentheses::Never)
                        )),
                        token(")")
                    ]
                )
            }
        }
        // If the body has comments, we always want to preserve the parentheses. This also
        // ensures that we correctly handle parenthesized comments, and don't need to worry
        // about them in the implementation below.
        else if body_comments.has_leading() || body_comments.has_trailing_own_line() {
            body.format().with_options(Parentheses::Always).fmt(f)
        }
        // Include parentheses for cases that always require them, such as named expressions:
        //
        // ```py
        // lambda x: (y := x + 1)
        // ```
        else if matches!(needs_parentheses, OptionalParentheses::Always) {
            body.format().with_options(Parentheses::Always).fmt(f)
        }
        // Use `parenthesize_if_expands` for cases that require parentheses when broken over
        // multiple lines, including some calls and subscripts:
        //
        // ```py
        // lambda x: "implicitly" "concatenated {x}".format(x)
        // lambda x: "implicitly" "concatenated {x}"[x]
        // ```
        else if matches!(needs_parentheses, OptionalParentheses::Multiline) {
            parenthesize_if_expands(&body.format().with_options(Parentheses::Never)).fmt(f)
        }
        // Calls and subscripts require special formatting because they have their own
        // parentheses, but they can also have an arbitrary amount of text before the
        // opening parenthesis. We want to avoid cases where we keep a long callable on the
        // same line as the lambda parameters. For example, `db_evmtx...` in:
        //
        // ```py
        // transaction_count = self._query_txs_for_range(
        //     get_count_fn=lambda from_ts, to_ts, _chain_id=chain_id: db_evmtx.count_transactions_in_range(
        //         chain_id=_chain_id,
        //         from_ts=from_ts,
        //         to_ts=to_ts,
        //     ),
        // )
        // ```
        //
        // should cause the whole lambda body to be parenthesized instead:
        //
        // ```py
        // transaction_count = self._query_txs_for_range(
        //     get_count_fn=lambda from_ts, to_ts, _chain_id=chain_id: (
        //         db_evmtx.count_transactions_in_range(
        //             chain_id=_chain_id,
        //             from_ts=from_ts,
        //             to_ts=to_ts,
        //         )
        //     ),
        // )
        // ```
        else if matches!(body, Expr::Call(_) | Expr::Subscript(_)) {
            let unparenthesized = body.format().with_options(Parentheses::Never).memoized();
            if unparenthesized.inspect(f)?.will_break() {
                expand_parent().fmt(f)?;
            }

            best_fitting![
                // body all flat
                unparenthesized,
                // body expanded
                group(&unparenthesized).should_expand(true),
                // parenthesized
                format_args![token("("), block_indent(&unparenthesized), token(")")]
            ]
            .fmt(f)
        }
        // For other cases with their own parentheses, such as lists, sets, dicts, tuples,
        // etc., we can just format the body directly. Their own formatting results in the
        // lambda being formatted well too. For example:
        //
        // ```py
        // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: [xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz]
        // ```
        //
        // gets formatted as:
        //
        // ```py
        // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: [
        //     xxxxxxxxxxxxxxxxxxxx,
        //     yyyyyyyyyyyyyyyyyyyy,
        //     zzzzzzzzzzzzzzzzzzzz
        // ]
        // ```
        else if has_own_parentheses(body, f.context()).is_some() {
            body.format().fmt(f)
        }
        // Finally, for expressions without their own parentheses, use
        // `parenthesize_if_expands` to add parentheses around the body, only if it expands
        // across multiple lines. The `Parentheses::Never` here also removes unnecessary
        // parentheses around lambda bodies that fit on one line. For example:
        //
        // ```py
        // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: xxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyy + zzzzzzzzzzzzzzzzzzzz
        // ```
        //
        // is formatted as:
        //
        // ```py
        // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: (
        //     xxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyy + zzzzzzzzzzzzzzzzzzzz
        // )
        // ```
        //
        // while
        //
        // ```py
        // lambda xxxxxxxxxxxxxxxxxxxx: (xxxxxxxxxxxxxxxxxxxx + 1)
        // ```
        //
        // is formatted as:
        //
        // ```py
        // lambda xxxxxxxxxxxxxxxxxxxx: xxxxxxxxxxxxxxxxxxxx + 1
        // ```
        else {
            parenthesize_if_expands(&body.format().with_options(Parentheses::Never)).fmt(f)
        }
    }
}