tsv_ts 0.8.0

TypeScript/JS formatter, type stripper and acorn-compatible parser — part of tsv
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Call-argument and arrow shape predicates shared by the call, new, and chain printers.

use crate::ast::{self, Expression, ExpressionKind, TSType};
use crate::printer::Printer;
use crate::printer::expressions::functions::{arrow_token_end, has_leftmost_arrow_body_parens};
use crate::printer::needs_parens::strip_non_null_wrappers;
use crate::printer::types::helpers::{is_simple_type, unwrap_parenthesized};
use tsv_lang::source_scan::has_newline_after_position;

/// Prettier's `isBooleanTypeCoercion` (`utilities/is-boolean-type-coercion.js`): a plain
/// `Boolean(x)` call — the `!!x` coercion spelled as a call.
///
/// A `shouldNotIndent` term (`key === "arguments" && isBooleanTypeCoercion(parent)`,
/// binaryish.js), so its argument's binary chain takes no continuation indent, exactly as
/// `!!(a || b)`'s operand does. Every conjunct is prettier's, and a wrong answer is a wrong
/// indent in one direction or the other:
///
/// - the callee is the bare identifier `Boolean` — `new Boolean(…)` is a `NewExpression`,
///   not a call, and indents like any other argument position;
/// - **exactly one argument** — `Boolean(a || b, c)` is not a coercion, so its chain
///   indents;
/// - **not optional** — `Boolean?.(a || b)` is read as an ordinary optional call by
///   prettier and indents.
///
/// Asked through [`mark_boolean_coercion_argument`] alone, which is how the answer reaches
/// the argument.
fn is_boolean_type_coercion(call: &ast::CallExpression<'_>, printer: &Printer<'_>) -> bool {
    if call.optional || call.arguments.len() != 1 {
        return false;
    }
    let ExpressionKind::Identifier(id) = &call.callee.kind else {
        return false;
    };
    printer.with_ident_name(id, |s| s == "Boolean")
}

/// Route a `Boolean()` coercion's lone argument to the flat chain layout
/// ([`is_boolean_type_coercion`]), as a [`Printer::mark_flat_chain`] mark on the argument.
///
/// Called ONCE per call by each call-argument entry point — the plain call's
/// `build_call_doc_with_wrapping` and the member chain's `build_call_args_doc_for_chain_impl`
/// (per `conditional_group` candidate, since each re-enters it) — ahead of every layout. A
/// mark rather than a flat builder named at a layout site: the six argument layouts (the
/// plain default list, the plain comment paths, the freeze-aware item builder, the chain's
/// single-argument, force-expanded and comment arms) all bottom out in
/// `Printer::build_arg_expression_doc`, which reads the mark, so a commented or chain-headed
/// coercion answers exactly as the plain default one does. Prettier reaches the same answer
/// from the other side — its member-chain printer reprints a call's arguments through the
/// same `printCallArguments`, where the parent is still the `Boolean(…)` call. A no-op for
/// every other call, `new Boolean(…)` included.
pub(super) fn mark_boolean_coercion_argument(
    printer: &Printer<'_>,
    call: &ast::CallExpression<'_>,
) {
    if is_boolean_type_coercion(call, printer) {
        printer.mark_flat_chain(call.arguments[0]);
    }
}

/// Check if an argument is "hopefully short" enough to stay inline
///
/// Matches Prettier's `isHopefullyShortCallArgument` logic, which is STRICTER
/// than `isSimpleCallArgument`. Key differences:
/// - Call expressions with > 1 argument are NOT short (even if structurally simple)
/// - Binary expressions check both sides with depth=1
/// - An `as` / `satisfies` cast is short only under [`cast_is_hopefully_short`]; an
///   angle-bracket assertion (`<T>x`) is never short
/// - A JSDoc cast is transparent: the question is re-asked of the wrapped expression,
///   so the rules above still fire through it (`is_simple_call_argument` has no such
///   case, which is what keeps the transparency one level deep)
///
/// Used to determine if tail args can stay inline after a function callback.
fn is_hopefully_short_arg(expr: &Expression<'_>) -> bool {
    match &expr.kind {
        // Prettier: if (node.type === "ParenthesizedExpression") recurse into node.expression.
        // A JSDoc cast is prettier's retained `ParenthesizedExpression` — its annotation
        // attaches to the INNER expression, so the wrapper is transparent here and the
        // shortness question is asked of what it wraps. The recursion is one level deep on
        // purpose: `is_simple_call_argument` has no paren case, so a cast nested inside
        // another argument stays opaque, matching prettier.
        ExpressionKind::CommentBoundPair(cast) => is_hopefully_short_arg(cast.inner),

        // Prettier: `isBinaryCastExpression(node) || node.type === "TypeCastExpression"` —
        // the `as` / `satisfies` pair (the Flow spellings have no tsv equivalent).
        ExpressionKind::TSAsExpression(cast) => {
            cast_is_hopefully_short(cast.type_annotation, cast.expression)
        }
        ExpressionKind::TSSatisfiesExpression(cast) => {
            cast_is_hopefully_short(cast.type_annotation, cast.expression)
        }

        // An angle-bracket assertion (`<T>x`) is NEVER short: prettier's
        // `isBinaryCastExpression` does not list `TSTypeAssertion`, so it falls past the cast
        // branch to `isSimpleCallArgument`, which has no case for it either. Stated here
        // rather than left to the fallthrough (which now answers the same) because the
        // asymmetry with the two arms above IS the rule, and it is asked about exactly here:
        // `<T>{}` and `{} as T` are one seed written two ways, and only one of them hugs.
        ExpressionKind::TSTypeAssertion(_) => false,

        // Prettier: if (isCallLikeExpression(node) && getCallArguments(node).length > 1) return false
        _ if CallLikeArguments::of(expr).is_some_and(|arguments| arguments.len() > 1) => false,

        // Prettier: if (isBinaryish(node)) check both sides with depth=1
        // Note: Our AST uses BinaryExpression for logical ops (&&, ||, ??) too
        ExpressionKind::BinaryExpression(bin) => {
            is_simple_call_argument(bin.left, 1) && is_simple_call_argument(bin.right, 1)
        }

        // Prettier: return isRegExpLiteral(node) || isSimpleCallArgument(node)
        // All regex is "hopefully short" regardless of pattern length — the pattern
        // length check in is_simple_call_argument only matters for chain 3+ calls.
        ExpressionKind::RegexLiteral(_) => true,
        _ => is_simple_call_argument(expr, 2),
    }
}

