biome_js_formatter 0.0.2

Biome's JavaScript formatter
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
use crate::prelude::*;
use biome_formatter::{
    format_args, write, CstFormatContext, FormatRuleWithOptions, RemoveSoftLinesBuffer,
};
use std::iter::once;

use crate::context::trailing_comma::FormatTrailingComma;
use crate::js::expressions::call_arguments::GroupedCallArgumentLayout;
use crate::parentheses::{
    is_binary_like_left_or_right, is_callee, is_conditional_test,
    update_or_lower_expression_needs_parentheses, AnyJsExpressionLeftSide, NeedsParentheses,
};
use crate::utils::function_body::{FormatMaybeCachedFunctionBody, FunctionBodyCacheMode};
use crate::utils::test_call::is_test_call_argument;
use crate::utils::{resolve_left_most_expression, AssignmentLikeLayout};
use biome_js_syntax::{
    AnyJsArrowFunctionParameters, AnyJsBindingPattern, AnyJsExpression, AnyJsFormalParameter,
    AnyJsFunctionBody, AnyJsParameter, AnyJsTemplateElement, JsArrowFunctionExpression,
    JsFormalParameter, JsSyntaxKind, JsSyntaxNode, JsTemplateExpression,
};
use biome_rowan::{SyntaxNodeOptionExt, SyntaxResult};

#[derive(Debug, Copy, Clone, Default)]
pub(crate) struct FormatJsArrowFunctionExpression {
    options: FormatJsArrowFunctionExpressionOptions,
}

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct FormatJsArrowFunctionExpressionOptions {
    pub assignment_layout: Option<AssignmentLikeLayout>,
    pub call_arg_layout: Option<GroupedCallArgumentLayout>,
    pub body_cache_mode: FunctionBodyCacheMode,
}

impl FormatRuleWithOptions<JsArrowFunctionExpression> for FormatJsArrowFunctionExpression {
    type Options = FormatJsArrowFunctionExpressionOptions;

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

impl FormatNodeRule<JsArrowFunctionExpression> for FormatJsArrowFunctionExpression {
    fn fmt_fields(
        &self,
        node: &JsArrowFunctionExpression,
        f: &mut JsFormatter,
    ) -> FormatResult<()> {
        let layout =
            ArrowFunctionLayout::for_arrow(node.clone(), f.context().comments(), &self.options)?;

        match layout {
            ArrowFunctionLayout::Chain(chain) => {
                write!(f, [chain])
            }
            ArrowFunctionLayout::Single(arrow) => {
                use self::AnyJsExpression::*;
                use AnyJsFunctionBody::*;

                let body = arrow.body()?;

                let format_signature = format_with(|f| {
                    write!(
                        f,
                        [
                            format_signature(&arrow, self.options.call_arg_layout.is_some()),
                            space(),
                            arrow.fat_arrow_token().format()
                        ]
                    )
                });

                let format_body = FormatMaybeCachedFunctionBody {
                    body: &body,
                    mode: self.options.body_cache_mode,
                };

                // With arrays, arrow selfs and objects, they have a natural line breaking strategy:
                // Arrays and objects become blocks:
                //
                //    [
                //      100000,
                //      200000,
                //      300000
                //    ]
                //
                // Arrow selfs get line broken after the `=>`:
                //
                //  (foo) => (bar) =>
                //     (foo + bar) * (foo + bar)
                //
                // Therefore if our body is an arrow self, array, or object, we
                // do not have a soft line break after the arrow because the body is
                // going to get broken anyways.
                let body_has_soft_line_break = match &body {
                    JsFunctionBody(_)
                    | AnyJsExpression(
                        JsArrowFunctionExpression(_) | JsArrayExpression(_) | JsObjectExpression(_),
                    ) => !f.comments().has_leading_own_line_comment(body.syntax()),
                    AnyJsExpression(JsxTagExpression(_)) => true,
                    AnyJsExpression(JsTemplateExpression(template)) => {
                        is_multiline_template_starting_on_same_line(template)
                    }
                    AnyJsExpression(JsSequenceExpression(_)) => {
                        return write!(
                            f,
                            [group(&format_args![
                                format_signature,
                                group(&format_args![
                                    space(),
                                    text("("),
                                    soft_block_indent(&format_body),
                                    text(")")
                                ])
                            ])]
                        );
                    }
                    _ => false,
                };

                if body_has_soft_line_break {
                    write![f, [format_signature, space(), format_body]]
                } else {
                    // Add parentheses to avoid confusion between `a => b ? c : d` and `a <= b ? c : d`
                    // but only if the body isn't an object/function or class expression because parentheses are always required in that
                    // case and added by the object expression itself
                    let should_add_parens = match &body {
                        AnyJsExpression(expression @ JsConditionalExpression(_)) => {
                            let are_parentheses_mandatory = matches!(
                                resolve_left_most_expression(expression),
                                AnyJsExpressionLeftSide::AnyJsExpression(
                                    JsObjectExpression(_)
                                        | JsFunctionExpression(_)
                                        | JsClassExpression(_)
                                )
                            );

                            !are_parentheses_mandatory
                        }
                        _ => false,
                    };

                    let is_last_call_arg = matches!(
                        self.options.call_arg_layout,
                        Some(GroupedCallArgumentLayout::GroupedLastArgument)
                    );

                    let should_add_soft_line = (is_last_call_arg
                        // if it's inside a JSXExpression (e.g. an attribute) we should align the expression's closing } with the line with the opening {.
                        || matches!(node.syntax().parent().kind(), Some(JsSyntaxKind::JSX_EXPRESSION_CHILD | JsSyntaxKind::JSX_EXPRESSION_ATTRIBUTE_VALUE)))
                        && !f.context().comments().has_comments(node.syntax());

                    write!(
                        f,
                        [
                            format_signature,
                            group(&format_args![
                                soft_line_indent_or_space(&format_with(|f| {
                                    if should_add_parens {
                                        write!(f, [if_group_fits_on_line(&text("("))])?;
                                    }

                                    write!(f, [format_body])?;

                                    if should_add_parens {
                                        write!(f, [if_group_fits_on_line(&text(")"))])?;
                                    }

                                    Ok(())
                                })),
                                is_last_call_arg.then_some(format_args![FormatTrailingComma::All,]),
                                should_add_soft_line.then_some(format_args![soft_line_break()])
                            ])
                        ]
                    )
                }
            }
        }
    }

