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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
// Main call expression formatting logic
//
// Contains the primary `build_call_doc_with_wrapping` function that handles
// all the special cases for call expression formatting.

use super::super::{ParenContext, Printer, SecondTypeArgs};
use super::CalleeGap;
use super::arg_comments::{
    PartitionedComments, any_arg_empty_line, first_arg_has_any_comments,
    has_inter_argument_comments, has_trailing_comments_on_args,
    should_force_expansion_for_comments,
};
use super::arg_predicates::{
    arrow_body_is_call_through_non_null, is_array_or_object_unwrapped,
    is_function_composition_args, is_ternary_arrow_body, lone_arg_params_render_flat,
    mark_boolean_coercion_argument,
};
use super::arg_wrapping::{
    ArgOpener, append_type_args_with_gap_comments, arg_needs_soft_wrap,
    arrow_hug_refused_by_comments, build_arrow_call_body_states,
    build_arrow_gap_break_single_arg_doc, build_arrow_hug_printed_doc, build_arrow_sig_doc,
    build_call_args_expanded, build_call_args_with_blank_lines, build_empty_args_doc,
    build_expand_first_arg_doc, build_joined_argument_doc, build_printed_argument_doc,
    build_single_arrow_hug_doc, build_single_container_arg_doc, build_ternary_arrow_hug_ladder,
    could_expand_arrow_chain, first_arg_signature_refuses_expand_first, last_arg_arrow_gap_break,
    prebuild_expand_last_break_body, should_expand_first_arg, try_hook_deps_args_doc,
    try_hug_multiline_template_arg, wrap_call_with_soft_breaks, wrap_call_with_will_break_guard,
};
use super::expand_last::{ArgOwner, try_expand_last_arg};
use super::module_paths::{get_module_path_chain_break, is_module_path_no_break};
use super::test_patterns::{build_test_callee_flat_doc, is_test_call, test_call_flat_gaps_clear};
use crate::ast;
use crate::printer::comments::ShareSite;
use crate::printer::expressions::functions::{
    arrow_signature_refuses_hug, callback_signature_refuses_hug,
};
use crate::printer::ignore::FrozenOperandPair;
use smallvec::smallvec;
use tsv_lang::Span;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::arena::DocId;

/// Print a call expression: `foo()`, `obj.method(arg1, arg2)`
///
/// For method chains like `arr.filter().map()`, wraps with leading `.`:
/// ```javascript
/// arr
///     .filter(...)
///     .map(...)
/// ```
///
/// For standalone calls and simple method calls, wraps args when they exceed print_width:
/// ```javascript
/// fn(
///     arg1,
///     arg2,
/// )
/// assert.deepStrictEqual(
///     longArg1,
///     [1, 2],
/// )
/// ```
///
/// Built as a HEAD and an argument LIST, joined here, because the callee→`(` gap's pre-paren
/// half ([`super::CalleeGap::paren_split`]) hangs the whole list under its run — an
/// `indent(…)` has to wrap the list, so the list must exist as a doc of its own. (The `?.`
/// split needs no such thing: its tail is one token the head simply concatenates.) On the
/// unsplit path — every call with no `//` in that gap — the head is handed straight through
/// and the shape is unchanged.
pub(super) fn build_call_doc_with_wrapping(
    printer: &Printer<'_>,
    call: &ast::CallExpression<'_>,
    span: Span,
) -> DocId {
    let d = printer.d();
    let head = build_call_head(printer, call, span);
    let Some((split_start, paren)) = head.gap.paren_split else {
        return build_call_args_doc(printer, call, span, head.doc, &head);
    };
    let args = build_call_args_doc(printer, call, span, d.empty(), &head);
    super::hang_args_under_split(printer, head.doc, (split_start, paren), args)
}

/// A call's **head**: everything printed before the argument list's `(` — the callee's own
/// doc, the required pair it may print, the `?.` a split gap puts behind it, and the type
/// arguments — plus the two decisions the argument side re-reads.
struct CallHead {
    /// The head's doc.
    doc: DocId,
    /// The one [`super::CalleeGap`] derivation both halves read.
    gap: CalleeGap,
    /// The test-call decision — asked ONCE (see below) and re-read by the layout and by the
    /// argument side's blank-line question.
    test_call: TestCall,
    /// The argument list opens with `?.(` because the `?.` fused into it.
    fuse_optional: bool,
    /// This call is the callee of a call taking fewer arguments, so its default tail prints
    /// the list without a group ([`Printer::long_curried_target`]).
    ungroup_args: bool,
}