/// Prettier's **cast branch of `isHopefullyShortCallArgument`**: an `as` / `satisfies`
/// cast is short when its target type is simple and the expression it wraps is a simple
/// call argument at depth 1.
///
/// The type is read through two rewrites before [`is_simple_type`] sees it, both
/// prettier's:
///
/// 1. **Array element**, at most twice — `T[]` and `T[][]` are as short as `T`, `T[][][]`
///    is not (prettier stops after two, and so does this).
/// 2. **A lone type argument** of a type reference — `A<B>` is as short as `B`, while
///    `A<B, C>` keeps the reference itself, which is never simple once it carries type
///    arguments. That one-argument boundary is the whole reason `{} as Record<K, V>`
///    breaks all args where `{} as T` hugs.
///
/// Parens are unwrapped at each step because prettier's TS AST has no
/// `TSParenthesizedType` node — `(T)[]` reaches its check already as `T[]`.
fn cast_is_hopefully_short(type_annotation: &TSType<'_>, expression: &Expression<'_>) -> bool {
    let mut ty = unwrap_parenthesized(type_annotation);
    for _ in 0..2 {
        let TSType::Array(array) = ty else { break };
        ty = unwrap_parenthesized(array.element_type);
    }
    if let TSType::TypeReference(reference) = ty
        && let Some(type_arguments) = &reference.type_arguments
        && let [lone] = type_arguments.params
    {
        ty = lone;
    }

    is_simple_type(ty) && is_simple_call_argument(expression, 1)
}

/// The **call-like family** prettier's `isCallLikeExpression` names — a call, a `new`, or a
/// dynamic `import(…)` — read through its `getCallArguments`. An import's "arguments" are its
/// specifier plus the optional options object, which is why this is not simply a slice.
///
/// One spelling of a closed list that both [`is_hopefully_short_arg`] and
/// [`is_simple_call_argument`] ask about. A member present in one of them and missing from
/// the other is exactly the drift this exists to prevent — `import(…)` was missing from both.
#[derive(Clone, Copy)]
enum CallLikeArguments<'a> {
    /// A call's or `new`'s callee and argument list.
    Called {
        callee: &'a Expression<'a>,
        arguments: &'a [&'a Expression<'a>],
    },
    /// A dynamic import's specifier and optional options object. It has **no callee**, and
    /// prettier's simplicity test skips the callee arm for it rather than failing on it.
    Imported {
        source: &'a Expression<'a>,
        options: Option<&'a Expression<'a>>,
    },
}

impl<'a> CallLikeArguments<'a> {
    /// The call-like reading of `expr`, or `None` when it is not call-like.
    fn of(expr: &'a Expression<'a>) -> Option<Self> {
        match &expr.kind {
            ExpressionKind::CallExpression(call) => Some(Self::Called {
                callee: call.callee,
                arguments: call.arguments,
            }),
            ExpressionKind::NewExpression(new_expr) => Some(Self::Called {
                callee: new_expr.callee,
                arguments: new_expr.arguments,
            }),
            ExpressionKind::ImportExpression(import_expr) => Some(Self::Imported {
                source: import_expr.source,
                options: import_expr.options,
            }),
            _ => None,
        }
    }

    /// Prettier's `getCallArguments(node).length`.
    fn len(self) -> usize {
        match self {
            Self::Called { arguments, .. } => arguments.len(),
            Self::Imported { options, .. } => 1 + usize::from(options.is_some()),
        }
    }

    /// The callee whose own simplicity prettier tests, or `None` where it has none to test.
    fn callee(self) -> Option<&'a Expression<'a>> {
        match self {
            Self::Called { callee, .. } => Some(callee),
            Self::Imported { .. } => None,
        }
    }

    /// Whether every argument satisfies `predicate`.
    fn all(self, mut predicate: impl FnMut(&'a Expression<'a>) -> bool) -> bool {
        match self {
            Self::Called { arguments, .. } => arguments.iter().copied().all(predicate),
            Self::Imported { source, options } => {
                predicate(source) && options.is_none_or(predicate)
            }
        }
    }
}