    fn needs_parentheses(&self, item: &JsArrowFunctionExpression) -> bool {
        item.needs_parentheses()
    }

    fn fmt_dangling_comments(
        &self,
        _: &JsArrowFunctionExpression,
        _: &mut JsFormatter,
    ) -> FormatResult<()> {
        // Formatted inside of `fmt_fields`
        Ok(())
    }
}

/// Writes the arrow function type parameters, parameters, and return type annotation.
///
/// Formats the parameters and return type annotation without any soft line breaks if `is_first_or_last_call_argument` is `true`
/// so that the parameters and return type are kept on the same line.
///
/// # Errors
///
/// Returns [`FormatError::PoorLayout`] if `is_first_or_last_call_argument` is `true` but the parameters
/// or return type annotation contain any content that forces a [*group to break](FormatElements::will_break).
///
/// This error gets captured by [FormatJsCallArguments].
fn format_signature(
    arrow: &JsArrowFunctionExpression,
    is_first_or_last_call_argument: bool,
) -> impl Format<JsFormatContext> + '_ {
    format_with(move |f| {
        if let Some(async_token) = arrow.async_token() {
            write!(f, [async_token.format(), space()])?;
        }

        let format_parameters = format_with(|f: &mut JsFormatter| {
            write!(f, [arrow.type_parameters().format()])?;

            match arrow.parameters()? {
                AnyJsArrowFunctionParameters::AnyJsBinding(binding) => {
                    let should_hug = is_test_call_argument(arrow.syntax())?;

                    let parentheses_not_needed = can_avoid_parentheses(arrow, f);

                    if !parentheses_not_needed {
                        write!(f, [text("(")])?;
                    }

                    if should_hug {
                        write!(f, [binding.format()])?;
                    } else {
                        write!(
                            f,
                            [&soft_block_indent(&format_args![
                                binding.format(),
                                FormatTrailingComma::All
                            ])]
                        )?
                    }

                    if !parentheses_not_needed {
                        write!(f, [text(")")])?;
                    }
                }
                AnyJsArrowFunctionParameters::JsParameters(params) => {
                    write!(f, [params.format()])?;
                }
            };

            Ok(())
        });

        if is_first_or_last_call_argument {
            let mut buffer = RemoveSoftLinesBuffer::new(f);
            let mut recording = buffer.start_recording();

            write!(
                recording,
                [group(&format_args![
                    group(&format_parameters),
                    group(&arrow.return_type_annotation().format())
                ])]
            )?;

            if recording.stop().will_break() {
                return Err(FormatError::PoorLayout);
            }
        } else {
            write!(
                f,
                [group(&format_args![
                    format_parameters,
                    arrow.return_type_annotation().format()
                ])]
            )?;
        }

        if f.comments().has_dangling_comments(arrow.syntax()) {
            write!(f, [space(), format_dangling_comments(arrow.syntax())])?;
        }

        Ok(())
    })
}