fn build_call_head(printer: &Printer<'_>, call: &ast::CallExpression<'_>, span: Span) -> CallHead {
    let d = printer.d();

    // Read before the callee is built, which re-arms the target for the callee's own span.
    let ungroup_args = printer.long_curried_target.get() == Some(span);

    // Test function calls (`it`, `test.only`, `describe`, …) stay on one line even past
    // the print width — unless an argument gap holds a comment the flat layout has no
    // emitter for, in which case the call expands like any other. Asked ONCE, here, and
    // re-read by the layout branch below: the flat CALLEE and the flat LAYOUT are two
    // halves of one decision, and a second `test_call_flat_layout_applies` call is a
    // second question that can answer differently. Spelled as its two halves because the
    // argument side reads the `is_test_call` half alone too.
    let test_call = if !is_test_call(call, printer) {
        TestCall::No
    } else if test_call_flat_gaps_clear(call, span, printer) {
        TestCall::Flat
    } else {
        TestCall::Declined
    };
    let test_call_flat = test_call == TestCall::Flat;

    // Two callee positions print a required pair that keeps BOTH its gaps inside it: an
    // IIFE (`paren_pair_keeps_leading_run` — prettier's `printCommentsForFunction` prints
    // a function/arrow callee's leading AND trailing comments within the parens) and a
    // sealed optional chain, where the pair is what stops the chain. ⚠️ ONE variable
    // answers it, because the two consumers below — the pair's own doc and the window
    // that opens past its `)` — must agree: a `trailing_gap` the doc does not emit is a
    // DROPPED comment, and the reverse is a double-print. The pair has to be the author's
    // own for a trailing gap to exist at all: `(fn /* t */)()` writes it around the
    // callee, `(/* t */ fn())` around the whole call, where the comment belongs to the
    // call and not to any pair printed here.
    //
    // The REQUIRED pair a callee prints when it takes one, as a shape — and with it the
    // builder its operand takes. Asked BEFORE the body is built, because a cast and a
    // binaryish callee each want an operand doc `build_expression_doc` does not give
    // ([`super::CalleeParens`]); `None` is the callee that needs no pair at all.
    let callee_parens = super::CalleeParens::of(
        printer,
        call.callee,
        ParenContext::Callee,
        call.type_arguments
            .as_ref()
            .map(|_| SecondTypeArgs::Expression),
    );
    // The pair's facts and every window that opens past its `)`, off ONE derivation
    // ([`super::CalleeGap`]).
    let gap = super::callee_gap(printer, call, span);
    let CalleeGap {
        owned_pair,
        trailing_gap,
        start: callee_gap_start,
        optional,
        paren_split: _,
    } = gap;

    // The flat callee is a break-free doc built straight from the chain parts, so a long
    // `it.skip` never breaks at its `.`. It replaces ONLY the callee's own doc, which is why
    // it is built HERE rather than in the layout branch: everything the general path wraps
    // around a callee — the removed-paren comments (`(/* c */ it)(…)`), the type arguments
    // and the gap before them (`it/* c */ <T>(…)`) — applies to it below. A branch that
    // returns a doc assembled from its own callee skips every one of those, `<T>` included.
    // The CALLEE's erased-paren freeze, over the region the `prepend_removed_paren_comments`
    // below emits (`(⏎// prettier-ignore⏎f⏎)(1)`) — the bare-callee twin of the chain base's
    // (`Printer::build_left_spine_operand_doc`).
    //
    // ⚠️ Only where the position prints NO pair of its own. A callee that takes a required
    // pair has that pair emitted around a doc the printer BUILDS (`CalleeParens`, the owned
    // pair), and a verbatim slice cannot be reached into — frozen there, a decorated class
    // expression came out as `@dec class {}()`, which does not parse. The coarser claim one
    // level out still honors the directive: it leads the whole statement, and the statement
    // freeze keeps the author's pair inside its slice.
    let callee_freezes = callee_parens.is_none() && !owned_pair;
    // A callee that is a call taking more arguments than this one prints its list without a
    // group (prettier's `isLongCurriedCallExpression`): armed for the callee build alone.
    let outer_target = super::callee_is_long_curried(call).then(|| {
        printer
            .long_curried_target
            .replace(Some(call.callee.span()))
    });
    // A comment in a shell below a pair the callee's left spine prints leads the whole
    // call (`Printer::left_spine_run_claim`); an owned pair keeps its run inside it. Armed
    // over the callee's build, where the sites below decline the region, and again over
    // this site's own prepend, which prints it.
    let claim = (!owned_pair)
        .then(|| {
            printer.left_spine_run_claim(span, span.start, call.callee, || callee_parens.is_some())
        })
        .flatten();
    let callee_doc = printer.with_left_spine_claim(claim, || {
        printer.build_left_spine_operand_doc_if(
            callee_freezes,
            span.start,
            call.callee,
            FrozenOperandPair::position(ParenContext::Callee),
            || {
                test_call_flat
                    .then(|| build_test_callee_flat_doc(call.callee, printer))
                    .flatten()
                    .unwrap_or_else(|| {
                        callee_parens.as_ref().map_or_else(
                            || printer.build_expression_doc(call.callee),
                            |parens| {
                                parens.build_body_doc(
                                    printer,
                                    printer.pair_gaps_are_comment_free(
                                        (span.start, call.callee.span().start),
                                        trailing_gap,
                                    ),
                                )
                            },
                        )
                    })
            },
        )
    });
    if let Some(outer) = outer_target {
        printer.long_curried_target.set(outer);
    }

    let callee = if owned_pair {
        printer.build_owned_required_pair_doc(
            (span.start, call.callee.span().start),
            trailing_gap,
            callee_doc,
            ")",
        )
    } else {
        // Wrap callee in parens if needed (e.g., ternary: `(a ? b : c)()`)
        // This must happen BEFORE adding removed-paren comments so comments stay outside
        let callee_doc = callee_parens
            .as_ref()
            .map_or(callee_doc, |parens| parens.build_doc(printer, callee_doc));
        // Check for comments between removed parentheses and callee
        // e.g., (/* comment */ foo)() has span.start at '(' and callee.span.start at 'foo'
        // The comment is in the range [span.start, callee.span.start) and needs to be preserved
        // Note: This happens AFTER parens wrapping so `(/* c */ (a ? b : c))()` -> `/* c */ (a ? b : c)()`
        printer.with_left_spine_claim(claim, || {
            printer.prepend_removed_paren_comments(
                span,
                span.start,
                call.callee.span().start,
                callee_doc,
            )
        })
    };

    // Handle optional chaining. With an empty argument list and no explicit type arguments
    // `?.` fuses into the list's own `?.(` instead of gluing onto the callee, so the whole
    // callee→`(` gap lands BEFORE it — the side prettier picks, and the member-chain
    // printer's answer to the same gap (`build_chain_args_empty`). Otherwise the `?.` is a
    // position with two writable sides, this call prints it, and `optional_callee_gap_doc`
    // emits the callee-side half of the gap in front of it; the argument side's own half is
    // already past `gap.start`. Both spellings are states of one derivation
    // ([`CalleeGap::optional`]) rather than two `call.optional` tests.
    let fuse_optional = optional.fused();
    let callee = match super::optional_callee_gap_doc(printer, gap) {
        Some(optional_doc) => d.concat(&[callee, optional_doc]),
        None => callee,
    };

    // Combine callee with type arguments (`fn<T>`), preserving comments in the gap
    // e.g., `fn/* c1 */ <string>()` — comment between callee and `<`
    let callee = append_type_args_with_gap_comments(
        printer,
        callee,
        callee_gap_start,
        call.type_arguments.as_ref(),
    );

    CallHead {
        doc: callee,
        gap,
        test_call,
        fuse_optional,
        ungroup_args,
    }
}

/// What a call's head decided about the test-call layout ([`CallHead::test_call`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum TestCall {
    /// The call is not a test call ([`is_test_call`]).
    No,
    /// A test call taking the flat layout.
    Flat,
    /// A test call whose argument gaps hold a comment the flat layout would drop
    /// ([`test_call_flat_gaps_clear`]), so its arguments lay out like any other call's.
    Declined,
}