/// Whether a second argument keeps the "expand first arg" hug — prettier's
/// `shouldExpandFirstArg` minus its first-argument half, i.e. its three named refusals plus
/// `isHopefullyShortCallArgument(secondArg) && !couldExpandArg(secondArg)`.
///
/// `leading_gap_start` is where this argument's leading gap opens (the previous argument's
/// printed end) — [`could_expand_collection_arg`] needs it to ask prettier's
/// `hasComment(node)` of a bare collection.
///
/// The `has_comments` closure answers whether a comment OCCUPIES THE PAGE in a range — the
/// on-page axis, since `hasComment` is a pure layout question that an owned annotation
/// satisfies. Callers pass `printer.has_comments_on_page_between`.
pub(super) fn is_short_second_arg_for_expand_first<F>(
    arg: &Expression<'_>,
    leading_gap_start: u32,
    has_comments: F,
) -> bool
where
    F: Fn(u32, u32) -> bool,
{
    match &arg.kind {
        // The three kinds prettier's `shouldExpandFirstArg` names outright. A spread needs
        // no arm of its own: `isSimpleCallArgument` has no case for one either, so it is
        // refused below exactly as prettier refuses it.
        ExpressionKind::ArrowFunctionExpression(_)
        | ExpressionKind::FunctionExpression(_)
        | ExpressionKind::ConditionalExpression(_) => false,
        // `!couldExpandArg(secondArg)`
        _ if could_expand_collection_arg(arg, leading_gap_start, &has_comments) => false,
        // `isHopefullyShortCallArgument(secondArg)`. A truly empty, uncommented `{}` / `[]`
        // reaches this arm and is simple by the vacuous `all` over its members — as it is in
        // prettier, which likewise gives an empty collection no arm of its own.
        _ => is_hopefully_short_arg(arg),
    }
}

/// Prettier's **`couldExpandArg` collection arms**: an object or array that would expand —
/// non-empty, or carrying a comment — asked through the `as` / `satisfies` / `<T>` casts
/// `couldExpandArg` recurses into (never through `!`, which it does not look past).
///
/// **Which comments count depends on the spelling, and that asymmetry is prettier's.**
/// `hasComment` is asked of whatever the recursion landed on, so for a BARE collection a
/// comment written before it attaches to the collection and blocks the hug, while for a
/// cast-wrapped one it attaches to the **cast** — which is why `/* c */ {} as T` still hugs
/// and `/* c */ {}` does not. Hence the range: `leading_gap_start` for a bare collection,
/// the collection's own start for a wrapped one.
///
/// A JSDoc cast is deliberately absent: prettier keeps its parens, so `couldExpandArg` sees
/// an opaque paren node rather than the collection inside and expands-first even for a
/// non-empty one. The transparency a cast does get is in [`is_hopefully_short_arg`] —
/// pinned by `calls/expand_first_jsdoc_cast_second_arg`.
fn could_expand_collection_arg<F>(
    arg: &Expression<'_>,
    leading_gap_start: u32,
    has_comments: &F,
) -> bool
where
    F: Fn(u32, u32) -> bool,
{
    let (collection, comments_from) = match &arg.kind {
        ExpressionKind::ObjectExpression(_) | ExpressionKind::ArrayExpression(_) => {
            (arg, leading_gap_start)
        }
        ExpressionKind::TSAsExpression(_)
        | ExpressionKind::TSSatisfiesExpression(_)
        | ExpressionKind::TSTypeAssertion(_) => unwrap_ts_type_wrappers(arg),
        _ => return false,
    };

    match &collection.kind {
        ExpressionKind::ObjectExpression(obj) => {
            !obj.properties.is_empty() || has_comments(comments_from, collection.span.end)
        }
        ExpressionKind::ArrayExpression(arr) => {
            !arr.elements.is_empty() || has_comments(comments_from, collection.span.end)
        }
        _ => false,
    }
}

/// Whether an arrow's expression body is a call, looking through a trailing `!`.
///
/// Matches prettier's `isCallExpression(stripChainElementWrappers(body))` in
/// `couldExpandArg`: `(x) => fn()` and `(x) => fn()!` are both call bodies, so the
/// arrow hugs the call's open paren rather than breaking at it.
pub(super) fn arrow_body_is_call_through_non_null(body: &Expression<'_>) -> bool {
    matches!(
        strip_non_null_wrappers(body).kind,
        ExpressionKind::CallExpression(_)
    )
}

/// Check if an arrow function body is a ternary expression
///
/// Check if an arrow body is a ternary that needs conditional paren treatment.
///
/// Matches Prettier's `couldExpandArg` logic for conditional expressions:
/// - Flat: `(x) => (x ? y : z)` - parens prevent ambiguity with `<=`
/// - Break: `(x) =>\n  x ? y : z,` - no parens needed, clearly arrow body
///
/// Call expressions, objects, and arrays are handled by other code paths.
pub(super) fn is_ternary_arrow_body(body: &Expression<'_>) -> bool {
    matches!(body.kind, ExpressionKind::ConditionalExpression(_))
}