fn should_break_chain(arrow: &JsArrowFunctionExpression) -> SyntaxResult<bool> {
    if arrow.type_parameters().is_some() {
        return Ok(true);
    }

    let parameters = arrow.parameters()?;

    let has_parameters = match &parameters {
        AnyJsArrowFunctionParameters::AnyJsBinding(_) => true,
        AnyJsArrowFunctionParameters::JsParameters(parameters) => !parameters.items().is_empty(),
    };

    if arrow.return_type_annotation().is_some() && has_parameters {
        return Ok(true);
    }

    // Break if the function has any rest, object, or array parameter
    let result = has_rest_object_or_array_parameter(&parameters);

    Ok(result)
}

fn has_rest_object_or_array_parameter(parameters: &AnyJsArrowFunctionParameters) -> bool {
    match parameters {
        AnyJsArrowFunctionParameters::AnyJsBinding(_) => false,
        AnyJsArrowFunctionParameters::JsParameters(parameters) => parameters
            .items()
            .iter()
            .flatten()
            .any(|parameter| match parameter {
                AnyJsParameter::AnyJsFormalParameter(AnyJsFormalParameter::JsFormalParameter(
                    parameter,
                )) => {
                    matches!(
                        parameter.binding(),
                        Ok(AnyJsBindingPattern::JsArrayBindingPattern(_)
                            | AnyJsBindingPattern::JsObjectBindingPattern(_))
                    )
                }
                AnyJsParameter::AnyJsFormalParameter(AnyJsFormalParameter::JsBogusParameter(_)) => {
                    false
                }
                AnyJsParameter::TsThisParameter(_) => false,
                AnyJsParameter::JsRestParameter(_) => true,
            }),
    }
}

/// Returns `true` if parentheses can be safely avoided and the `arrow_parentheses` formatter option allows it
pub fn can_avoid_parentheses(arrow: &JsArrowFunctionExpression, f: &mut JsFormatter) -> bool {
    arrow.parameters().map_or(false, |parameters| {
        f.options().arrow_parentheses().is_as_needed()
            && parameters.len() == 1
            && arrow.type_parameters().is_none()
            && arrow.return_type_annotation().is_none()
            && !has_rest_object_or_array_parameter(&parameters)
            && !parameters
                .as_js_parameters()
                .and_then(|p| p.items().first()?.ok())
                .and_then(|p| JsFormalParameter::cast(p.syntax().clone()))
                .is_some_and(|p| {
                    f.context().comments().has_comments(p.syntax())
                        || p.initializer().is_some()
                        || p.question_mark_token().is_some()
                        || p.type_annotation().is_some()
                })
    })
}

#[derive(Clone, Debug)]
enum ArrowFunctionLayout {
    /// Arrow function with a non-arrow function body
    Single(JsArrowFunctionExpression),

    /// A chain of at least two arrow functions.
    ///
    /// An arrow function is part of the chain when it is the body of the parent arrow function.
    ///
    /// The idea of arrow chains is that they break after the `=>` token
    ///
    /// ```javascript
    /// const x =
    ///   (a): string =>
    ///   (b) =>
    ///   (c) =>
    ///   (d) =>
    ///   (e) =>
    ///     f;
    /// ```
    Chain(ArrowChain),
}

#[derive(Clone, Debug)]
struct ArrowChain {
    /// The top most arrow function in the chain
    head: JsArrowFunctionExpression,

    /// The arrow functions in the chain that are neither the first nor the last.
    /// Empty for chains consisting only of two arrow functions.
    middle: Vec<JsArrowFunctionExpression>,

    /// The last arrow function in the chain
    tail: JsArrowFunctionExpression,

    options: FormatJsArrowFunctionExpressionOptions,

    /// Whether the group wrapping the signatures should be expanded or not.
    expand_signatures: bool,
}

impl ArrowChain {
    /// Returns an iterator over all arrow functions in this chain
    fn arrows(&self) -> impl Iterator<Item = &JsArrowFunctionExpression> {
        once(&self.head)
            .chain(self.middle.iter())
            .chain(once(&self.tail))
    }
}