/// The argument-list half of [`build_call_doc_with_wrapping`], `callee` being the head it
/// hangs off — the real head on the unsplit path, an empty doc when the pre-paren half of
/// the callee→`(` gap has taken it, so the wrapper can hang this whole doc under the run.
///
/// `callee` is a parameter rather than read off `head`, and every arm below takes it from
/// here: that is what makes the empty-head contract unforgettable — an arm assembling its own
/// callee would print it twice on the split path, or drop it on the unsplit one. `head` is
/// still passed for the two decisions the argument side re-reads (`gap`, the flat-layout and
/// `?.`-fusion verdicts), never for its doc.
fn build_call_args_doc(
    printer: &Printer<'_>,
    call: &ast::CallExpression<'_>,
    span: Span,
    callee: DocId,
    head: &CallHead,
) -> DocId {
    let d = printer.d();
    let &CallHead {
        gap,
        test_call,
        fuse_optional,
        ungroup_args,
        ..
    } = head;
    let callee_gap_start = gap.start;

    // Empty args: just `fn()` or `fn<T>()`, preserving dangling comments
    if call.arguments.is_empty() {
        let after_type_args = call
            .type_arguments
            .as_ref()
            .map_or(callee_gap_start, |ta| ta.span.end);
        return build_empty_args_doc(printer, callee, after_type_args, span.end, fuse_optional);
    }

    let paren_open = gap.paren_open(call);

    // A `Boolean()` coercion's argument is a `shouldNotIndent` position (`key === "arguments"
    // && isBooleanTypeCoercion(parent)`, `shouldNotIndent` in `print/binaryish.js`): its binary chain takes no
    // continuation indent, the argument list already supplying the level, exactly as the
    // `!!()` coercion it mirrors. Marked ONCE here, ahead of every layout below, because they
    // all reach the argument through the shared `build_arg_expression_doc`, which reads the
    // mark — a per-arm spelling left every arm but the default list blind. The member-chain
    // printer marks at the same point of its own entry, so a chain HEAD answers alike.
    mark_boolean_coercion_argument(printer, call);
    printer.mark_relational_sibling_authored_pairs(call.arguments.iter().copied().map(Some));

    // Single template literal argument with embedded newlines on the same line as `(` — hug
    // it. A template on its own line declines and falls through to the layouts below, whose
    // `will_break` guards see the template's own newline.
    //
    // ⚠️ ABOVE the comment paths, which is prettier's own position and not a preference:
    // `isTemplateLiteralSingleArg` is the FIRST thing `printCallExpression` asks, above the
    // member chain and above `printCallArguments` entirely, so the rule is
    // comment-INDEPENDENT there — `` fn(/* c */ `a⏎b`) `` hugs. Asking it below
    // `try_single_arg_comment_paths` let any leading comment defeat the hug, which is a
    // divergence on its own AND the reason the gap emitter inside the hug could not be added
    // alone: emitting the run inline gave prettier's form on pass 1 and re-expanded on pass 2,
    // because the relocated comment then leads the argument and the comment path claims it
    // again. The `new` twin and the member chain already hugged past a leading comment, so
    // this is the plain call joining them rather than a third answer.
    if let Some(doc) =
        try_hug_multiline_template_arg(printer, callee, call.arguments, paren_open, span.end)
    {
        return doc;
    }

    // Single-argument comment paths: leading line comments (multi-line expansion)
    // and inline block comments. Own-line trailing comments defer to the general
    // comment path, so this returns `None` and the caller falls through.
    if call.arguments.len() == 1
        && let Some(doc) = try_single_arg_comment_paths(printer, call, span, callee, paren_open)
    {
        return doc;
    }

    // The test-call flat layout, whose break-free callee `callee` already carries (built
    // at the top, so the type arguments and the removed-paren comments wrap it there).
    if test_call == TestCall::Flat {
        // Check for trailing comments on last arg. The empty-args case returned
        // above, so `arguments` is non-empty here and `.last()` is always `Some`.
        #[expect(clippy::unreachable)] // empty args already returned above ⇒ last() is Some
        let Some(last_arg) = call.arguments.last() else {
            unreachable!("a test call requires arguments");
        };
        let paren_close = span.end;

        // The callback's own parameter list stays flat. Prettier reaches the same place from
        // the other side — its parameter printers ask `isTestCall` of the function's PARENT
        // (`isParametersInTestCall`) — and tsv's printer has no parent link, so the call sets
        // a one-shot flag on the way down instead. `is_test_call` has already established
        // that argument 1 is the callback; its type-parameter builders peek the flag and its
        // value-parameter builder spends it before building anything nested, so nothing below
        // the callback's own signature sees it.
        // The `set` per argument (rather than only at index 1) keeps the flag from surviving
        // an argument that never consumed it.
        //
        // Keyed on the flat LAYOUT — this branch — and not on `is_test_call`, deliberately: the
        // flat-parameter licence is the overrunning line's, so a call that DECLINES the flat
        // layout (an argument gap holds a comment) is an ordinary call, and its callback's
        // parameters break on width like any other's. Prettier keys the same rule on the callee
        // alone, but never reaches the expanded state to disagree — `printCallExpression` takes
        // its test-call branch unconditionally, so its `isParametersInTestCall` holds exactly
        // when the call already printed flat. Both boundaries are pinned by
        // `tests/fixtures/typescript/expressions/calls/test_call_expanded_params_long_prettier_divergence`;
        // reasoning in docs/conformance_prettier.md §Print Width Philosophy.
        let arg_docs: DocBuf = call
            .arguments
            .iter()
            .enumerate()
            .map(|(i, arg)| {
                printer.test_call_flat_params.set(i == 1);
                printer.build_expression_doc(arg)
            })
            .collect();
        printer.test_call_flat_params.set(false);

        let mut parts: DocBuf = smallvec![callee, d.text("("), d.join_doc(arg_docs, d.text(", "))];

        // The last-arg→`)` gap, per the canonical trailing-run rule: a block inline
        // before the `)`, a `//` deferred past it (the flat test-call quirk — prettier
        // relocates it to `}); // c` too, pinned by `calls/trailing_comment_edge_cases`),
        // an own-line comment keeping its own line inside the suffix. The returned
        // must-break is deliberately ignored: the deferred run escapes the flat call by
        // design here, and the flush at the statement's own break ends its line.
        printer.push_trailing_comments_in_range(&mut parts, last_arg.span().end, paren_close);
        parts.push(d.text(")"));

        return d.concat(&parts);
    }

    // Whole-call comment-presence gate: one binary search over the entire argument
    // window. Every per-argument comment sub-query below (the leading / inter-arg /
    // trailing predicates, each O(n) over args, plus the general comment path) lies
    // within [paren_open, call_span.end], so when the call has no comment they are
    // provably all false/empty — skip them. Canonical reference:
    // build_params_doc_with_comments.
    // Counts owned comments: this asks whether the argument window puts any comment text on
    // the page (a *layout* question), not who emits it — see `has_comments_on_page_between`.
    let call_has_comments = printer.has_comments_on_page_between(paren_open, span.end);

    // Prettier's React-hook deps-array layout — the FIRST thing `printCallArguments` asks,
    // above `anyArgEmptyLine` and every specialized layout, so an author blank between the
    // callback and the deps array collapses here rather than forcing the arguments out.
    if let Some(doc) = try_hook_deps_args_doc(
        printer,
        call.arguments,
        paren_open,
        span.end,
        call_has_comments,
        d.concat(&[callee, d.text("(")]),
    ) {
        return doc;
    }

    // A trailing LINE comment on an argument (`fn(a, // c⏎ b)`) rules out every layout
    // below that would have to place the arguments itself: each joins them with `", "` or
    // hugs them, and a comment running to EOL can't survive either — so they all decline
    // and the call falls through to the comment-aware paths. Computed once: it is pure in
    // `(call, printer)`, six arms ask it, and each ask walks the arguments with a binary
    // search per gap. (`build_call_with_arg_comments` hoists the same predicate for the
    // same reason.) The `call_has_comments` conjunct keeps a comment-free call at the one
    // window-wide binary search above.
    let arg_trailing_line_comment =
        call_has_comments && has_trailing_comments_on_args(call, span, printer);

    // Prettier's `anyArgEmptyLine` (`print/call-arguments.js`): an author blank line in ANY
    // inter-argument gap forces `allArgsBrokenOut()` — and that test sits ABOVE
    // `shouldExpandFirstArg` / `shouldExpandLastArg`, so the blank defeats every specialized
    // layout rather than being asked about after one has been chosen. Asking it only
    // at the bottom of this dispatcher, below every early return, would let the blank survive a
    // plain argument list and be silently eaten by each hug / expand / composition path — the
    // blank-DROP class (docs/blank_audit.md), invisible to every gate but a prettier compare.
    // Hoisted here as a DECLINE conjunct on those arms rather than as an early return, so a
    // call whose gaps also hold comments still reaches `build_call_with_arg_comments` (which
    // owns the blank question for a commented gap) — the same shape as
    // `arg_trailing_line_comment` above, and what keeps `build_call_args_with_blank_lines`'s
    // "no inter-arg comments here" invariant true.
    //
    // ⚠️ A **test call has no `anyArgEmptyLine`**, and the predicate is `is_test_call` — the
    // CALLEE — not `test_call_flat_layout_applies`, the layout that fired above. Prettier's
    // `printCallExpression` takes its `isTestCall` branch unconditionally and joins the
    // arguments itself, so `printCallArguments` (and with it `anyArgEmptyLine`) is never
    // reached for one; tsv's flat layout additionally DECLINES when an argument gap holds a
    // comment it has no emitter for (the sanctioned divergence pinned by
    // `test_call_arg_comment_prettier_divergence`). Keying the blank on the layout would let
    // a declined test call keep the blank, and that is not idempotent: pass 1 glues the
    // own-line comment to its argument, which makes the flat layout apply on pass 2, which
    // drops the blank again. Keying it on the callee gives both passes the same answer —
    // prettier's — and `blanks:audit` caught exactly this as three NON-IDEMPOTENT shapes.
    let any_arg_empty_line =
        test_call == TestCall::No && any_arg_empty_line(call.arguments, printer);

    // A trailing BLOCK comment on the last argument — the block twin of the predicate above,
    // disqualifying the hug arms the same way. Computed here rather than at the first hug
    // because the blank gate below hands it to `build_call_with_arg_comments`; it is pure and
    // already short-circuited by `call_has_comments`, so hoisting it costs nothing.
    let has_trailing_block_comment = call_has_comments
        && call.arguments.last().is_some_and(|last_arg| {
            printer
                .comments_on_page_between(last_arg.span().end, span.end)
                .any(|c| c.is_block)
        });

    // Prettier's POSITION for `anyArgEmptyLine` — it short-circuits to `allArgsBrokenOut()`
    // above every specialized layout. ONE site rather than a decline conjunct on each arm, so
    // a layout added below cannot forget to ask; the two forms are equivalent because every
    // arm this jumps over is either single-argument (a blank needs two arguments to sit
    // between, so the question is vacuous there) or would have declined on the blank anyway.
    //
    // WHICH builder owns it is the gaps' answer, not this gate's: a commented gap belongs to
    // `build_call_with_arg_comments`, which carries the blank through its own per-gap
    // emitters, and only a comment-free one reaches `build_call_args_with_blank_lines` —
    // whose "no inter-argument comments here" invariant is exactly what this fallback states.
    if any_arg_empty_line {
        return build_call_with_arg_comments(
            printer,
            call,
            span,
            callee,
            paren_open,
            has_trailing_block_comment,
            call_has_comments,
        )
        .unwrap_or_else(|| {
            build_call_args_with_blank_lines(printer, callee, call.arguments, paren_open, span.end)
        });
    }

    // Module path calls that should not break at arguments (e.g., require.resolve)
    // Keep the call on one line; let assignment/parent break instead
    if is_module_path_no_break(call, printer) && !arg_trailing_line_comment {
        return d.concat(&[
            callee,
            d.text("("),
            d.join(
                call.arguments
                    .iter()
                    .map(|arg| printer.build_expression_doc(arg)),
                ", ",
            ),
            d.text(")"),
        ]);
    }

    // Module path calls (require.resolve.paths, import.meta.resolve) break at chain
    // rather than at arguments, keeping the path on the same line as the method
    if let Some((base_expr, method_name)) =
        get_module_path_chain_break(call, printer).filter(|_| !arg_trailing_line_comment)
    {
        let base_doc = printer.build_expression_doc(base_expr);
        let method_doc = printer.identifier_name_doc(method_name);
        let arg_doc = printer.build_expression_doc(call.arguments[0]);

        // Format: base\n\t.method(arg)
        // When it fits on one line, don't break
        return d.group(d.concat(&[
            base_doc,
            d.indent_softline(d.concat(&[
                d.text("."),
                method_doc,
                d.text("("),
                arg_doc,
                d.text(")"),
            ])),
        ]));
    }

    // Single function argument: "hugged" formatting
    // - Block arrows stay hugged if first line fits, wrap if it doesn't
    // - Expression arrows use width-aware group (wrap when exceeds line limit)
    // Skip hugging if there are trailing comments - let comment handling block handle it
    if call.arguments.len() == 1
        && !arg_trailing_line_comment
        && !has_trailing_block_comment
        && let Some(doc) = try_single_arg_hug(printer, call, callee)
    {
        return doc;
    }

    // No arm here for an argument carrying its own newline — a line-continuation string, a
    // multiline template. Prettier has no container-level predicate for one either: it
    // prints such a literal through `replaceEndOfLine`, whose `literalline` carries a
    // `breakParent`, and the expansion is `propagateBreaks` alone. tsv's counterparts are
    // the `will_break` guards each layout below already asks — `expand_all_if_head_breaks`
    // in the expand-last ladder, `build_expand_first_arg_doc`'s tail scan, and
    // `wrap_call_with_will_break_guard` on the default path — which is why a source-scanning
    // twin ahead of them could only pre-empt the hug prettier keeps.

    // Function composition pattern: when any argument is a call containing a callback
    // e.g., fn(arr.map((x) => x), b) → fn(\n\tarr.map((x) => x),\n\tb,\n)
    // Prettier's isFunctionCompositionArgs: 2+ args, any arg is call with function/arrow inside
    // Skip if there are trailing comments - let the comment handling code deal with expansion
    if is_function_composition_args(call.arguments) && !arg_trailing_line_comment {
        return build_call_args_expanded(
            printer,
            ArgOpener::callee(d, callee),
            call.arguments,
            paren_open,
            span.end,
        );
    }

    // "Expand first arg" pattern: when first arg is a function with block body
    // and remaining args are short, hug the function and put tail args after closing }
    // e.g., setTimeout(() => { tick(); }, 100);
    // The inline tail can carry neither a comment running to EOL nor one leading the first
    // argument. Named rather than inlined, matching the `new` twin.
    // The first argument's own signature refusing the hug is asked last, behind the shape
    // test: it builds that signature.
    let expand_first_blocked = arg_trailing_line_comment
        || (call_has_comments && first_arg_has_any_comments(call.arguments, printer, paren_open));
    if should_expand_first_arg(printer, call.arguments)
        && !expand_first_blocked
        && !first_arg_signature_refuses_expand_first(printer, call.arguments)
    {
        return build_expand_first_arg_doc(
            printer,
            ArgOpener::callee(d, callee),
            call.arguments,
            paren_open,
            span.end,
        );
    }

    // No all-arrows arm here: `is_function_composition_args` above already covers it.
    // 2+ arguments that are ALL arrows means `function_count > 1`, which that predicate
    // short-circuits `true` on, and both arms decline on the same
    // `arg_trailing_line_comment` — so an arrow-only arm below it can never be reached.
    //
    // Prettier's `shouldExpandLastArg`, shared with the `new` printer (one
    // `printCallArguments` prints both). Must come BEFORE the comment-handling path below:
    // an inline block comment ahead of the first argument (`fn(/* c */ a, b, {…})`) would
    // otherwise take that path, which has no expand-last layout, and `build_args_split_last`
    // already handles such a comment correctly. Returns `None` when the guard fails, so the
    // caller falls through.
    if let Some(doc) = try_expand_last_arg(
        printer,
        call.arguments,
        callee,
        paren_open,
        span.end,
        call_has_comments,
        ArgOwner::Call,
    ) {
        return doc;
    }

    // Comment-handling path: leading, inter-argument, or trailing comments on the
    // arguments. Returns `None` when there are no such comments, so the caller
    // falls through to the blank-line / default layout below.
    if let Some(doc) = build_call_with_arg_comments(
        printer,
        call,
        span,
        callee,
        paren_open,
        has_trailing_block_comment,
        call_has_comments,
    ) {
        return doc;
    }

    // Build args with line separators (one per line when broken). A `Boolean()` coercion's
    // argument goes flat here through the mark set at the top of this function, not through
    // a builder named at this site.
    let arg_parts = d.join_doc(
        call.arguments.iter().map(|arg| {
            // This is prettier's `printedArguments` — printed with no `expandLastArg`, so a
            // curried chain takes the progressive layout (`build_printed_argument_doc`).
            build_printed_argument_doc(printer, arg, || printer.build_arg_expression_doc(arg))
        }),
        d.comma_line(),
    );

    // Prettier: group(contents, { shouldBreak: printedArguments.some(willBreak) }).
    //
    // The explicit shouldBreak is NOT redundant, though it looks it: a forced break in
    // `arg_parts` does break this group at *render* (the plain-group arm keys on
    // `should_break || will_break(contents)`), but `arena_fits`' Group arm keys only on
    // `should_break` — tsv has no propagateBreaks. So inside an outer FLAT fits walk a
    // plain group is measured flat to its first hardline, where a `group_break` is
    // entered in Break mode and ends the line at its first softline. Prettier's
    // propagateBreaks makes its own fits see such a group broken, i.e. like the
    // `group_break` side. The two shapes therefore differ wherever an outer flat fits
    // measures this call — a `conditional_group` state, a fill part — and the angle-bracket
    // cast ladder is a live observer: without the guard, `<A>fn(a, (y) => { … }, c)` is
    // measured short enough to select the parenthesized state, printing `<A>(⏎fn(…)⏎)`
    // where prettier keeps the cast attached. See
    // `expressions/type_assertion_call_block_arg_long`.
    //
    // This still handles block functions before the last arg (`fn((x) => { body }, aaa)`)
    // without the old has_block_function_before_last check, which was too aggressive — it
    // forced hardlines for empty block bodies like `async () => {}`, preventing calls like
    // `fn([], 3, async () => {}, aaa)` from staying on one line.
    //
    // A long-curried call's list takes no group at all: prettier returns the bare contents,
    // so the list breaks with the group around it — the outer call's.
    if ungroup_args {
        return ArgOpener::callee(d, callee).soft_list(d, arg_parts);
    }
    wrap_call_with_will_break_guard(d, callee, arg_parts)
}