/// Whether an arrow's expression body breaks after `=>` with the space before it that a
/// `fits` measurement counts ([`super::arg_wrapping`]'s break-body state): prettier's
/// `shouldAddParensIfNotBreak` — a ternary that does not take its own pair
/// ([`has_leftmost_arrow_body_parens`]), printed
/// `" ", group([ifBreak("", "("), indent([softline, body]), …])` — and only while the body
/// stays on the `=>` line, which a comment ending its line refuses
/// ([`arrow_body_has_leading_own_line_comment`]).
pub(super) fn arrow_body_breaks_after_space(
    printer: &Printer<'_>,
    arrow: &ast::ArrowFunctionExpression<'_>,
    body: &Expression<'_>,
) -> bool {
    is_ternary_arrow_body(body)
        && !has_leftmost_arrow_body_parens(body)
        && !arrow_body_has_leading_own_line_comment(printer, arrow, body)
}

/// Whether a comment in an arrow's `=>`→body gap ends its line — prettier's
/// `hasLeadingOwnLineComment(text, body)` (a leading comment with a newline after it), the
/// conjunct of `shouldPutBodyOnSameLine` that sends the body to `indent([line, body])`, with
/// no space after `=>` (`(a) => /* c */⏎a ? b : c`). The break-body states measure their
/// `=>` line by it ([`arrow_body_breaks_after_space`] and the lone ternary ladder).
pub(super) fn arrow_body_has_leading_own_line_comment(
    printer: &Printer<'_>,
    arrow: &ast::ArrowFunctionExpression<'_>,
    body: &Expression<'_>,
) -> bool {
    printer
        .comments_in_source_between(arrow_token_end(arrow), body.span().start)
        .any(|c| has_newline_after_position(printer.source, c.span.end))
}

/// Whether an expression is an object literal with properties — the narrow
/// `couldExpandArg` an `import(…)`'s **options** argument asks for its expand-last states.
/// Deliberately not [`could_expand_collection_arg`]: that one answers the expand-FIRST
/// question, which looks through casts and counts comments; this one is a plain shape test
/// on the last argument.
pub(super) fn is_expandable_object(expr: &Expression<'_>) -> bool {
    matches!(&expr.kind, ExpressionKind::ObjectExpression(obj) if !obj.properties.is_empty())
}

/// Check if the last argument is an array or object expression (unwrapping type assertions)
#[inline]
pub(super) fn last_arg_is_array_or_object(
    arguments: &[&Expression<'_>],
    printer: &Printer<'_>,
) -> bool {
    arguments
        .last()
        .is_some_and(|arg| is_array_or_object_unwrapped(arg, printer))
}

/// The container half of prettier's `couldExpandArg`: an object or array literal — read
/// through the TS casts — that is NON-EMPTY, or empty but carrying a comment
/// (`arg.properties.length > 0 || hasComment(arg)`, and the array twin).
///
/// The emptiness clause is load-bearing under a cast: an empty `{}` / `[]` has nothing to
/// expand, so a hug state of it renders as its flat state and falls through — but
/// `<T[]>[]` puts the cast's own `<…>` group inside the hug, and a walk that reaches it
/// selects the hug and breaks the TYPE (`fn(cb, <⏎\tT[]⏎>[])`) where prettier, refusing the
/// expansion, breaks every argument out (`calls/empty_container_cast_last_arg_long`). The
/// comment clause reads **on page** from where a leading comment starts attaching to the
/// container ([`unwrap_ts_type_wrappers`]) through its end: a dangling comment makes an
/// empty literal print multi-line, and a comment after a `<T>` assertion's `>` is the
/// literal's own leading one — which is why `<T[]>/* c */ []` expands where `<T[]>[]` does
/// not.
///
/// What leads the whole ARGUMENT is deliberately not read here, the one axis on which this
/// stops short of `hasComment`. It can only matter for an EMPTY bare container, and an empty
/// one has nothing to break: its hug state renders as its flat state, so every ladder this
/// feeds lands on the same bytes whether the clause admits it or not. The expand-FIRST twin,
/// where the same comment does decide, takes that gap as a parameter
/// ([`could_expand_collection_arg`]).
pub(super) fn is_array_or_object_unwrapped(expr: &Expression<'_>, printer: &Printer<'_>) -> bool {
    let (inner, leading_from) = unwrap_ts_type_wrappers(expr);
    let non_empty = match &inner.kind {
        ExpressionKind::ArrayExpression(arr) => !arr.elements.is_empty(),
        ExpressionKind::ObjectExpression(obj) => !obj.properties.is_empty(),
        _ => return false,
    };
    non_empty || printer.has_comments_on_page_between(leading_from, inner.span().end)
}

/// Unwrap the TypeScript cast wrappers (`as`, `satisfies`, `<T>`) to get the inner
/// expression, together with the position from which a LEADING comment attaches to that
/// inner expression rather than to something around it.
///
/// Mirrors Prettier's `couldExpandArg`, which looks through `isBinaryCastExpression`
/// (`as`/`satisfies`) and `TSTypeAssertion` (`<T>x`) but NOT `TSNonNullExpression`: a
/// `{...}!` / `[...]!` argument is not treated as an expandable object/array, so it does
/// not hug the call parens.
///
/// **The window is the half `hasComment` reads and a span cannot give.** `couldExpandArg`
/// recurses and only then asks `hasComment` of whatever it landed on, so the question is
/// which comments attach THERE. A `<T>` assertion is the one wrapper that puts source AHEAD
/// of what it wraps, so a comment written after its `>` is the inner node's own leading
/// comment: `<T[]>/* c */ []` satisfies the clause where `<T[]>[]` does not. Every other
/// spelling starts where the inner node does — under `as` / `satisfies` the inner comes
/// FIRST, so a comment ahead of it precedes the whole CAST and attaches there
/// (`/* c */ [] as T` does not expand). Nested assertions take the innermost `>`.
///
/// What leads the whole ARGUMENT is the caller's question, since only the caller knows where
/// that gap opens — see [`could_expand_collection_arg`] and
/// [`is_array_or_object_unwrapped`], which answer it differently and say why.
fn unwrap_ts_type_wrappers<'a>(mut expr: &'a Expression<'a>) -> (&'a Expression<'a>, u32) {
    let mut leading_from = expr.span().start;
    loop {
        expr = match &expr.kind {
            ExpressionKind::TSAsExpression(cast) => cast.expression,
            ExpressionKind::TSSatisfiesExpression(cast) => cast.expression,
            ExpressionKind::TSTypeAssertion(cast) => {
                leading_from = cast.type_annotation.span().end;
                cast.expression
            }
            _ => return (expr, leading_from),
        };
    }
}