impl Format<JsFormatContext> for ArrowChain {
    fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
        let ArrowChain {
            head,
            tail,
            expand_signatures,
            ..
        } = self;

        let head_parent = head.syntax().parent();
        let tail_body = tail.body()?;

        let is_assignment_rhs = self.options.assignment_layout.is_some();

        let is_callee = head_parent
            .as_ref()
            .map_or(false, |parent| is_callee(head.syntax(), parent));

        let body_on_separate_line = !matches!(
            tail_body,
            AnyJsFunctionBody::JsFunctionBody(_)
                | AnyJsFunctionBody::AnyJsExpression(
                    AnyJsExpression::JsObjectExpression(_)
                        | AnyJsExpression::JsSequenceExpression(_)
                )
        );

        let break_before_chain = (is_callee && body_on_separate_line)
            || matches!(
                self.options.assignment_layout,
                Some(AssignmentLikeLayout::ChainTailArrowFunction)
            );

        let format_arrow_signatures = format_with(|f| {
            if is_callee || is_assignment_rhs {
                write!(f, [soft_line_break()])?;
            }

            let join_signatures = format_with(|f| {
                for arrow in self.arrows() {
                    write!(
                        f,
                        [
                            format_leading_comments(arrow.syntax()),
                            format_signature(arrow, self.options.call_arg_layout.is_some())
                        ]
                    )?;

                    // The arrow of the tail is formatted outside of the group to ensure it never
                    // breaks from the body
                    if arrow != tail {
                        write!(
                            f,
                            [
                                space(),
                                arrow.fat_arrow_token().format(),
                                soft_line_break_or_space()
                            ]
                        )?;
                    }
                }

                Ok(())
            });

            write!(
                f,
                [group(&join_signatures).should_expand(*expand_signatures)]
            )
        });

        let format_tail_body_inner = format_with(|f| {
            let format_tail_body = FormatMaybeCachedFunctionBody {
                body: &tail_body,
                mode: self.options.body_cache_mode,
            };

            // Ensure that the parens of sequence expressions end up on their own line if the
            // body breaks
            if matches!(
                tail_body,
                AnyJsFunctionBody::AnyJsExpression(AnyJsExpression::JsSequenceExpression(_))
            ) {
                write!(
                    f,
                    [group(&format_args![
                        text("("),
                        soft_block_indent(&format_tail_body),
                        text(")")
                    ])]
                )?;
            } else {
                write!(f, [format_tail_body])?;
            }

            // Format the trailing comments of all arrow function EXCEPT the first one because
            // the comments of the head get formatted as part of the `FormatJsArrowFunctionExpression` call.
            for arrow in self.arrows().skip(1) {
                write!(f, [format_trailing_comments(arrow.syntax())])?;
            }

            Ok(())
        });

        let format_tail_body = format_with(|f| {
            if body_on_separate_line {
                write!(
                    f,
                    [indent(&format_args![
                        soft_line_break_or_space(),
                        format_tail_body_inner
                    ])]
                )
            } else {
                write!(f, [space(), format_tail_body_inner])
            }
        });

        let group_id = f.group_id("arrow-chain");

        let format_inner = format_once(|f| {
            write!(
                f,
                [
                    group(&indent(&format_arrow_signatures))
                        .with_group_id(Some(group_id))
                        .should_expand(break_before_chain),
                    space(),
                    tail.fat_arrow_token().format(),
                    indent_if_group_breaks(&format_tail_body, group_id),
                ]
            )?;

            if is_callee {
                write!(
                    f,
                    [if_group_breaks(&soft_line_break()).with_group_id(Some(group_id))]
                )?;
            }

            Ok(())
        });

        write!(f, [group(&format_inner)])
    }
}