/// Close the lone argument's `argument`→`)` gap.
///
/// Every branch of [`try_single_arg_comment_paths`] opens a gap *before* the argument, and
/// each one owes the gap *after* it — the branches are chosen on what leads the argument,
/// but they all print the whole `(…)`. `has_own_line_trailing_comment` has already routed
/// every own-line comment in this gap to the general path, so what reaches here is
/// same-line blocks, which stay on the argument's line.
///
/// One emitter because a branch that forgot it printed the gap it opened and dropped the
/// one it closed (`f(⏎// c⏎a /* t */)` → `f(⏎// c⏎a)`).
fn push_lone_arg_trailing_comments(
    printer: &Printer<'_>,
    parts: &mut DocBuf,
    arg_end: u32,
    paren_close: u32,
) {
    if let Some(trailing) = printer.build_inline_comments_between_doc_opt(arg_end, paren_close) {
        parts.push(trailing);
    }
}

/// Single-argument comment paths for the `(`→argument gap: a gap a comment forces open (a
/// line comment, or a block that owns its line) takes the expanded layout with the
/// delimiter-line pull, and a block-only gap leads the argument as one run inside the soft
/// wrap. Returns `None` when the gap holds no comment — or the argument has own-line
/// trailing comments, which defer to the general comment path — so the caller falls through.
fn try_single_arg_comment_paths(
    printer: &Printer<'_>,
    call: &ast::CallExpression<'_>,
    span: Span,
    callee: DocId,
    paren_open: u32,
) -> Option<DocId> {
    let d = printer.d();
    let first_arg = &call.arguments[0];
    let arg_start = first_arg.span().start;
    let arg_end = first_arg.span().end;
    let paren_close = span.end;

    // Own-line trailing comments after the arg (any line comment, or a block
    // comment on a line below the arg) aren't handled by the single-arg
    // branches below — defer to the general comment path (which emits them
    // after the last arg, no trailing comma). Same-line inline trailing block
    // comments (e.g. `fn(/* c */ a /* t */)`) stay on this fast path.
    let has_own_line_trailing_comment = printer
        .comments_on_page_between(arg_end, paren_close)
        .any(|c| !c.is_block || !printer.is_same_line(arg_end, c.span.start));

    // A line comment, or a block comment that owns its line, forces the list open — the gap
    // question `new` and the member chain ask too. Such a gap takes the expanded layout
    // below, which answers the delimiter-line question as every sibling does
    // (`docs/comments.md` §The delimiter-line question): a comment on the `(` line stays
    // there, and the rest leads the argument, each own-line comment on its own line.
    //
    // ⚠️ **Not `has_line_comments` alone.** A block that owns its line forces the break
    // exactly as a `//` does, and the hug branch below — whose glued emitter joins a block to
    // what follows even across a newline — MERGED comments the author put on separate lines
    // (`fn(/* c1 */⏎/* c2 */⏎a)` → `fn(⏎/* c1 */ /* c2 */⏎a⏎)`, then `fn(/* c1 */ /* c2 */ a)`
    // on the next pass) and welded a glued pair below one (`/* c2 */ /* c3 */⏎{` →
    // `/* c2 */ /* c3 */ {`), a form prettier's own output reached on its first tsv pass.
    let forces_expansion = should_force_expansion_for_comments(printer, paren_open, arg_start);
    if forces_expansion && !has_own_line_trailing_comment {
        // Multi-line format: fn( // comment\n\targ,\n)
        // Comments trailing the `(` on its own line stay there (a divergence from
        // prettier, which relocates them to their own line); own-line comments
        // stay on their own lines before the arg. See conformance_prettier_ts_comments.md
        // §Comment relocation (Call open paren `(`).
        let mut paren_line_prefix = DocBuf::new();
        let mut inner = DocBuf::new();
        // Own-line comments each take their own line (author blanks preserved); a
        // block that hugs the arg stays inline with it (`/* b */ a`).
        PartitionedComments::new(printer, paren_open, arg_start).emit_pulled_gap(
            &mut paren_line_prefix,
            &mut inner,
            printer,
        );
        // Use the argument-context builder so a binary/logical chain (or conditional)
        // takes the ARGUMENT group structure — matching the no-leading-comment path.
        // (Both builders indent the continuation; they differ in whether a forced break
        // reaches every operand — see `Printer::build_arg_expression_doc_uncached`.)
        // An own-line directive in the gap freezes the argument verbatim (Rule A);
        // this branch already keeps such a comment on its own line.
        inner.push(build_joined_argument_doc(
            printer,
            paren_open,
            call.arguments,
            0,
        ));
        push_lone_arg_trailing_comments(printer, &mut inner, arg_end, paren_close);

        return Some(d.concat(&[
            callee,
            d.text("("),
            d.concat(&paren_line_prefix),
            d.indent_hardline(d.concat(&inner)),
            d.hardline(),
            d.text(")"),
        ]));
    }

    // A block comment before the lone argument — **owned or not** — defeats the
    // argument hug, exactly as prettier's `couldExpandArg` refuses to hug an arg
    // whose leading comment sits before it. This is an **on-page** question (does a
    // comment occupy the page here), not a *to-emit* one: an owned comment (a JSDoc
    // cast / any glued block comment) travels inside the argument's own doc, so it
    // isn't emitted here, but it still forces the expansion — a to-emit gate would
    // go blind to it and wrongly hug.
    //
    // The run itself is the gap's one leading run (`PartitionedComments::emit_unpulled_gap`,
    // which states why a glue emitter here is the bug class): it prints only the non-owned
    // comments — an owned one rides on the argument's doc, so
    // `fn(/** @type {A} */ /** @type {B} */ expr)` keeps its glued space — and an author blank's
    // hardline opens the call. No comment here owns its line: such a gap took the expanded
    // branch above.
    if printer.has_comments_on_page_between(paren_open, arg_start) && !has_own_line_trailing_comment
    {
        let mut parts: DocBuf = DocBuf::new();
        PartitionedComments::new(printer, paren_open, arg_start)
            .emit_unpulled_gap(&mut parts, printer);
        // Argument-context builder so a binary/logical chain gets its
        // continuation indent (matches the no-comment path); see the leading
        // line-comment branch above for the same reasoning. A directive alone on its
        // line freezes the argument (Rule A) — only the BLOCK spelling reaches here
        // (a line comment routes to the branch above).
        parts.push(build_joined_argument_doc(
            printer,
            paren_open,
            call.arguments,
            0,
        ));
        push_lone_arg_trailing_comments(printer, &mut parts, arg_end, paren_close);

        // Soft-break wrapping so the outer call can expand when content exceeds print
        // width — e.g., fn(/** @type {T} */ call(long_args)) →
        // fn(\n\t/** @type {T} */ call(\n\t\tlong_args,\n\t),\n). An arg that breaks
        // internally (multiline content) breaks this group with it, which is already
        // the expanded form — no separate hard-break arm.
        return Some(wrap_call_with_soft_breaks(d, callee, d.concat(&parts)));
    }

    None
}