/// Check if an expression is a function with a block body.
///
/// Matches arrow functions with block bodies (`() => { ... }`) and
/// function expressions (`function() { ... }`). These contain hardlines.
#[inline]
pub(super) fn is_block_function(expr: &Expression<'_>) -> bool {
    matches!(
        &expr.kind,
        ExpressionKind::ArrowFunctionExpression(arrow)
            if matches!(arrow.body, ast::ArrowFunctionBody::BlockStatement(_))
    ) || matches!(expr.kind, ExpressionKind::FunctionExpression(_))
}

/// Prettier's **`isReactHookCallWithDepsArray`** (`print/call-arguments.js`): a
/// zero-parameter block-body arrow immediately followed by an array literal —
/// `useEffect(() => {…}, [a, b])`, or the three-argument
/// `useImperativeHandle(ref, () => {…}, [a, b])` whose first argument is a plain
/// identifier.
///
/// The shape is the whole rule: prettier reads **no callee name**, so any call written this
/// way takes the layout, `new` and member-chain calls included (one `printCallArguments`
/// serves them all). It is also the FIRST thing that printer asks, above `anyArgEmptyLine`
/// and every specialized layout — which is why an author blank line between the callback and
/// the deps array is collapsed rather than preserved here.
///
/// The `!args.some(hasComment)` conjunct asks about comments **attached to an argument**,
/// not comments anywhere inside one: a comment in the callback's body or between the deps
/// array's own brackets leaves the layout alone, while one leading or trailing an argument
/// refuses it. The caller supplies that answer through `arg_gap_has_comment`, which it asks
/// of the gaps around the arguments — `(`→first, each inter-argument gap, last→`)` — on the
/// ON-PAGE axis, since an owned annotation glued to an argument is a comment prettier's
/// `hasComment` sees.
pub(super) fn is_react_hook_call_with_deps_array<F>(
    args: &[&Expression<'_>],
    arg_gap_has_comment: F,
) -> bool
where
    F: Fn() -> bool,
{
    let base = match args.len() {
        2 => 0,
        3 if matches!(args[0].kind, ExpressionKind::Identifier(_)) => 1,
        _ => return false,
    };

    is_hook_callback_with_deps(args[base], args[base + 1]) && !arg_gap_has_comment()
}

/// The shape half of [`is_react_hook_call_with_deps_array`] — prettier's
/// `isValidHookCallbackAndDepsFormat` minus its comment conjunct: a zero-parameter
/// block-body arrow followed by an array literal.
///
/// Split out for `import(…)`, whose AST carries `source` + `options` rather than an argument
/// slice; prettier reaches it through the same `printCallArguments` (`ImportExpression` is in
/// that printer's header list), so the shape question must have one answer for both.
pub(super) fn is_hook_callback_with_deps(callback: &Expression<'_>, deps: &Expression<'_>) -> bool {
    matches!(
        &callback.kind,
        ExpressionKind::ArrowFunctionExpression(arrow)
            if arrow.params.is_empty()
                && matches!(arrow.body, ast::ArrowFunctionBody::BlockStatement(_))
    ) && matches!(deps.kind, ExpressionKind::ArrayExpression(_))
}

/// Check if an expression is a "simple" call argument (Prettier's `isSimpleCallArgument`)
///
/// Uses depth-limited recursion (typically depth=2) to prevent checking arbitrarily
/// deep structures. Returns false at depth 0.
///
/// Simple cases:
/// - Literals, identifiers, `this`, `super`
/// - Template literals without newlines (with simple expressions)
/// - Objects with simple property values
/// - Arrays with simple elements
/// - Call-like nodes ([`CallLikeArguments`]) with a simple callee and few simple arguments
/// - Member expressions with simple object and property
/// - Update expressions, and unary ones over `!` / `-` / `+` / `~`
///
/// Everything else is NOT simple — notably a TS cast, a meta property, and `typeof` / `void` /
/// `delete`, each of which prettier leaves to its own closing `return false`.
///
/// Reference: prettier's `isSimpleCallArgument` (`utilities/is-simple-call-argument.js`)
pub(crate) fn is_simple_call_argument(expr: &Expression<'_>, depth: usize) -> bool {
    if depth == 0 {
        return false;
    }

    // Prettier opens with `node = stripChainElementWrappers(node)` — the chain-element
    // wrappers ONLY, at the same depth. A cast (`as` / `satisfies` / `<T>`) is deliberately
    // not looked through: prettier has no case for one, so it falls to the closing
    // `_ => false`. That refusal is load-bearing at both callers — a cast argument is what
    // force-expands a 3+ call member chain
    // (`call_has_complex_args`) and what refuses the expand-first hug through
    // `is_hopefully_short_arg`.
    //
    // The spine — a call-like node's callee, a member's object — is walked in a loop, not a
    // recursion: both stay at THIS depth, so a chain is as long as the spine limit lets it be,
    // and a frame per link is what the stack contract prices. Each link's own conditions are
    // pure, so asking them before the rest of the spine answers what the recursion answered.
    let mut expr = expr;
    let expr = loop {
        expr = strip_non_null_wrappers(expr);

        // Call-like nodes: the callee must be simple at THIS depth, the arguments must fit
        // within the remaining depth, and each must be simple one level shallower. Prettier
        // skips the callee arm for a dynamic `import(…)`
        // (`node.type === "ImportExpression" || isSimpleCallArgument(node.callee, depth)`)
        // rather than failing on it — it has no callee. Answered ahead of the match because a
        // match guard cannot bind; the family is disjoint from every arm below.
        if let Some(arguments) = CallLikeArguments::of(expr) {
            if !(arguments.len() <= depth
                && arguments.all(|argument| is_simple_call_argument(argument, depth - 1)))
            {
                return false;
            }
            match arguments.callee() {
                Some(callee) => {
                    expr = callee;
                    continue;
                }
                None => return true,
            }
        }

        // Member expressions: object must be simple, property is simple if not computed
        // (or if computed with a simple expression)
        if let ExpressionKind::MemberExpression(member) = &expr.kind {
            // Non-computed properties (identifiers) are always simple; computed properties
            // must have a simple expression
            if member.computed && !is_simple_call_argument(member.property, depth) {
                return false;
            }
            expr = member.object;
            continue;
        }
        break expr;
    };

    match &expr.kind {
        // Simple literals are always simple (Prettier: isLiteral)
        ExpressionKind::Literal(_) => true,

        // Regex: simple only if pattern is short (Prettier: getStringWidth(pattern) <= 5).
        // Uses the precomputed pattern width so this stays source-free.
        ExpressionKind::RegexLiteral(regex) => usize::from(regex.pattern_width) <= 5,

        // Single-word types are simple (Prettier: `isSingleWordType`). A meta property
        // (`import.meta`, `new.target`) is deliberately NOT one — prettier lists neither it
        // nor any `Meta*` node in `isSingleWordType` or `isLiteral`, so it falls to the
        // closing `_ => false`. `PrivateIdentifier` is on prettier's list but unreachable
        // here: a bare `#x` is only ever the left side of `#x in o`, and `a.#b` is answered
        // by the member arm's non-computed short-circuit before it asks.
        ExpressionKind::Identifier(_)
        | ExpressionKind::ThisExpression(_)
        | ExpressionKind::Super(_) => true,

        // Template literals: simple if no newlines and expressions are simple
        ExpressionKind::TemplateLiteral(template) => {
            // Check both raw and cooked for newlines (Prettier checks both).
            // `has_newline` covers the raw side (and the no-escape `Verbatim`
            // cooked, which equals raw); only a `Decoded` cooked can introduce a
            // newline raw lacks (a `\n` escape) — and it owns its string, so this
            // stays source-free.
            let has_newline = template.quasis.iter().any(|q| {
                q.has_newline
                    || matches!(&q.cooked, ast::TemplateCooked::Decoded(c) if c.contains('\n'))
            });
            if has_newline {
                return false;
            }
            // Check all expressions are simple at reduced depth
            template
                .expressions
                .iter()
                .all(|e| is_simple_call_argument(e, depth - 1))
        }

        // Objects: simple if all properties are non-computed and values are simple
        ExpressionKind::ObjectExpression(obj) => obj.properties.iter().all(|prop| match prop {
            ast::ObjectProperty::Property(p) => {
                !p.computed && (p.shorthand || is_simple_call_argument(p.value, depth - 1))
            }
            // Spread properties are not simple
            ast::ObjectProperty::SpreadElement(_) => false,
        }),

        // Arrays: simple if all elements are simple (None = hole, which is simple)
        ExpressionKind::ArrayExpression(arr) => arr.elements.iter().all(|elem| {
            elem.as_ref()
                .is_none_or(|e| is_simple_call_argument(e, depth - 1))
        }),

        // Unary expressions with simple operands. Prettier's
        // `simpleCallArgumentUnaryOperators` is exactly these four — `typeof`, `void` and
        // `delete` are all absent, so a `typeof x` argument is NOT simple.
        ExpressionKind::UnaryExpression(unary) => {
            matches!(
                unary.operator,
                ast::UnaryOperator::Minus
                    | ast::UnaryOperator::Plus
                    | ast::UnaryOperator::Bang
                    | ast::UnaryOperator::Tilde
            ) && is_simple_call_argument(unary.argument, depth)
        }

        // Update expressions (++x, x++)
        ExpressionKind::UpdateExpression(update) => is_simple_call_argument(update.argument, depth),

        // Everything else is not simple: arrow functions, function expressions, and
        // spread elements (matches prettier — no SpreadElement case), etc.
        _ => false,
    }
}

/// Whether a LONE call argument's own doc renders with its parameter list FLAT inside the
/// hug states — prettier's `printFunction` `shouldExpandParameters` (`print/function.js`),
/// which under `expandLastArg` hands `printFunctionParameters` a `removeLines`'d list so
/// neither hug state can break it.
///
/// Only a `FunctionExpression` can answer yes — an arrow prints through
/// `printArrowFunction`, which has no such rule — and only when every parameter is a plain
/// `Identifier` with no type annotation. A default value, a destructuring pattern, a rest
/// element or a type annotation each leave the list breakable, so the function hugs and its
/// parameters break inside it; an all-plain-identifier list cannot break there, so the whole
/// argument drops to its own line instead.
///
/// ⚠️ Prettier's full condition is "the parent call has more than one argument, OR every
/// parameter is a plain identifier". This spells the one-argument half, the only half a lone
/// argument can be asked about. The other half of its gate is `isCallExpression(parent)`,
/// which a `new` is not — so the `new` printer passes `false` to
/// [`super::arg_wrapping::ArgOpener::lone_hug_ladder`] rather than asking this.
pub(super) fn lone_arg_params_render_flat(arg: &Expression<'_>) -> bool {
    matches!(&arg.kind, ExpressionKind::FunctionExpression(func) if func.params.iter().all(|param| {
        matches!(&param.kind, ExpressionKind::Identifier(id) if id.type_annotation().is_none())
    }))
}

/// Check if arguments form a "function composition" pattern that forces expansion.
///
/// Matches Prettier's `isFunctionCompositionArgs` logic:
/// - 2+ arguments
/// - Either: 2+ function/arrow arguments, OR
///   any argument is a call expression containing a function/arrow argument
///
/// This triggers `allArgsBrokenOut()` in Prettier to expand all arguments.
pub(super) fn is_function_composition_args(arguments: &[&Expression<'_>]) -> bool {
    if arguments.len() <= 1 {
        return false;
    }

    let mut function_count = 0;

    for arg in arguments {
        if matches!(
            arg.kind,
            ExpressionKind::ArrowFunctionExpression(_) | ExpressionKind::FunctionExpression(_)
        ) {
            function_count += 1;
            if function_count > 1 {
                return true;
            }
        } else if let ExpressionKind::CallExpression(call) = &arg.kind {
            // Check if this call has any function/arrow arguments
            if call.arguments.iter().any(|child_arg| {
                matches!(
                    child_arg.kind,
                    ExpressionKind::ArrowFunctionExpression(_)
                        | ExpressionKind::FunctionExpression(_)
                )
            }) {
                return true;
            }
        }
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use bumpalo::Bump;

    /// Parse a bare expression to its internal AST node (spans index into `src`),
    /// allocated in the caller-supplied `arena`.
    fn parse_expr<'a>(arena: &'a Bump, src: &str) -> &'a Expression<'a> {
        crate::__private::parse_expression_with_comments(src, 0, 0, arena, "end of input", |_| {
            Ok(())
        })
        .expect("expression should parse")
        .0
    }

    /// Parse a call expression and return its argument list.
    fn args_of<'a>(arena: &'a Bump, src: &str) -> &'a [&'a Expression<'a>] {
        match parse_expr(arena, src) {
            Expression {
                kind: ExpressionKind::CallExpression(call),
                ..
            } => call.arguments,
            other => panic!("expected a call expression, got: {other:?}"),
        }
    }

    /// The argument shapes whose parameter list stays breakable inside the hug — everything
    /// but a function expression whose parameters are all plain, unannotated identifiers.
    #[test]
    fn lone_arg_params_render_flat_only_for_plain_identifiers() {
        let arena = Bump::new();
        let flat = |src| lone_arg_params_render_flat(parse_expr(&arena, src));

        // Plain identifiers — including none at all.
        assert!(flat("(function () {})"));
        assert!(flat("(function (a, b) {})"));

        // Anything the list can break around leaves it breakable.
        assert!(!flat("(function (a: T) {})"));
        assert!(!flat("(function (a = 1) {})"));
        assert!(!flat("(function ({ a }) {})"));
        assert!(!flat("(function ([a]) {})"));
        assert!(!flat("(function (...a) {})"));
        // One non-plain parameter is enough.
        assert!(!flat("(function (a, b: T, c) {})"));

        // Only a function expression answers yes at all — an arrow prints through
        // `printArrowFunction`, which has no such rule.
        assert!(!flat("((a, b) => {})"));
        assert!(!flat("({ a: b })"));
        assert!(!flat("(class {})"));
    }

    #[test]
    fn simple_call_argument_depth_and_shape() {
        let arena = Bump::new();
        // Depth 0 is always "not simple".
        assert!(!is_simple_call_argument(parse_expr(&arena, "x"), 0));
        // Literals / identifiers are simple at any positive depth.
        assert!(is_simple_call_argument(parse_expr(&arena, "42"), 1));
        assert!(is_simple_call_argument(parse_expr(&arena, "foo"), 1));
        // Regex is simple only if the pattern width is <= 5.
        assert!(is_simple_call_argument(parse_expr(&arena, "/abcde/"), 2));
        assert!(!is_simple_call_argument(parse_expr(&arena, "/abcdef/"), 2));
        // A call's args must fit within the remaining depth: `f(a)` needs depth >= 2.
        assert!(!is_simple_call_argument(parse_expr(&arena, "f(a)"), 1));
        assert!(is_simple_call_argument(parse_expr(&arena, "f(a)"), 2));
        // Spread elements are never simple.
        assert!(!is_simple_call_argument(parse_expr(&arena, "[...x]"), 2));
    }

    #[test]
    fn simple_call_argument_looks_through_only_the_chain_wrappers() {
        let arena = Bump::new();
        let simple = |src: &str| is_simple_call_argument(parse_expr(&arena, src), 2);
        // `!` is prettier's `stripChainElementWrappers`, so `x!` is as simple as `x`.
        assert!(simple("x!"));
        // A TS cast is not looked through — prettier has no case for one.
        assert!(!simple("x as T"));
        assert!(!simple("x satisfies T"));
        assert!(!simple("<T>x"));
        // Only four unary operators are simple; `typeof` / `void` / `delete` are not.
        assert!(simple("-x"));
        assert!(simple("!x"));
        assert!(!simple("typeof x"));
        assert!(!simple("void x"));
        assert!(!simple("delete x.y"));
        // A dynamic import is call-like: its specifier plus optional options object are its
        // arguments, and it has no callee to test.
        assert!(simple("import('a')"));
        assert!(simple("import(a, b)"));
        // …and the argument count is still held to the depth.
        assert!(!is_simple_call_argument(
            parse_expr(&arena, "import(a, b)"),
            1
        ));
    }

    #[test]
    fn hopefully_short_reads_a_cast_through_its_type() {
        let arena = Bump::new();
        let short = |src: &str| is_hopefully_short_arg(parse_expr(&arena, src));
        // A bare type reference is simple, so the cast-wrapped seed stays short.
        assert!(short("{} as T"));
        assert!(short("{} satisfies T"));
        // A lone type argument is descended into; two of them are not.
        assert!(short("{} as A<B>"));
        assert!(!short("{} as A<B, C>"));
        // An array element type is unwrapped, at most twice.
        assert!(short("{} as T[]"));
        assert!(short("{} as T[][]"));
        assert!(!short("{} as T[][][]"));
        // The wrapped expression must itself be simple at depth 1.
        assert!(!short("fn(a) as T"));
        assert!(!short("({} as A) as B"));
        // An angle-bracket assertion is never short, whatever its type says.
        assert!(!short("<T>{}"));
        // A call-like argument with more than one argument is never short.
        assert!(short("fn(a)"));
        assert!(!short("fn(a, b)"));
        assert!(short("import('a')"));
        assert!(!short("import('a', b)"));
    }

    #[test]
    fn function_composition_args_detection() {
        let arena = Bump::new();
        // Two arrow args ⇒ composition.
        assert!(is_function_composition_args(args_of(
            &arena,
            "compose(a => a, b => b)"
        )));
        // A single arg is never composition.
        assert!(!is_function_composition_args(args_of(&arena, "f(a => a)")));
        // A call argument that itself wraps a callback ⇒ composition.
        assert!(is_function_composition_args(args_of(
            &arena,
            "compose(x, g(() => {}))"
        )));
        // Two non-function args ⇒ not composition.
        assert!(!is_function_composition_args(args_of(&arena, "f(a, b)")));
    }

    #[test]
    fn react_hook_deps_array_shape() {
        let arena = Bump::new();
        // The gap-comment conjunct is the caller's; these cases isolate the shape.
        let shape = |src: &str| is_react_hook_call_with_deps_array(args_of(&arena, src), || false);

        // Two-argument form: zero-parameter block arrow, then an array literal.
        assert!(shape("useEffect(() => {}, [a, b])"));
        // The callee name is never read — any call written in the shape takes the layout.
        assert!(shape("fn(() => {}, [a])"));
        // An empty deps array still counts; so does an `async` callback.
        assert!(shape("fn(() => {}, [])"));
        assert!(shape("fn(async () => {}, [a])"));

        // A parameter on the callback disqualifies it…
        assert!(!shape("fn((x) => {}, [a])"));
        // …as does an expression body, or a non-array second argument.
        assert!(!shape("fn(() => a, [b])"));
        assert!(!shape("fn(() => {}, {})"));
        assert!(!shape("fn(() => {}, a)"));
        // A spread is not the callback.
        assert!(!shape("fn(...[() => {}], [a])"));

        // Three-argument form: a plain IDENTIFIER first, then the same pair.
        assert!(shape("useImperativeHandle(ref, () => {}, [a])"));
        // Any other first argument refuses it — prettier tests `type === "Identifier"`.
        assert!(!shape("useImperativeHandle(o.p, () => {}, [a])"));
        assert!(!shape("useImperativeHandle(1, () => {}, [a])"));

        // One or four arguments are not the shape at all.
        assert!(!shape("fn(() => {})"));
        assert!(!shape("fn(() => {}, [a], b)"));

        // A comment attached to an argument refuses it, whatever the shape says.
        assert!(!is_react_hook_call_with_deps_array(
            args_of(&arena, "fn(() => {}, [a])"),
            || true
        ));
    }
}