impl ArrowFunctionLayout {
    /// Determines the layout for the passed arrow function. See [ArrowFunctionLayout] for a description
    /// of the different layouts.
    fn for_arrow(
        arrow: JsArrowFunctionExpression,
        comments: &JsComments,
        options: &FormatJsArrowFunctionExpressionOptions,
    ) -> SyntaxResult<ArrowFunctionLayout> {
        let mut head = None;
        let mut middle = Vec::new();
        let mut current = arrow;
        let mut should_break = false;

        let result = loop {
            match current.body()? {
                AnyJsFunctionBody::AnyJsExpression(AnyJsExpression::JsArrowFunctionExpression(
                    next,
                )) if matches!(
                    options.call_arg_layout,
                    None | Some(GroupedCallArgumentLayout::GroupedLastArgument)
                ) && !comments.is_suppressed(next.syntax()) =>
                {
                    should_break = should_break || should_break_chain(&current)?;

                    if head.is_none() {
                        head = Some(current);
                    } else {
                        middle.push(current);
                    }

                    current = next;
                }
                _ => {
                    break match head {
                        None => ArrowFunctionLayout::Single(current),
                        Some(head) => ArrowFunctionLayout::Chain(ArrowChain {
                            head,
                            middle,
                            tail: current,
                            expand_signatures: should_break,
                            options: *options,
                        }),
                    }
                }
            }
        };

        Ok(result)
    }
}

impl NeedsParentheses for JsArrowFunctionExpression {
    fn needs_parentheses_with_parent(&self, parent: &JsSyntaxNode) -> bool {
        match parent.kind() {
            JsSyntaxKind::TS_AS_EXPRESSION
            | JsSyntaxKind::TS_SATISFIES_EXPRESSION
            | JsSyntaxKind::JS_UNARY_EXPRESSION
            | JsSyntaxKind::JS_AWAIT_EXPRESSION
            | JsSyntaxKind::TS_TYPE_ASSERTION_EXPRESSION => true,

            _ => {
                is_conditional_test(self.syntax(), parent)
                    || update_or_lower_expression_needs_parentheses(self.syntax(), parent)
                    || is_binary_like_left_or_right(self.syntax(), parent)
            }
        }
    }
}

/// Returns `true` if the template contains any new lines inside of its text chunks.
fn template_literal_contains_new_line(template: &JsTemplateExpression) -> bool {
    template.elements().iter().any(|element| match element {
        AnyJsTemplateElement::JsTemplateChunkElement(chunk) => chunk
            .template_chunk_token()
            .map_or(false, |chunk| chunk.text().contains('\n')),
        AnyJsTemplateElement::JsTemplateElement(_) => false,
    })
}

/// Returns `true` for a template that starts on the same line as the previous token and contains a line break.
///
///
/// # Examples
//
/// ```javascript
/// "test" + `
///   some content
/// `;
/// ```
///
/// Returns `true` because the template starts on the same line as the `+` token and its text contains a line break.
///
/// ```javascript
/// "test" + `no line break`
/// ```
///
/// Returns `false` because the template text contains no line break.
///
/// ```javascript
/// "test" +
///     `template
///     with line break`;
/// ```
///
/// Returns `false` because the template isn't on the same line as the '+' token.
pub(crate) fn is_multiline_template_starting_on_same_line(template: &JsTemplateExpression) -> bool {
    let contains_new_line = template_literal_contains_new_line(template);

    let starts_on_same_line = template.syntax().first_token().map_or(false, |token| {
        for piece in token.leading_trivia().pieces() {
            if let Some(comment) = piece.as_comments() {
                if comment.has_newline() {
                    return false;
                }
            } else if piece.is_newline() {
                return false;
            }
        }

        true
    });

    contains_new_line && starts_on_same_line
}

#[cfg(test)]
mod tests {

    use crate::{assert_needs_parentheses, assert_not_needs_parentheses};
    use biome_js_syntax::{JsArrowFunctionExpression, JsFileSource};

    #[test]
    fn needs_parentheses() {
        assert_needs_parentheses!("new (a => test)()`", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => test)()", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => test).member", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => test)[member]", JsArrowFunctionExpression);
        assert_not_needs_parentheses!("object[a => a]", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a) as Function", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a)!", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a)`template`", JsArrowFunctionExpression);
        assert_needs_parentheses!("+(a => a)", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a) && b", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a) instanceof b", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a) in b", JsArrowFunctionExpression);
        assert_needs_parentheses!("(a => a) + b", JsArrowFunctionExpression);
        assert_needs_parentheses!("await (a => a)", JsArrowFunctionExpression);
        assert_needs_parentheses!(
            "<Function>(a => a)",
            JsArrowFunctionExpression,
            JsFileSource::ts()
        );
        assert_needs_parentheses!("(a => a) ? b : c", JsArrowFunctionExpression);
        assert_not_needs_parentheses!("a ? b => b : c", JsArrowFunctionExpression);
        assert_not_needs_parentheses!("a ? b : c => c", JsArrowFunctionExpression);
        assert_needs_parentheses!("class Test extends (a => a) {}", JsArrowFunctionExpression);
    }
}