/// Single huggable argument: the "hug" layout cascade (block/expression arrows,
/// function expressions, object/array literals, short literals). Returns `None`
/// for long/multiline literals and other non-arrow arguments that should fall
/// through to standard wrapping.
fn try_single_arg_hug(
    printer: &Printer<'_>,
    call: &ast::CallExpression<'_>,
    callee: DocId,
) -> Option<DocId> {
    let d = printer.d();
    let arg = &call.arguments[0];

    // Non-huggable arguments: use soft-break wrapping so outer call can break first
    // (call expressions, member expressions, new expressions, identifiers, conditionals)
    if arg_needs_soft_wrap(arg) {
        let arg_doc = printer.build_arg_expression_doc(arg);
        return Some(wrap_call_with_soft_breaks(d, callee, arg_doc));
    }

    // A broken `=>`→body gap keeps the arrow start on the `callee(` line and breaks the
    // closing paren onto its own. **Above the match**, because the rule is the gap's and not
    // the arms' body-kind split — the one body question it does owe, prettier's
    // `couldExpandArg`, the helper applies itself ([`last_arg_arrow_gap_break`]) — asking it
    // inside the block-arrow arm left every other body kind to the arms below, which are
    // body-keyed and answer this gap not at all: a call or ternary body took its own
    // reassembling layout and printed the signature past the print width with no state to
    // fall through to (`calls/arrow_object_body_own_line_comment_long`).
    //
    // A signature that will break still wins: that layout renders the signature's head on the
    // callee's line, which the break makes impossible, so the helper refuses the state for
    // every callee spelling and the block-arrow arm's own refusal keeps it.
    if let ast::ExpressionKind::ArrowFunctionExpression(_) = &arg.kind
        && let Some(gap_break) = last_arg_arrow_gap_break(printer, arg)
    {
        return Some(build_arrow_gap_break_single_arg_doc(
            printer,
            ArgOpener::callee(d, callee),
            arg,
            &gap_break,
            None,
            || printer.build_expression_doc(arg),
        ));
    }

    match &arg.kind {
        // Block arrow (or expandable arrow chain): use conditional_group to let Doc decide hug vs wrap
        //
        // Expandable arrow chains: `() => () => { block }`, `() => () => ({obj})`
        // are treated identically to block-body arrows. Matches prettier's
        // couldExpandArg recursive check with arrowChainRecursion=true.
        ast::ExpressionKind::ArrowFunctionExpression(arrow)
            if !arrow.body.is_expression() || could_expand_arrow_chain(arrow) =>
        {
            return Some(build_block_arrow_hug_states(
                printer, callee, arrow, arg.span, arg,
            ));
        }

        // Regular function expression: the shared lone-argument ladder
        // ([`ArgOpener::lone_hug_ladder`]). Its middle state is what lets a long PARAMETER
        // list break while `callee(function name(` stays on one line
        // (`prettier/tests/format/js/last-argument-expansion/overflow.js`).
        //
        // A signature that refuses the hug refuses it outright: every hug state renders the
        // callee and the signature's head on one line, which the break makes impossible.
        ast::ExpressionKind::FunctionExpression(_) => {
            let arg_doc = printer.build_expression_doc(arg);
            let opener = ArgOpener::callee(d, callee);
            if callback_signature_refuses_hug(printer, arg, 1) {
                return Some(opener.break_out(d, arg_doc));
            }
            return Some(opener.lone_hug_ladder(d, arg_doc, lone_arg_params_render_flat(arg)));
        }

        // Object/array literals, and type assertions wrapping them — the shared arm, so the
        // `new` twin cannot answer either half differently
        // ([`build_single_container_arg_doc`]).
        _ if is_array_or_object_unwrapped(arg, printer) => {
            return Some(build_single_container_arg_doc(printer, callee, arg));
        }

        // No arm for a lone LITERAL argument: prettier has none either
        // (`printCallArguments` ends at its soft-break group for every non-hug argument), so
        // a literal falls through to `wrap_call_with_soft_breaks` like any other. ⚠️ A hug
        // keyed on a short literal used to live here, and it was prettier's 25-char
        // `LONE_SHORT_ARGUMENT_THRESHOLD_RATE` read at the wrong layer: that threshold is the
        // ASSIGNMENT layout's (`isPoorlyBreakableMemberOrCallChain`, tsv's
        // `is_poorly_breakable_chain`, pinned by `calls/string_arg_long`), which chooses
        // between breaking at the operator and breaking the call — it never says the call has
        // NO break point. Spelling it here emitted a group-free, line-free doc, so
        // `fn('short')` could not break at all once nothing above it could: a statement-position
        // call ran past the print width (`calls/literal_arg_statement_long`), and so did a
        // template interpolation whose source spans lines, where `${` hugs a non-qualifying
        // expression and the call is the only thing left that can break
        // (`literals/template/interpolation_call_newline_long`).

        // Expression arrow whose body is neither a block nor expandable — an object or array
        // body cannot reach here, since [`could_expand_arrow_chain`] claims it for the first
        // arm above. (Probed: 0 hits over 15.5k real files and the whole fixture suite, which
        // is what the guard's complement already says.)
        ast::ExpressionKind::ArrowFunctionExpression(arrow) => {
            if let ast::ArrowFunctionBody::Expression(body_expr) = &arrow.body {
                // Expandable body (ternary): use conditional parens
                // Prettier's "expand last arg" pattern:
                // - Flat: `map((x) => (x ? y : z))` - parens prevent `<=` ambiguity
                // - Break: `map((x) =>\n  x ? y : z,)` - no parens, indented
                // Prettier's couldExpandArg keys on the body type and looks
                // through the return-type annotation, so typed-return arrows
                // (`(x): T => …`) are eligible too.
                // The reassembling arm's refusal pair (`arrow_hug_refused_by_comments`): a
                // break forced inside the signature this conditional-group cannot honor, and
                // a comment on the body's tail — every state below reassembles the argument
                // from a signature and a body doc, synthesizing its own parens around the
                // ternary, so such a comment reaches no emitter. A signature that will break
                // refuses too: the states print it flattened, and none prints the argument
                // whole, so the call breaks every argument out below.
                if is_ternary_arrow_body(body_expr)
                    && !arrow_hug_refused_by_comments(printer, arrow, arg.span, body_expr)
                    && !arrow_signature_refuses_hug(printer, arrow, arg.span)
                {
                    return Some(build_ternary_arrow_hug_states(
                        printer, callee, arg, arrow, body_expr,
                    ));
                }
            }
            // Other expression arrows: fall through to wrap
        }

        // Other arguments: fall through to standard handling
        _ => {}
    }

    // Wrap callback with width-aware breaking
    if let ast::ExpressionKind::ArrowFunctionExpression(arrow) = &call.arguments[0].kind {
        if let ast::ArrowFunctionBody::Expression(body_expr) = &arrow.body {
            // Prettier keeps `fn((x) =>` together (sig on opening line) when the
            // body is a call expression (looking through a trailing non-null `!`,
            // per prettier's `stripChainElementWrappers`). couldExpandArg keys on
            // the body type and ignores the return-type annotation, so typed-return
            // arrows (`(x): T => call()`) hug too.
            if arrow_body_is_call_through_non_null(body_expr)
                // The reassembling arm's refusal pair — a break forced inside the signature
                // invalidates this hug exactly as it does the object/array one above, and so
                // does a comment on the body's own tail, which the states this builds
                // reassemble past (`arrow_hug_refused_by_comments`).
                && !arrow_hug_refused_by_comments(printer, arrow, arg.span, body_expr)
                // The body is built once and shared by every state (see the ladder's doc) —
                // last, because it builds.
                && let Some(body_reuse) = prebuild_expand_last_break_body(printer, Some(arg))
            {
                return Some(build_arrow_call_body_states(
                    printer,
                    ArgOpener::callee(d, callee),
                    arg,
                    arrow,
                    body_expr,
                    body_reuse,
                    || printer.build_expression_doc(arg),
                ));
            }
            // Other expression types: fall through to standard wrapping
        }
        // Block arrow or non-call expression body: standard wrapping.
        // Nothing here hugs, so this is prettier's `printedArguments` shape — a curried
        // chain takes the progressive layout (`build_printed_argument_doc`).
        let arg = &call.arguments[0];
        let arg_doc =
            build_printed_argument_doc(printer, arg, || printer.build_expression_doc(arg));
        return Some(wrap_call_with_soft_breaks(d, callee, arg_doc));
    }

    None
}

/// Build the hug/wrap states for a single block-body arrow (or expandable arrow
/// chain) argument: `callee((x) => { ... })`. Handles trailing-param-comment
/// forcing, object/array expression bodies, and the default 2-state hug/wrap.
fn build_block_arrow_hug_states(
    printer: &Printer<'_>,
    callee: DocId,
    arrow: &ast::ArrowFunctionExpression<'_>,
    span: Span,
    arg: &ast::Expression<'_>,
) -> DocId {
    let d = printer.d();
    let build = || printer.build_expression_doc(arg);

    // ⚠️ Both comment refusals are asked BEFORE the pair below and read only the
    // `printedArguments` printing — the pair is a second build of the argument, which
    // recurses into any call nested in its body ([`build_arrow_hug_printed_doc`]).

    // A signature that will break — a comment forcing it, or a break its own docs carry —
    // refuses the hug: every hug state renders the signature's head on the callee's line.
    if arrow_signature_refuses_hug(printer, arrow, span) {
        let printed = build_arrow_hug_printed_doc(printer, arg, arrow, build);
        return d.concat(&[
            callee,
            d.text("("),
            d.indent(d.concat(&[d.softline(), printed])),
            d.softline(),
            d.text(")"),
        ]);
    }

    // ⚠️ An own-line comment between `=>` and the body is NOT asked here — `try_single_arg_hug`
    // answers it above its whole body-kind match, because the rule is the gap's and not the
    // body's and the arms past this builder never asked it at all. The only way such a comment
    // reaches here is behind the signature-break refusal above, which returns first.

    // The two printings and the state ladder they feed, shared with the `new` and
    // member-chain single-argument arms — an object/array terminal gets the middle state that
    // expands it internally while the arrow stays hugged.
    build_single_arrow_hug_doc(
        printer,
        ArgOpener::callee(d, callee),
        arg,
        arrow,
        None,
        build,
    )
}

/// Build the 3-state expand-last layout for a single expression arrow with a
/// ternary body: `map((x) => (cond ? a : b))`. Flat keeps the parens; the break
/// states drop them and indent the body after `=>` (no trailing comma).
///
/// The ladder itself is [`build_ternary_arrow_hug_ladder`], shared with the `new` and
/// member-chain spellings of this same layout.
fn build_ternary_arrow_hug_states(
    printer: &Printer<'_>,
    callee: DocId,
    arg: &ast::Expression<'_>,
    arrow: &ast::ArrowFunctionExpression<'_>,
    body_expr: &ast::Expression<'_>,
) -> DocId {
    let d = printer.d();
    let sig_doc = build_arrow_sig_doc(printer, arrow, arg.span);

    // The body expression; the ladder prepends the comments between `=>` and the body
    let body_doc = printer.build_arrow_arg_body_doc(body_expr);

    build_ternary_arrow_hug_ladder(
        printer,
        ArgOpener::callee(d, callee),
        arrow,
        body_expr,
        sig_doc,
        body_doc,
        || printer.build_expression_doc(arg),
    )
}

/// Build the argument-list doc when the arguments carry comments (leading,
/// inter-argument, or trailing). Returns `None` when there are no such comments,
/// so the caller falls through to the blank-line / default layout.
fn build_call_with_arg_comments(
    printer: &Printer<'_>,
    call: &ast::CallExpression<'_>,
    span: Span,
    callee: DocId,
    paren_open: u32,
    has_trailing_block_comment: bool,
    call_has_comments: bool,
) -> Option<DocId> {
    let d = printer.d();

    // Zero-comment fast gate: this path only fires when the argument list has
    // comments; with none, every check below is false and it returns None anyway,
    // so skip them (canonical reference: build_params_doc_with_comments).
    if !call_has_comments {
        return None;
    }

    // Check for any comments in arguments (leading, inter-argument, or trailing)
    let has_leading_comments = !call.arguments.is_empty()
        && printer.has_comments_to_emit_between(paren_open, call.arguments[0].span().start);
    let has_inter_arg_comments = has_inter_argument_comments(call, printer);
    let has_trailing_arg_comments = has_trailing_comments_on_args(call, span, printer);
    // Also check for trailing block comments (has_trailing_comments_on_args only checks line comments)
    let has_any_trailing_comments = has_trailing_arg_comments || has_trailing_block_comment;

    // Check for own-line block comments after the last arg (before closing paren).
    // These need per-element handling to emit after the trailing comma.
    // A spread's stripped parens can leave one *before* the argument's own end, where no
    // scan here can reach it — that share is asked for by name, of every argument.
    let has_spread_paren_comments = printer.any_paren_interior_forces_expansion(call.arguments);
    let has_own_line_trailing_block = call.arguments.last().is_some_and(|last_arg| {
        let search_start = last_arg.span().end;
        printer
            .comments_on_page_between(search_start, span.end)
            .any(|c| c.is_block && !printer.is_same_line(search_start, c.span.start))
    });

    if !(has_leading_comments
        || has_inter_arg_comments
        || has_any_trailing_comments
        || has_own_line_trailing_block
        || has_spread_paren_comments)
    {
        return None;
    }

    // Build arguments with leading and/or inter-argument comments
    let mut arg_parts = DocBuf::new();
    // Comments trailing the `(` on its own line, kept on the `(` line when the
    // call expands (divergence from prettier, which relocates them to their own
    // line). Injected after `(` in the force-expansion wrap below.
    let mut paren_line_prefix_parts: DocBuf = DocBuf::new();
    let mut force_expansion = false;

    for (i, arg) in call.arguments.iter().enumerate() {
        // Handle leading comments before first argument
        if i == 0 && has_leading_comments {
            let first_arg_start = arg.span().start;

            if should_force_expansion_for_comments(printer, paren_open, first_arg_start) {
                force_expansion = true;
            }

            let gap_pc = PartitionedComments::new(printer, paren_open, first_arg_start);
            let has_paren_line = gap_pc.has_trailing_comments();

            // `PartitionedComments::pulls_to_delimiter_line`, spelled with the flag this
            // builder independently needs (it must record the forced expansion even where
            // nothing sits on the `(` line).
            if force_expansion && has_paren_line {
                // Comments trailing the `(` stay on the `(` line, author blank included;
                // the own-line set then leads the first arg via the shared emitter (a block
                // hugging the arg stays inline, own-line/line comments break, author blanks
                // preserved).
                gap_pc.emit_pulled_gap(&mut paren_line_prefix_parts, &mut arg_parts, printer);
            } else if !has_paren_line {
                // No comment on the `(` line → every gap comment leads the first
                // arg. Same shared emitter; it ends with the right separator before
                // the arg (space after a hug, hardline after an own-line comment).
                gap_pc.emit_leading_comments_inline_aware(&mut arg_parts, printer);
            } else {
                // A comment trails the `(` and nothing in the gap forces the list open, so the
                // run is block-only and no comment in it owns its line: the gap's one leading
                // run, whose author-blank hardline is the one separator that must also open the
                // list. Every builder of this gap shares that emitter
                // (`PartitionedComments::emit_unpulled_gap`, which states why a hand-rolled
                // separator here is the bug class).
                force_expansion |= gap_pc.emit_unpulled_gap(&mut arg_parts, printer);
            }
        }

        // Build the argument with the argument-context builder so a binary/logical
        // chain (or conditional) keeps its continuation indent — matching the
        // no-comment path (the single-arg comment path does the same via
        // build_arg_expression_doc). An own-line format-ignore directive in this
        // argument's gap freezes it verbatim (Rule A).
        arg_parts.push(build_joined_argument_doc(
            printer,
            paren_open,
            call.arguments,
            i,
        ));

        // Check for comments after this argument (before next arg or closing paren)
        if i < call.arguments.len() - 1 {
            let arg_end = arg.span().end;
            let next_arg_start = call.arguments[i + 1].span().start;

            // The gap after this argument, in the two regions that partition it: the
            // parent's share of a spread's stripped-paren interior and the ordinary
            // `[arg_end, next_arg_start)` scan. `open_inter_arg_gap` owns both — asking
            // only one of them (as an `if`/`else` over the two) drops the other.
            if printer.inter_arg_gap_has_comments(arg, next_arg_start) {
                if should_force_expansion_for_comments(printer, arg_end, next_arg_start) {
                    force_expansion = true;
                }

                // Open the gap (reclassify hugging blocks, emit before/after-comma
                // trailing comments + the comma, then the interior's own-line blocks);
                // the separator + leading comments below finish it.
                let interior = printer.arg_paren_interior(paren_open, call.arguments, i);
                let gap = printer.open_inter_arg_gap(&mut arg_parts, arg, interior, next_arg_start);
                let pc = gap.comments;
                if gap.forces_expansion {
                    force_expansion = true;
                }

                let has_blank_line = pc.has_blank_line_in_gap(printer);
                if has_blank_line || pc.has_trailing_line() {
                    force_expansion = true;
                }
                if has_blank_line {
                    arg_parts.push(d.literalline());
                }
                // A line comment runs to EOL → hard-break; otherwise a soft line so a
                // block-only arg can still collapse inline.
                arg_parts.push(if pc.has_trailing_line() {
                    d.hardline()
                } else {
                    d.line()
                });

                // Leading: own-line comments + after-comma comments that hug the next arg
                // (`C`), emitted inline with it.
                pc.emit_leading_comments_inline_aware(&mut arg_parts, printer);
            } else {
                let has_blank_line = printer.is_next_line_empty(arg_end, next_arg_start);
                if has_blank_line {
                    // No comments but blank line between args
                    force_expansion = true;
                    arg_parts.push(d.text(","));
                    arg_parts.push(d.literalline());
                    arg_parts.push(d.hardline());
                } else {
                    // No comments, just comma and line
                    arg_parts.push(d.comma_line());
                }
            }
        } else {
            // Last argument - trailing comments before the closing paren, in two
            // regions that partition it (see `emit_last_arg_trailing_comments`, which
            // states the same split for the builders that need no force-expansion
            // feedback): the parent's share of a spread's stripped-paren interior —
            // own-line comments the spread's own doc deliberately leaves behind, each a
            // sibling line the call cannot stay collapsed around — and the ordinary gap,
            // whose trailing run follows the share (`push_element_share_and_run`).
            // A same-line `//` the spread's own doc defers must flush INSIDE the call:
            // on a collapsed list the buffer drains past the `)` and the `;`,
            // re-binding the comment to the statement.
            let interior = printer.arg_paren_interior(paren_open, call.arguments, i);
            if printer.paren_interior_defers_line_comment(interior) {
                force_expansion = true;
            }
            // The ordinary gap, on the argument's own end. Widening this anchor to reach the
            // interior claims the spread's share a second time — the same-line blocks and
            // interior `//`s print twice. The last-argument gap holds the list's own comma
            // (`for_closer_gap`, never the delimiter reading) — see
            // `emit_last_arg_trailing_comments`, the shared path this loop mirrors so it can
            // feed `force_expansion`.
            let pc = PartitionedComments::for_closer_gap(printer, arg.span().end, span.end);

            // The trailing run, in source order: same-line blocks, then the same-line line
            // comment (via `line_suffix`). With no trailing comma emitted (trailingComma:
            // 'none'), a block that sat after the source comma simply trails the arg past
            // where the comma was. Blocks alone don't force expansion — width/source
            // newlines decide: fn({short} /* c */) stays inline, fn({long...} /* c */)
            // expands. A line comment always forces the CALL to expand: it runs to end of
            // line, and never counts toward width (prettier's `lineSuffix`), so the
            // argument's own group can stay inline while the call breaks.
            let share_pushed = printer.push_element_share_and_run(
                &mut arg_parts,
                interior,
                ShareSite::Closer,
                pc.trailing_run(),
            );
            let mut run_forces_expansion = pc.has_trailing_line();

            // Own-line comments (block or line) after the last arg, before the closing
            // paren — emitted each on its own line, with no trailing comma (trailingComma:
            // 'none').
            if !pc.leading.is_empty() {
                run_forces_expansion = true;
                pc.emit_dangling_comments(&mut arg_parts, printer);
            }
            if share_pushed || run_forces_expansion {
                force_expansion = true;
            }
        }
    }

    let arg_doc = d.concat(&arg_parts);

    // Force expansion if needed, otherwise allow collapsing.
    // Use a group with break_parent instead of literal hardlines to avoid
    // propagating breaks to parent (e.g., assignment) during fits().
    if force_expansion {
        // No trailing comma after the last arg (trailingComma: 'none').
        // Use hardlines for the expansion. The assignment should use NeverBreakAfterOperator
        // for calls since they handle their own expansion.
        // Wrap in group_break so line() separators between non-commented args
        // are forced to Break mode (newlines). Without this, when the call doc
        // is used as a body_doc inside chain_args or other contexts that render
        // in Flat mode, line() between args becomes a space instead of newline.
        return Some(d.concat(&[
            callee,
            d.text("("),
            d.concat(&paren_line_prefix_parts),
            d.group_break(d.concat(&[d.indent_hardline(arg_doc), d.hardline()])),
            d.text(")"),
        ]));
    }

    Some(wrap_call_with_soft_breaks(d, callee, arg_doc))
}