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
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
// Comment handling for call expression arguments
//
// Handles detection and partitioning of comments in argument lists:
// - Inter-argument comments (between arguments)
// - Trailing comments on arguments
// - Leading comments before arguments

use smallvec::SmallVec;

use super::super::{LeadingGlue, Printer};
use crate::ast;
use crate::printer::comments::ShareSite;
use tsv_lang::Span;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::arena::DocId;

impl<'a> Printer<'a> {
    /// Open a non-last argument gap that may carry comments and emit its head into
    /// `parts`: partition the comments, reclassify an after-comma block that **hugs**
    /// the next arg as leading (`C`) while a **stranded** one stays on the comma line
    /// (`A`), then emit the before-comma blocks, the comma, the stranded after-comma
    /// blocks, and the same-line line comment.
    ///
    /// Like [`emit_last_arg_trailing_comments`] at the other end of the list, the region
    /// after `prev_arg` has **two** sources and they must partition it exactly once
    /// (`docs/comments.md` §The element-comma seam, §A stripped-paren interior is a
    /// partition too): the ordinary gap `[prev_arg.end, next_arg_start)` above, and the
    /// parent's share of `prev_arg`'s own stripped-paren interior — the own-line comments a
    /// spread's doc deliberately leaves behind
    /// ([`Printer::push_paren_interior_own_line_comments`]). That share lies BEFORE
    /// `prev_arg`'s end, so a caller guarding this call on a plain gap scan must ask
    /// [`Printer::inter_arg_gap_has_comments`] instead or the interior is DROPPED.
    ///
    /// Where the interior stands between the argument's text and its run
    /// ([`Printer::paren_interior_separates_run`]) the order changes, to the order the same
    /// argument prints in without its parens: the comma, then the share, then the run
    /// ([`Printer::push_element_share_and_run`]). The comma sits against the argument, so a
    /// block of the run that no `//` follows is past it and leads the next argument
    /// ([`PartitionedComments::lead_run_blocks_behind_interior`]).
    ///
    /// Returns the routed [`PartitionedComments`] so the caller supplies the rest of the
    /// gap — its own separator policy (soft vs. hard line, blank-line preservation), then
    /// the next arg's leading comments via
    /// [`PartitionedComments::emit_leading_comments_inline_aware`] — alongside the
    /// force-expansion feedback the interior obliges. Every per-argument loop (`call`,
    /// `new`, member-chain, and the wrapping helpers) shares this head so the
    /// route-then-emit ordering — and the respect-the-newline rule it encodes — lives in
    /// one place; only the separator, which genuinely differs per layout, stays at the
    /// call site.
    ///
    /// `interior` is the previous argument's stripped-paren interior as the loop printed it
    /// ([`Self::arg_paren_interior`]) — `None` for a frozen one, whose verbatim slice already
    /// carries it.
    pub(super) fn open_inter_arg_gap(
        &self,
        parts: &mut DocBuf,
        prev_arg: &ast::Expression<'_>,
        interior: Option<Span>,
        next_arg_start: u32,
    ) -> InterArgGap<'a> {
        let mut pc =
            PartitionedComments::for_routed_arg_gap(self, prev_arg.span().end, next_arg_start);
        if !self.paren_interior_separates_run(interior) {
            pc.emit_trailing_comments_around_comma(parts, self);
            return InterArgGap {
                forces_expansion: false,
                comments: pc,
            };
        }
        pc.lead_run_blocks_behind_interior(self);
        parts.push(self.d().text(","));
        self.push_element_share_and_run(parts, interior, ShareSite::NextElement, pc.trailing_run());
        InterArgGap {
            // An own-line interior comment is a sibling line, and an interior `//` the
            // spread defers must flush INSIDE the list — on a collapsed one the buffer
            // drains past the `)` and the `;`, re-binding the comment to the statement.
            // `paren_interior_separates_run` is exactly one of the two.
            forces_expansion: true,
            comments: pc,
        }
    }

    /// The stripped-paren interior of argument `i` of the list opening at `container_start`
    /// — `None` for anything but a spread, and for an argument a format-ignore directive
    /// FROZE ([`Self::args_frozen_span`]): its verbatim slice already printed the interior,
    /// so it has no share to emit and its run is an ordinary one. The argument loops ask it
    /// beside `build_joined_argument_doc`, which makes the same freeze decision.
    pub(super) fn arg_paren_interior(
        &self,
        container_start: u32,
        args: &[&ast::Expression<'_>],
        i: usize,
    ) -> Option<Span> {
        let interior = args[i].paren_interior()?;
        self.args_frozen_span(container_start, args, i)
            .is_none()
            .then_some(interior)
    }

    /// Whether the region between `prev_arg` and the next argument holds anything for
    /// [`Self::open_inter_arg_gap`] to emit.
    ///
    /// The ordinary gap `[prev_arg.end, next_arg_start)` is only half of it: the parent's
    /// share of a spread's stripped-paren interior lies *before* `prev_arg`'s end, where a
    /// plain gap scan cannot see it. A guard spelled as that scan alone routes the whole
    /// gap to a comment-free arm and drops the interior — the [`Printer::open_inter_arg_gap`]
    /// counterpart of the entry-gate hole [`any_comment_forces_expansion`] closes.
    pub(super) fn inter_arg_gap_has_comments(
        &self,
        prev_arg: &ast::Expression<'_>,
        next_arg_start: u32,
    ) -> bool {
        self.has_comments_to_emit_between(prev_arg.span().end, next_arg_start)
            || self.paren_interior_forces_expansion(prev_arg.paren_interior())
    }
}

/// What [`Printer::open_inter_arg_gap`] emitted, and what it obliges of the caller.
pub(super) struct InterArgGap<'a> {
    /// The routed gap, for the caller's separator policy and the next argument's leading
    /// comments.
    pub comments: PartitionedComments<'a>,
    /// Whether the gap's content cannot survive a collapsed argument list, so the caller
    /// must force its layout open. Always already true for the hard-broken layouts.
    pub forces_expansion: bool,
}

/// Emit an empty argument list into `parts`: the comments in the gap before the
/// `(` (`fn<string> /* c */()`), then the parens themselves — closed (`()`) or
/// enclosing their dangling comments (`fn(/* c */)`, and the broken form a line
/// comment forces).
///
/// `search_from` is where to look for the `(` (the position after the type
/// arguments, or after the callee when there are none) and `paren_close` the
/// position past the `)`. `prefix` is the open delimiter's doc — `(`, or `?.(` for
/// an optional call — built by the caller where its spelling is a literal.
///
/// Shared by the plain call/`new` path and the member-chain path so the empty-args
/// shape lives in one place: these two drifted apart once already, and the
/// inline-comment emission that drift preserved let a `//` comment swallow the `)`.
pub(super) fn build_empty_args_parens_doc(
    printer: &Printer<'_>,
    search_from: u32,
    paren_close: u32,
    prefix: DocId,
) -> DocId {
    let d = printer.d();
    // No `(` in the gap: a `new` written with no argument list at all synthesizes one
    // (`new (Foo /* c */)` → `new Foo /* c */()`), so the whole gap is pre-paren. The
    // shape is the found-paren case with the list's own position standing in for the
    // `(`, which is why it routes through the same two arms below rather than emitting
    // a bare `()` — doing that dropped every comment the callee's stripped grouping
    // parens held, at every callee kind.
    let paren_pos = printer
        .find_char_outside_comments(search_from, paren_close, b'(')
        .unwrap_or(paren_close);
    let parens = if paren_pos == paren_close {
        d.concat(&[prefix, d.text(")")])
    } else {
        printer.build_empty_parens_inline_with_comments_doc(paren_pos, paren_close, prefix)
    };
    // A **line** comment in this gap runs to end of line, so the argument list cannot
    // stay on it — left inline the `//` swallows the `()` and everything after it
    // (`call // c⏎()` → `call // c();`, losing the call itself). That is the whole rule
    // [`Printer::build_line_split_gap_doc`] states, shared with the callee→`?.` half an
    // optional call splits off ([`super::optional_callee_gap_doc`]) — the same position,
    // so the two cannot answer it differently.
    printer.build_line_split_gap_doc(search_from, paren_pos, parens)
}

//
// Comma-relative comment helpers
//

/// Find the comma position between two argument spans
///
/// Returns the absolute position of the separating comma in the source, or None
/// if not found. Commas inside comments are skipped: the gap between two argument
/// expressions only ever holds whitespace, comments, stripped parens, and the
/// separating comma — never strings or code — so skipping `/* … */` and `// …`
/// spans is enough to avoid mistaking a comment-internal comma (`a /* p, q */, b`)
/// for the separator.
#[inline]
fn find_comma_pos(source: &str, start: u32, end: u32) -> Option<usize> {
    // Byte scan is safe: `,`, `/`, `*`, `\n` are ASCII and never appear as a
    // UTF-8 continuation byte, so multibyte content in a comment can't false-match.
    let bytes = source.as_bytes();
    let (s, e) = (start as usize, end as usize);
    let mut i = s;
    while i < e {
        match bytes[i] {
            b',' => return Some(i),
            b'/' if i + 1 < e && bytes[i + 1] == b'*' => {
                // Skip a block comment, including its internal commas.
                i += 2;
                while i + 1 < e && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                    i += 1;
                }
                i += 2;
            }
            b'/' if i + 1 < e && bytes[i + 1] == b'/' => {
                // Skip a line comment to end of line.
                i += 2;
                while i < e && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            _ => i += 1,
        }
    }
    None
}

/// Find the effective start position for blank-line checking before an arg.
///
/// When grouping parens are stripped (e.g., `(expr)` → `expr`), the expression's
/// span starts after the `(`, but the source between a comma and the expression
/// may contain `(\n\t\texpr` — two newlines that look like a blank line.
/// This scans from `from` toward `to` and skips past any opening `(` that's the
/// first non-whitespace character, returning the position after it.
///
/// Tolerates an inverted range (`from > to`): parser-produced argument spans
/// are always ascending, but a synthetic tree mixing borrowed (host-span) and
/// minted (appendix-span) arguments can invert a gap — there is no paren to
/// skip in an empty or inverted gap, so `to` comes back unchanged.
#[inline]
pub(crate) fn skip_stripped_open_paren(source: &str, from: u32, to: u32) -> u32 {
    if from >= to {
        return to;
    }
    let slice = &source[from as usize..to as usize];
    for (i, byte) in slice.bytes().enumerate() {
        if byte == b'(' {
            return from + i as u32 + 1;
        }
        if !byte.is_ascii_whitespace() {
            break;
        }
    }
    to
}

/// Check if a comment is before the comma position
///
/// ⚠️ **Private, and it should stay that way.** The comma-relative reading is an internal
/// detail of the seam's own partition ([`PartitionedComments::for_routed_arg_gap`] and the
/// emitters over it); an argument layout that asks it *directly* is re-deriving which
/// argument a comment binds to, which is the shape of every bug this seam has produced.
/// Callers take the partition.
#[inline]
fn is_comment_before_comma(comment: &ast::Comment, comma_pos: usize) -> bool {
    (comment.span.start as usize) < comma_pos
}

/// Check if a comment is after the comma position — private for the reason on
/// [`is_comment_before_comma`].
#[inline]
fn is_comment_after_comma(comment: &ast::Comment, comma_pos: usize) -> bool {
    (comment.span.start as usize) > comma_pos
}

/// One argument gap's comments, as the two docs the break sits between: everything
/// through the comma (before-comma blocks, the comma, a stranded after-comma block, a
/// deferred `//`), and the next argument's leading run.
///
/// The caller supplies the separator between them — a bare `" "` in an inline state, a
/// `line` in a broken-out one — so both of
/// [`super::arg_wrapping::build_args_split_last`]'s states describe the gap with the same
/// two docs and can only differ in whether that separator breaks.
///
/// ⚠️ **The gap is the SEAM, so it takes the shared partition, not a same-line filter.**
/// Both halves are [`PartitionedComments::for_item_gap`]'s, routed by
/// [`PartitionedComments::route_after_comma_hugging_to_leading`] and emitted by the two
/// canonical emitters — the same pair [`Printer::open_inter_arg_gap`] hands the
/// comment-aware path, so the expand-last states cannot answer the seam differently. A
/// hand-rolled loop here filtered the gap on a same-line anchor read BACKWARD from the
/// previous argument, which is neither of the seam's questions: it dropped every comment
/// of a run the author wrote below the comma (`fn(a,⏎/* c1 */ /* c2 */ b, {})` lost
/// `/* c1 */`, and the broke-after authoring lost both — the run's separator is prettier's
/// soft `line`, which lives in [`Printer::push_leading_comment_run`] and cannot be
/// re-derived from a filter), and it flattened a **stranded** after-comma block onto the
/// next argument, contradicting the sanctioned divergence the comment-aware path prints
/// (`nonlast_arg_after_comma_block_stranded_prettier_divergence`).
///
/// **Which of the two gap forms to reach for.** This one and [`Printer::open_inter_arg_gap`]
/// are a pair over the same partition and the same emitters, and differ in what the caller
/// owes back:
///
/// - **This one** hands back the two docs and asks nothing. It does *not* emit a spread's
///   stripped-paren interior, nor demote a `//` behind an argument that already defers one.
///   Its callers are the layouts that never see either, because
///   [`any_comment_forces_expansion`] (via `paren_interior_forces_expansion`) routes
///   such a call to the comment-aware path before any of them is selected — the invariant
///   that makes the omission sound, and the thing to re-check before giving it a new caller.
/// - [`Printer::open_inter_arg_gap`] emits into the caller's buffer, covers both of those,
///   and returns a `forces_expansion` **obligation** the caller must act on. Take it in any
///   builder that can still choose to expand.
///
/// Folding this into that one would hand three call sites an obligation they would each have
/// to ignore, which is the shape of latent bug this seam keeps producing — so they stay two
/// entry points over one implementation rather than one entry point with a dead return.
pub(super) fn build_arg_gap_docs(
    printer: &Printer<'_>,
    arg_end: u32,
    next_arg_start: u32,
) -> (DocBuf, DocBuf) {
    let pc = PartitionedComments::for_routed_arg_gap(printer, arg_end, next_arg_start);

    let mut through_comma = DocBuf::new();
    pc.emit_trailing_comments_around_comma(&mut through_comma, printer);

    let mut leading = DocBuf::new();
    pc.emit_leading_comments_inline_aware(&mut leading, printer);

    (through_comma, leading)
}

//
// Inter-argument comment detection
//

/// Check if a call expression has comments between any of its arguments
pub(super) fn has_inter_argument_comments(
    call: &ast::CallExpression<'_>,
    printer: &Printer<'_>,
) -> bool {
    has_inter_argument_comments_slice(call.arguments, printer)
}

/// Check if there are comments between arguments in a slice
pub(super) fn has_inter_argument_comments_slice(
    arguments: &[&ast::Expression<'_>],
    printer: &Printer<'_>,
) -> bool {
    if arguments.len() < 2 {
        return false;
    }

    arguments
        .windows(2)
        .any(|pair| printer.has_comments_to_emit_between(pair[0].span().end, pair[1].span().start))
}

/// Prettier's **`anyArgEmptyLine`** (`print/call-arguments.js`): does any inter-argument gap
/// hold an author blank line?
///
/// The gaps are exactly [`has_inter_argument_comments_slice`]'s — its blank-line sibling, which
/// is why the two live together. In prettier this decides `allArgsBrokenOut()`, and it is asked
/// **above** `shouldExpandFirstArg` / `shouldExpandLastArg`, so a blank defeats every specialized
/// argument layout instead of being asked about after one has been chosen. Every tsv caller uses
/// it the same way — as a DECLINE conjunct on its layout arms — so the four call-like builders
/// (plain call, `new`, member-chain arguments, the curried-callee inline path) can't drift into
/// four answers to one question; they had already drifted into four spellings of the scan.
///
/// A blank needs two arguments to sit between, so this is `false` for a shorter list — which is
/// what makes the single-argument hug arms safe to leave above the callers' gates.
///
/// **Coarse over-check by design**: a raw scan of every gap, because it must catch a blank that
/// sits *past* a same-line trailing comment, which the emitters' per-gap `blank_scan_end` measure
/// would clamp away. The two intentionally differ and are not shared.
///
/// ⚠️ A caller whose construct prettier prints WITHOUT `printCallArguments` must exclude it
/// itself: a **test call** is joined by `printCallExpression` directly, so it has no
/// `anyArgEmptyLine` at all (see `call_formatting.rs`, which asks `is_test_call` — the callee, not
/// the layout).
pub(super) fn any_arg_empty_line(
    arguments: &[&ast::Expression<'_>],
    printer: &Printer<'_>,
) -> bool {
    arguments
        .windows(2)
        .any(|pair| printer.is_next_line_empty(pair[0].span().end, pair[1].span().start))
}

/// Check if the gap between two source positions contains only whitespace and parens,
/// with the first paren on the same line as `start`.
///
/// Detects stripped grouping parens: `/** @type {T} */ (\n\texpr)` → after stripping,
/// the gap between `*/` and `expr` is ` (\n\t` (whitespace + parens). The opening
/// paren is on the same line as the comment, so these should be treated as inline.
///
/// Returns false when the paren is on a different line from the comment:
/// `/* block */\n(expr)` → gap `\n(` has a newline before the paren → NOT inline.
pub(crate) fn has_stripped_paren_gap(source: &str, start: u32, end: u32) -> bool {
    let s = start as usize;
    let e = end as usize;
    if s >= e || e > source.len() {
        return false;
    }
    let gap = &source[s..e];
    // All bytes must be whitespace or parens
    if !gap
        .bytes()
        .all(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'(' | b')'))
    {
        return false;
    }
    // Must have a paren, and no newline before it (comment and paren on same line)
    match gap.bytes().position(|b| b == b'(' || b == b')') {
        Some(pos) => !gap.as_bytes()[..pos]
            .iter()
            .any(|&b| b == b'\n' || b == b'\r'),
        None => false,
    }
}

/// Check if comments between `start` and `next_code_pos` should force expansion.
///
/// Only truly standalone block comments — on a line of their own in SOURCE — force it. A
/// block comment glued to what follows is an inline leading comment (`arg1,⏎/* c */ arg2`)
/// and forces nothing: it is part of the next argument's line, and the group/fits mechanism
/// decides the layout.
///
/// "Standalone" is the shared classification ([`Printer::block_comment_owns_its_line`],
/// which carries the argument) — read of the SOURCE on both sides, never of `start` (a
/// previous argument's end, or the `(`) and never of `next_code_pos`. The two positions
/// only look alike: the comma the author wrote between them belongs to neither span.
///
/// It subsumes what [`Printer::comment_hugs_next_item`] answered here: that predicate's
/// stripped-paren arm requires the `(` on the comment's line, which is the hug reading
/// already. It stays the anchor where a RUN is walked backwards comment by comment (the
/// emitters), a different question with a different next.
pub(super) fn should_force_expansion_for_comments(
    printer: &Printer<'_>,
    start: u32,
    next_code_pos: u32,
) -> bool {
    // Line comments always force expansion
    if printer.has_line_comments_between(start, next_code_pos) {
        return true;
    }
    // Check if any block comment is truly standalone (not inline with the next code).
    // `next_code_pos` bounds the gap, so an item always follows: every caller scans either
    // the `(`→first-argument gap or an inter-argument one, and the trailing position past
    // the last argument belongs to `Printer::has_own_line_block_comment_before_closer`.
    for comment in printer.comments_to_emit_between(start, next_code_pos) {
        if comment.is_block && printer.block_comment_owns_its_line(comment, true) {
            return true;
        }
    }
    false
}

/// Prettier's **`args.some(hasComment)`** for the argument list: does any comment attach to
/// an argument, i.e. sit in the `(`→first gap, an inter-argument gap, or the last→`)` one?
///
/// The gaps are the whole question — a comment strictly INSIDE an argument (in a callback's
/// body, between an array literal's own brackets) is attached to a node further down and
/// answers `false` here, which is what prettier's `hasComment(arg)` reports for it too.
/// **On page**, since an owned annotation glued to an argument is a comment prettier sees.
pub(super) fn any_arg_gap_has_comment_on_page(
    arguments: &[&ast::Expression<'_>],
    printer: &Printer<'_>,
    paren_open: u32,
    call_end: u32,
) -> bool {
    let mut prev_end = paren_open;
    for arg in arguments {
        if printer.has_comments_on_page_between(prev_end, arg.span().start) {
            return true;
        }
        prev_end = arg.span().end;
    }
    printer.has_comments_on_page_between(prev_end, call_end)
}

/// Check if any comments in a call's arguments force expansion.
///
/// Returns true for line comments or standalone block comments (on their own line,
/// not inline with either neighbor). Inline block comments do not force expansion.
pub(super) fn any_comment_forces_expansion(
    call: &ast::CallExpression<'_>,
    span: Span,
    printer: &Printer<'_>,
    paren_open: u32,
) -> bool {
    any_comment_forces_expansion_slice(call.arguments, printer, paren_open, span.end)
}

/// [`any_comment_forces_expansion`] over an argument slice, for the builder that holds a
/// `NewExpression` rather than a `CallExpression` — prettier prints both through one
/// `printCallArguments`, so they must ask this question with one predicate. The `new` twin
/// asked [`has_inter_argument_comments_slice`] instead, which counts a same-line inline
/// block (`new A(a /* c */, () => {…})`) and so broke out a list prettier keeps hugged.
pub(super) fn any_comment_forces_expansion_slice(
    arguments: &[&ast::Expression<'_>],
    printer: &Printer<'_>,
    paren_open: u32,
    call_end: u32,
) -> bool {
    if arguments.is_empty() {
        return false;
    }

    // Check leading comments before first arg
    let first_arg_start = arguments[0].span().start;
    if printer.has_comments_to_emit_between(paren_open, first_arg_start)
        && should_force_expansion_for_comments(printer, paren_open, first_arg_start)
    {
        return true;
    }

    // Check inter-argument and trailing comments
    for (i, arg) in arguments.iter().enumerate() {
        // A comment a spread's stripped grouping parens left behind (`...(x⏎/* c */)`,
        // `...(x // c⏎)`) sits BEFORE the argument's own end, so the gap scan below cannot
        // see it — yet it is exactly what forces the list open, either because it needs a
        // line of its own or because its deferred `//` would otherwise flush past the
        // call's `)`. Asked per argument: a non-last spread's interior needs the expansion
        // just as much as the last one's.
        if printer.paren_interior_forces_expansion(arg.paren_interior()) {
            return true;
        }

        let arg_end = arg.span().end;
        let next_boundary = if i < arguments.len() - 1 {
            arguments[i + 1].span().start
        } else {
            call_end
        };

        if !printer.has_comments_to_emit_between(arg_end, next_boundary) {
            continue;
        }

        // Line comments or standalone block comments force expansion.
        // Inline block comments (same line as previous arg or inline with next arg)
        // do not force expansion — the group/fits mechanism decides layout.
        //
        // The LAST argument's gap runs to the `)`, where no item is left to lead, so the
        // closer sharing a comment's line is not glue — the trailing position's own
        // predicate ([`Printer::has_own_line_block_comment_before_closer`], which carries
        // that argument). `should_force_expansion_for_comments` states the same rule for a
        // gap an item DOES follow, and the two must agree with what
        // `emit_last_arg_trailing_comments` trails: a gate that opens the list around a
        // comment the emitter puts back on the argument's line opens it around nothing.
        let forces = if i < arguments.len() - 1 {
            should_force_expansion_for_comments(printer, arg_end, next_boundary)
        } else {
            printer.has_line_comments_between(arg_end, next_boundary)
                || printer.has_own_line_block_comment_before_closer(arg_end, next_boundary)
        };
        if forces {
            return true;
        }
    }

    false
}

/// Check if the last arg has leading or trailing comments.
///
/// Matches prettier's shouldExpandLastArg checks:
///   `!hasComment(lastArg, CommentCheckFlags.Leading) &&
///    !hasComment(lastArg, CommentCheckFlags.Trailing)`
///
/// Leading = comments after the comma (or opening paren for single-arg),
/// before the last arg's span.
/// Trailing = comments after the last arg's span, before the closing paren.
///
/// Used to prevent expand-last-arg layout when the last arg has comments,
/// since prettier's shouldExpandLastArg returns false in that case.
pub(super) fn last_arg_has_comments(
    arguments: &[&ast::Expression<'_>],
    printer: &Printer<'_>,
    call_end: u32,
    paren_open: u32,
) -> bool {
    let Some(last) = arguments.last() else {
        return false;
    };
    let last_start = last.span().start;

    // Leading: comments before last arg. Counts owned comments — this is a pure layout
    // gate (it only disables the expand-last hug), and a bundler annotation leading the
    // last argument is on the page just like any other leading comment, so prettier's
    // `shouldExpandLastArg` refuses the hug for it too.
    if arguments.len() >= 2 {
        // Multi-arg: check after comma
        let prev_end = arguments[arguments.len() - 2].span().end;
        if let Some(cp) = find_comma_pos(printer.source, prev_end, last_start)
            && printer.has_comments_on_page_between((cp + 1) as u32, last_start)
        {
            return true;
        }
    } else {
        // Single-arg: the whole `paren_open`→argument window. `paren_open` is where the
        // argument side OPENS (`CalleeGap::paren_open`) — the callee's end on an unsplit gap,
        // where a callee→`(` comment the printer relocates into the list sits; never the
        // `(` itself there, so skipping a byte from it skipped a comment glued to the
        // callee (`a.b/* c⏎d */(() => e())` hugged on pass 1, then expanded once the
        // comment led the argument).
        if printer.has_comments_on_page_between(paren_open, last_start) {
            return true;
        }
    }

    // Trailing: comments after last arg, before closing paren
    printer.has_comments_to_emit_between(last.span().end, call_end)
}

/// Check if the first arg has any comments (leading or trailing).
///
/// Matches prettier's shouldExpandFirstArg check: `!hasComment(firstArg)`
///
/// Leading = comments between opening paren and the first arg's span.
/// Trailing = comments between the first arg's span end and the comma.
///
/// Used to prevent expand-first-arg layout when the first arg has comments,
/// since prettier's shouldExpandFirstArg returns false in that case.
///
/// **on page**, like its twin [`last_arg_has_comments`]: this only disables the
/// expand-first hug — a pure layout gate — and a bundler annotation leading the first
/// argument is on the page just like any other leading comment, so prettier's
/// `shouldExpandFirstArg` refuses the hug for it too.
pub(super) fn first_arg_has_any_comments(
    arguments: &[&ast::Expression<'_>],
    printer: &Printer<'_>,
    paren_open: u32,
) -> bool {
    if arguments.is_empty() {
        return false;
    }
    let first = &arguments[0];

    // Leading: comments between paren and first arg
    if printer.has_comments_on_page_between(paren_open, first.span().start) {
        return true;
    }

    // Trailing: the run the FOLLOWING GAP binds to this argument — asked as the gap's own
    // emitter asks it ([`PartitionedComments::for_item_gap`] + the hugging route), so the
    // gate and the seam cannot disagree about which argument a comment belongs to.
    //
    // ⚠️ **The before-comma half is not the whole run.** Reading only `[first_end, comma)`
    // misses a block the author STRANDED after the comma (`() => {…}, /* c */⏎b`), which
    // prettier binds as this argument's trailing comment (nothing follows it on its line)
    // and which therefore refuses the hug — tsv took the hug instead and, because the
    // inline tail emits only what leads the next argument, DROPPED the comment outright.
    // The routing step is what keeps the hugging spelling (`}, /* c */ b`) out of the run:
    // there the block leads the next argument, prettier's `hasComment(firstArg)` is false,
    // and the hug is correct.
    if let Some(second) = arguments.get(1) {
        let gap =
            PartitionedComments::for_routed_arg_gap(printer, first.span().end, second.span().start);
        return gap.has_trailing_comments();
    }

    false
}

/// Check if there are trailing line comments on any arguments
///
/// A trailing comment is one that appears after an argument's expression,
/// either between the arg and its comma, or between the last arg and the closing paren.
/// Example: `fn(a && b, // trailing)` - the `// trailing` is a trailing comment on `a && b`
pub(super) fn has_trailing_comments_on_args(
    call: &ast::CallExpression<'_>,
    span: Span,
    printer: &Printer<'_>,
) -> bool {
    has_trailing_line_comments_slice(call.arguments, span.end, printer)
}

/// Check if there are trailing line comments on any arguments (generic version)
///
/// Used by both CallExpression and NewExpression.
pub(super) fn has_trailing_line_comments_slice(
    arguments: &[&ast::Expression<'_>],
    call_span_end: u32,
    printer: &Printer<'_>,
) -> bool {
    has_trailing_comments_slice_impl(arguments, call_span_end, |start, end| {
        printer.has_line_comments_between(start, end)
    })
}

/// Emit the leading comments between `(` and the first argument, split across the
/// two lines they can land on: `paren_line` rides the `(` line, `parts` leads the
/// first argument.
///
/// Own-line comments always lead the first argument. A run with a comment trailing `(`
/// goes one of two ways, and the split is the run's *kind*, not each comment's:
///
/// - **Block-only** — the whole gap is one leading run
///   ([`PartitionedComments::emit_unpulled_gap`]): a space where the author glued a pair
///   (`fn(/* c */ a)`, so a call that fits stays on one line), the soft `line` where a comment
///   broke after (`fn(/* c */⏎a)` — its own line when the argument list breaks, the glued
///   bytes when it collapses), and a blank-preserving hardline for an author blank.
/// - **Any line comment in the run** — the whole run stays on the `(` line, in source
///   order. A `//` runs to EOL, so it cannot ride the argument's line; keeping it where
///   the author put it is tsv's sanctioned divergence (prettier relocates it to its own
///   line) — see `docs/conformance_prettier_ts_comments.md` §Comment relocation (Call
///   open paren `(`). Taking the run whole is what keeps a preceding block from jumping
///   past it: emitting the block inline and the line comment on the `(` line would
///   REVERSE the authored pair.
///
/// A non-empty `paren_line` obliges the caller to hard-break the call —
/// [`wrap_call_with_hard_breaks_paren_line`](super::arg_wrapping::wrap_call_with_hard_breaks_paren_line)
/// is that wrap. Otherwise the `(` line's `//` swallows the arguments that follow it.
///
/// Several per-argument printer loops only emit leading comments for args `1..n` (via
/// the previous arg's gap), so the first arg's leading comment must be emitted
/// explicitly or it's dropped.
///
/// **Why the split is `has_trailing_line` here and
/// `Printer::delimiter_line_comment_prefix`'s wider conjunction elsewhere** — the two are
/// the same rule read at different points, not drift (`docs/comments.md` §The
/// delimiter-line question). Both say *pull onto the delimiter's line only when the
/// container is breaking anyway; otherwise let the block hug the first element*. The list
/// family has to derive "is it breaking?" from the gap
/// (`should_force_expansion_for_comments`), and so do the call family's force-expanded
/// builders, which spell that same conjunction over
/// [`PartitionedComments::has_trailing_comments`]. This emitter runs on the paths where
/// the call may still collapse, so the only thing that can force the break is a `//` in
/// the run itself — and a block-only run must NOT be pulled, or a call that would have fit
/// is broken by the pull.
pub(super) fn emit_first_arg_leading_comments(
    printer: &Printer<'_>,
    paren_line: &mut DocBuf,
    parts: &mut DocBuf,
    paren_open: u32,
    first_arg_start: u32,
) {
    if !printer.has_comments_to_emit_between(paren_open, first_arg_start) {
        return;
    }
    let pc = PartitionedComments::new(printer, paren_open, first_arg_start);
    if pc.has_trailing_line() {
        pc.emit_trailing_comments(paren_line, printer);
        pc.emit_leading_comments_inline_aware(parts, printer);
    } else {
        pc.emit_unpulled_gap(parts, printer);
    }
}

/// Emit the comments between the LAST argument and `)` — the closing counterpart to
/// [`emit_first_arg_leading_comments`], and the other half of what a per-argument loop
/// owes beyond its interior gaps (see `docs/comments.md` §The element-comma seam).
///
/// A loop whose gap lookup is guarded by `i < len - 1` has no emitter for this region at
/// all, so everything an author parked after the last argument is DROPPED.
///
/// Two regions, and they must **partition**: the parent's share of the last argument's
/// own stripped-paren interior ([`Printer::push_paren_interior_own_line_comments`] — the
/// own-line comments a spread's doc deliberately leaves for its parent), and the
/// ordinary gap between the argument's end and `)`. The share goes first, in source
/// order, and the gap's trailing run follows it on the line
/// [`Printer::push_element_share_and_run`] names. The gap keeps the plain
/// `arg.span().end` anchor: widening it to reach the interior is what claims the spread's
/// own share a second time.
///
/// The gap is partitioned with [`PartitionedComments::for_closer_gap`], not
/// [`PartitionedComments::new`]: it holds the list's own **comma**, which under
/// `trailingComma: 'none'` is never re-emitted, so a comment the author wrote after a
/// comma pushed onto its own line (`fn(a⏎, /* c */)`) trails the argument and has no line
/// of its own to keep. The delimiter-line reading calls it own-line and dangles it below
/// the argument, force-opening a call that fits (`docs/comments.md` §Own-line-ness is a
/// SOURCE question).
///
/// `interior` is the argument's stripped-paren interior as the loop printed it
/// ([`Printer::arg_paren_interior`]).
pub(super) fn emit_last_arg_trailing_comments(
    printer: &Printer<'_>,
    parts: &mut DocBuf,
    last_arg: &ast::Expression<'_>,
    interior: Option<Span>,
    paren_close: u32,
) {
    let arg_end = last_arg.span().end;
    // Every argument list reaching these builders pays this call, comments or not, so
    // skip the partition on the common empty gap (same guard as
    // `emit_first_arg_leading_comments`). Both emits `PartitionedComments` would run
    // walk only its own buckets, so an empty range is already a no-op.
    let pc = printer
        .has_comments_to_emit_between(arg_end, paren_close)
        .then(|| PartitionedComments::for_closer_gap(printer, arg_end, paren_close));
    printer.push_element_share_and_run(
        parts,
        interior,
        ShareSite::Closer,
        pc.iter().flat_map(PartitionedComments::trailing_run),
    );
    if let Some(pc) = &pc {
        pc.emit_dangling_comments(parts, printer);
    }
}

/// Check if there are trailing comments (line OR block) on any arguments
///
/// Used when we need to detect ALL trailing comments, not just line comments.
/// This is important for new expressions where block comments after arguments
/// can also be lost if not handled properly.
pub(super) fn has_trailing_comments_slice(
    arguments: &[&ast::Expression<'_>],
    call_span_end: u32,
    printer: &Printer<'_>,
) -> bool {
    has_trailing_comments_slice_impl(arguments, call_span_end, |start, end| {
        printer.has_comments_to_emit_between(start, end)
    })
}

/// Shared implementation for checking trailing comments on arguments.
#[inline]
fn has_trailing_comments_slice_impl<F>(
    arguments: &[&ast::Expression<'_>],
    call_span_end: u32,
    has_comments: F,
) -> bool
where
    F: Fn(u32, u32) -> bool,
{
    if arguments.is_empty() {
        return false;
    }

    for (i, arg) in arguments.iter().enumerate() {
        let arg_end = arg.span().end;
        let next_boundary = if i < arguments.len() - 1 {
            arguments[i + 1].span().start
        } else {
            call_span_end
        };

        if has_comments(arg_end, next_boundary) {
            return true;
        }
    }

    false
}

/// Partitioned comments between two positions
///
/// Separates comments into a run that TRAILS what precedes the gap and one that LEADS
/// what follows it:
/// - `trailing_line`: the run's line comment — at most ONE, structurally: a `//` runs to
///   end of line, so no second comment can occupy the line it trails on, and every
///   constructor's walk stops claiming at the first `//`
///   ([`Printer::closer_trailing_comment_run`] and its inter-item twin by their
///   `take_while`; the delimiter reading because a second same-line comment would sit
///   inside the first's text)
/// - `trailing_block`: the run's block comments
/// - `leading`: everything past the run
///
/// Uses `SmallVec` to avoid heap allocations for the common case (0-2 comments per range).
///
/// ⚠️ **The three constructors ask different questions, and the gap's shape picks one.**
/// The split between them is where the gap's `start` sits: past a `(` it is an ITEM's end,
/// and the claim reads the SOURCE; at the `(` itself it is the delimiter's.
/// [`Self::for_item_gap`] — an **inter-item** gap — takes its split from
/// [`Printer::trailing_comment_run`], the same walk the object literal, both destructuring
/// patterns, the enum and the array literal partition their element→comma gaps with, so
/// the call family cannot answer the seam differently. [`Self::for_closer_gap`] — a
/// **last-item→`)`** gap, whether or not a comma sits in it — takes
/// [`Printer::closer_trailing_comment_run`], which differs from that walk on exactly one
/// thing (a `//` written against the comma `trailingComma: 'none'` deletes).
/// [`Self::new`] — a
/// **delimiter** gap (`(`→first argument) — keeps the same-line
/// reading of `tsv_lang::ClassifiedComments`, shared with the ternary
/// (`conditional.rs`) and member-chain (`chain/builder/helpers.rs`) gap printers, whose
/// gaps likewise hold an operator or a `.` rather than a comma. Each constructor's own
/// doc states why the other's reading is wrong for it.
///
/// This type adds the call-argument-specific emission (`emit_*`) and comma-relative
/// helpers on top; only the emission differs per shape, which is intentional.
pub(crate) struct PartitionedComments<'a> {
    pub trailing_line: Option<&'a ast::Comment>,
    pub trailing_block: SmallVec<[&'a ast::Comment; 2]>,
    pub leading: SmallVec<[&'a ast::Comment; 2]>,
    /// A run displaced past the comma by the previous argument's stripped-paren interior
    /// that LEADS the next argument ([`Self::lead_run_blocks_behind_interior`]), printed
    /// ahead of `leading` by [`Self::emit_leading_comments_inline_aware`].
    leads: SmallVec<[&'a ast::Comment; 2]>,
    /// Whether the previous argument's run follows its stripped-paren interior — the
    /// comma then sits against that argument, which moves where an author blank before the
    /// next argument is measured from ([`Self::has_blank_line_in_gap`]).
    behind_interior: bool,
    /// The gap the comments were partitioned over: `start` is the preceding element's
    /// end, `end` the following element's start. The emit/query methods operate on
    /// this gap (comma scan, blank-line check, dangling-comment base), so they read
    /// these rather than re-receiving the bounds the caller already passed to `new`.
    start: u32,
    end: u32,
}

impl<'a> PartitionedComments<'a> {
    /// Partition comments in a range based on their position relative to `start`
    ///
    /// Comments on the same line as `start` are "trailing" (they follow content on that line).
    /// Comments on subsequent lines are "leading" (they precede content on the next line).
    ///
    /// ⚠️ **The DELIMITER-LINE reading**, and only that: "does the comment sit on the
    /// anchor's line?" — exactly the question a `(`→first-item gap asks, where the anchor
    /// IS the delimiter (`docs/comments.md` §The delimiter-line question). It is blind to
    /// the two kinds of text no item span covers — the list's own **comma** and a stripped
    /// paren shell's `)` — so it must not be used where the answer decides which ITEM a
    /// comment binds to. An **inter-item** gap takes [`Self::for_item_gap`] and a
    /// **last-item→`)`** gap [`Self::for_closer_gap`]: a comment behind a stripped `)`, or
    /// behind a comma the author pushed onto its own line, still trails that item and this
    /// reading would leave it unclaimed.
    ///
    /// ⚠️ **A comma-less gap is no exception, and reading it as one was a bug.** The two
    /// comma-less single-argument shapes — `require('x')` and a `import(…)` with no options
    /// — were held here on the argument that their gap holds nothing the two readings
    /// disagree about. It holds one thing: another comment's `*/`. A comment the author
    /// glued behind it follows content on its line but not on the ARGUMENT's, so this
    /// reading dangled it below the argument and split a pair written as one. Every gap
    /// past a `(` now takes an item constructor, which leaves this one purely the
    /// **delimiter**-gap reading its name describes.
    pub(crate) fn new(printer: &Printer<'a>, start: u32, end: u32) -> Self {
        // Share the same-line/later-line classification with the chain and ternary
        // gap printers (`tsv_lang::ClassifiedComments`). `leading` keeps the two
        // own-line buckets merged in source order — the inline-aware emitter and its
        // JSDoc-cast detection rely on the authored order. The walk starts at the
        // printer's window-reading index, as every gap walk does.
        let classified = tsv_lang::ClassifiedComments::from_index(
            printer.comment_free_gap.comments(),
            printer.first_index_between(start, end),
            start,
            end,
            printer.source.as_bytes(),
            printer.comment_line_breaks,
        );
        let leading = classified.leading_in_source_order();
        // ≤ 1 by construction: a second same-line comment would sit inside the first
        // `//`'s own text, so it cannot exist as a token.
        debug_assert!(classified.trailing_line.len() <= 1);
        Self {
            trailing_line: classified.trailing_line.first().copied(),
            trailing_block: classified.trailing_block,
            leading,
            leads: SmallVec::new(),
            behind_interior: false,
            start,
            end,
        }
    }

    /// Partition an **inter-item** gap — one holding the list's own comma — into the
    /// previous item's **trailing** run and the next item's **leading** one.
    ///
    /// The split is [`Printer::trailing_comment_run`]: the gap's leading PREFIX of
    /// comments that follow content on their line in SOURCE, ending at the first `//`.
    /// Everything past the run leads the next argument, so the two answers partition the
    /// gap exactly once (`docs/comments.md` §The element-comma seam) — the same walk the
    /// object literal, both destructuring patterns, the enum and the array literal use, so
    /// the call family cannot answer the seam differently.
    ///
    /// ⚠️ **The reading is of the source, never of `start`** (the previous argument's
    /// end), and the two differ by exactly the text no argument span covers: the list's
    /// own **comma**, which the author can push onto its own line (`fn(a⏎, /* c */⏎b)`),
    /// and a stripped paren shell's `)`. An `is_same_line(start, …)` classification calls a
    /// comment glued to either one own-line, which both lifts it off the comma's line and
    /// force-expands a list that fits — a third fixed point neither the bare authoring nor
    /// prettier produces.
    ///
    /// ⚠️ **Not for a delimiter gap.** With `start` at the `(`/`[`, "follows content on
    /// its line" is a different question from "sits on the delimiter's line": an elision's
    /// comma or a leading `,` puts content ahead of a comment two lines below the opener,
    /// which this would call trailing — pulling it onto the delimiter's line *and* leaving
    /// it for the first item's leading run to print again. Use [`Self::new`] there.
    ///
    /// ⚠️ **Private: the unrouted partition is not a state an argument gap is ever in.**
    /// Its one caller is [`Self::for_routed_arg_gap`]; see there for why the two steps are
    /// one. A comma-less gap takes [`Self::for_closer_gap`], not this.
    fn for_item_gap(printer: &Printer<'a>, start: u32, end: u32) -> Self {
        Self::from_trailing_run(
            printer.trailing_comment_run(start, end),
            printer,
            start,
            end,
        )
    }

    /// Partition an **argument** gap and route it — [`Self::for_item_gap`] followed by
    /// [`Self::route_after_comma_hugging_to_leading`].
    ///
    /// ⚠️ **The two are one step, never two.** The routing is the whole difference between
    /// an after-comma block that HUGS the next argument (it leads that argument, and both
    /// formatters agree) and one the author STRANDED on the comma line (it trails it — the
    /// sanctioned relocation divergence). A caller that partitions without routing turns
    /// every hugging comment into a stranded one and silently moves it: same bytes, a
    /// different position, nothing dropped and no gate firing. So both halves are **private
    /// to this file** and this is the only argument-gap constructor — the unrouted state is
    /// unconstructible rather than merely discouraged.
    ///
    /// Every argument gap that HOLDS A COMMA takes this. The comma-less spellings — a last
    /// argument's gap to the `)`, a single argument — take [`Self::for_closer_gap`], whose
    /// trailing run follows the closer's own rule.
    pub(super) fn for_routed_arg_gap(printer: &Printer<'a>, start: u32, end: u32) -> Self {
        let mut pc = Self::for_item_gap(printer, start, end);
        pc.route_after_comma_hugging_to_leading(printer);
        pc
    }

    /// Partition a **last-item→`)`** gap — the one that holds the comma
    /// `trailingComma: 'none'` deletes — into the argument's **trailing** run and the
    /// **dangling** comments below it.
    ///
    /// [`Printer::closer_trailing_comment_run`] rather than the inter-item walk: a block
    /// takes the same source reading (the deleted comma is still content the author wrote
    /// against), while a `//` written after a comma the author gave its own line keeps
    /// that line — the sanctioned divergence that walk's doc carries. [`Self::new`]'s
    /// delimiter reading answers neither: it calls a comma-glued block own-line and
    /// dangles it below the argument, force-opening a call that fits.
    ///
    /// Taken by every last-argument gap, **including the comma-less ones** — `require('x')`
    /// and a `import(…)` with no options. The comma is not what makes the source reading
    /// necessary, only the loudest byte that needs it: a preceding comment's `*/` is text no
    /// argument span covers too, and a comment glued behind one is exactly as mis-read.
    pub(crate) fn for_closer_gap(printer: &Printer<'a>, item_end: u32, end: u32) -> Self {
        Self::from_trailing_run(
            printer.closer_trailing_comment_run(item_end, end),
            printer,
            item_end,
            end,
        )
    }

    /// Split a gap at its trailing RUN: the run's blocks and its (at most one) line
    /// comment trail, everything past it leads. Shared by the two item-gap constructors so
    /// only the run's own rule differs between them.
    fn from_trailing_run(
        run: impl Iterator<Item = &'a ast::Comment>,
        printer: &Printer<'a>,
        start: u32,
        end: u32,
    ) -> Self {
        let mut trailing_line: Option<&'a ast::Comment> = None;
        let mut trailing_block: SmallVec<[&'a ast::Comment; 2]> = SmallVec::new();
        let mut run_end = start;
        for comment in run {
            if comment.is_block {
                trailing_block.push(comment);
            } else {
                // The run walk stops claiming at the first `//`, so this assigns at
                // most once.
                debug_assert!(trailing_line.is_none());
                trailing_line = Some(comment);
            }
            run_end = comment.span.end;
        }
        let leading = printer.comments_to_emit_between(run_end, end).collect();
        Self {
            trailing_line,
            trailing_block,
            leading,
            leads: SmallVec::new(),
            behind_interior: false,
            start,
            end,
        }
    }

    /// Respect-the-newline split for a non-last argument gap: move after-comma block
    /// comments that **hug** the next argument out of `trailing_block` and into
    /// `leading`, so they render as a leading comment on the next argument (`C`).
    /// A **stranded** after-comma block (a newline separates it from the next argument)
    /// stays in `trailing_block` and renders after the comma on the same line (`A`).
    ///
    /// The author's placement is preserved in both cases: a comment hugging the next
    /// arg leads it; a comment left alone on the comma line stays there. Callers then
    /// emit `trailing_block` (before-comma blocks + stranded after-comma) via
    /// [`Self::emit_trailing_comments_around_comma`], the line break, then `leading` (own-line
    /// comments + hugged after-comma) via [`Self::emit_leading_comments_inline_aware`] — so the
    /// rule lives here once and every argument path inherits it.
    fn route_after_comma_hugging_to_leading(&mut self, printer: &Printer<'_>) {
        let Some(comma_pos) = find_comma_pos(printer.source, self.start, self.end) else {
            return;
        };
        let mut kept: SmallVec<[&'a ast::Comment; 2]> = SmallVec::new();
        for comment in self.trailing_block.drain(..) {
            if is_comment_after_comma(comment, comma_pos)
                && printer.comment_hugs_next_item(comment.span.end, self.end)
            {
                // Hugs the next arg → leads it. Source order holds: the hug sits on the
                // next arg's line, after any own-line leading comments, so appending keeps
                // `leading` sorted.
                self.leading.push(comment);
            } else {
                kept.push(comment);
            }
        }
        self.trailing_block = kept;
    }

    pub(crate) fn has_trailing_line(&self) -> bool {
        self.trailing_line.is_some()
    }

    /// Whether a **last-item→`)`** gap's comments force the parens open — asked of a
    /// [`Self::for_closer_gap`] partition, whose emitter is [`Self::emit_last_arg_comments`].
    ///
    /// Two things need a line the flat layout cannot give them: a `//` runs to end of line
    /// and would swallow the `)`, and an own-line comment (everything the trailing run did
    /// not claim, which is what `leading` holds here) keeps the line the author gave it via
    /// a `hardline` that a flat group has nowhere to put.
    ///
    /// One question, one predicate: the gate and the emitter partition the same gap, so a
    /// gate that opened the parens around a comment the emitter puts back on the item's
    /// line would open them around nothing.
    pub(super) fn forces_closer_break(&self) -> bool {
        self.has_trailing_line() || !self.leading.is_empty()
    }

    /// The gap's trailing RUN in source order — its same-line blocks, then the (at most
    /// one) same-line `//` the run ends at — for [`Printer::push_element_share_and_run`],
    /// which renders it behind an argument's stripped-paren interior.
    pub(super) fn trailing_run(&self) -> impl Iterator<Item = &'a ast::Comment> + '_ {
        self.trailing_block
            .iter()
            .chain(self.trailing_line.iter())
            .copied()
    }

    /// Re-partition a NON-last argument gap whose run follows the argument's stripped-paren
    /// interior ([`Printer::paren_interior_separates_run`]): the comma is emitted against
    /// the argument, ahead of the interior, so every block of the run is past it. A run
    /// that LEADS the next argument ([`Printer::run_leads_next_item`] — blocks with no
    /// author line break or blank after them, the stripped `)` counted as absent:
    /// `fn(...(b⏎/* i */⏎) /* t */, c)` → `...b,⏎/* i */⏎/* t */ c`) moves to
    /// [`Self::emit_leading_comments_inline_aware`]; the rest — a run ending in a `//`, a
    /// block on a line the author ended after it, blocks above an author blank — stays
    /// behind the interior ([`Printer::push_element_share_and_run`]).
    pub(super) fn lead_run_blocks_behind_interior(&mut self, printer: &Printer<'_>) {
        self.behind_interior = true;
        if self.trailing_line.is_none()
            && printer.run_leads_next_item(
                &self.trailing_block,
                find_comma_pos(printer.source, self.start, self.end).map(|c| c as u32),
                self.end,
            )
        {
            self.leads = std::mem::take(&mut self.trailing_block);
        }
    }

    /// Whether this gap follows the previous argument's stripped-paren interior
    /// ([`Self::lead_run_blocks_behind_interior`]).
    pub(super) fn is_behind_interior(&self) -> bool {
        self.behind_interior
    }

    pub(crate) fn has_trailing_block(&self) -> bool {
        !self.trailing_block.is_empty()
    }

    /// Whether anything at all sits on the opening delimiter's line — exactly what
    /// [`Self::emit_trailing_comments`] would emit, asked ahead of emitting it.
    ///
    /// The delimiter-line question every argument builder opens with: a non-empty run
    /// has to be injected after the `(` rather than led onto the first argument, and
    /// the run is taken WHOLE (both buckets) or an authored `/* b */ // c` pair comes
    /// back reversed. Paired with the emitter so the two can't answer differently.
    ///
    /// Conjoined with `should_force_expansion_for_comments` at every force-expanded call
    /// site, this **is** `Printer::delimiter_line_comment_prefix`'s `pull` — the list
    /// family's spelling of the same rule (`docs/comments.md` §The delimiter-line
    /// question). That conjunction is [`Self::pulls_to_delimiter_line`], so the two stay in
    /// step by construction rather than by review.
    pub(super) fn has_trailing_comments(&self) -> bool {
        self.has_trailing_block() || self.has_trailing_line()
    }

    /// The delimiter-line PULL as one predicate: something sits on the delimiter's line
    /// ([`Self::has_trailing_comments`]) AND a comment in this gap is what forces the
    /// container open (`should_force_expansion_for_comments`). Asked by the force-expanded
    /// builders (`new`, the member chain) so the two halves cannot be spelled over
    /// different ranges — both read the gap this partition was already built over, leaving
    /// the caller nothing to pass and so nothing to pass inconsistently.
    ///
    /// The plain call's builder spells the same conjunction with the `force_expansion` flag
    /// it independently needs, and the list family's
    /// `Printer::delimiter_line_comment_prefix` ORs the object literal's extra arm onto
    /// this one. The collapse-capable path ([`emit_first_arg_leading_comments`]) asks the
    /// narrower [`Self::has_trailing_line`] instead — load-bearing, not drift; see its doc.
    pub(crate) fn pulls_to_delimiter_line(&self, printer: &Printer<'_>) -> bool {
        self.has_trailing_comments()
            && should_force_expansion_for_comments(printer, self.start, self.end)
    }

    /// Emit a fired pull: the delimiter-line run, then the author blank that sat BELOW it.
    ///
    /// The two are one step. The pull moves the comment's line, not its membership, so the
    /// blank the author left under it rides along ([`Printer::push_delimiter_glued_blank`]
    /// carries that rule) — and every delimiter-line
    /// pull in the call and list families emits through here rather than re-deriving half
    /// of it.
    pub(crate) fn emit_delimiter_line_pull(&self, parts: &mut DocBuf, printer: &Printer<'_>) {
        self.emit_trailing_comments(parts, printer);
        if let Some(pulled_end) = self.trailing_end() {
            printer.push_delimiter_glued_blank(parts, pulled_end, self.end);
        }
    }

    /// Emit a gap whose delimiter-line pull fired: the pull onto `paren_line`
    /// ([`Self::emit_delimiter_line_pull`]), then everything below it leading the first item
    /// through the shared leading emitter ([`Self::emit_leading_comments_inline_aware`]) —
    /// the call family's force-expanded builders all take this pair.
    ///
    /// ⚠️ **The two halves are one step.** A builder that pulled through the shared emitter
    /// and printed the rest by hand — each comment followed by a bare `hardline` — split a
    /// glued pair below the pulled comment and ate an author blank before the argument
    /// (`new Foo( // c⏎/* a */ /* b */⏎x` → `/* a */⏎/* b */`), where every sibling builder
    /// kept both.
    pub(super) fn emit_pulled_gap(
        &self,
        paren_line: &mut DocBuf,
        parts: &mut DocBuf,
        printer: &Printer<'_>,
    ) {
        self.emit_delimiter_line_pull(paren_line, printer);
        self.emit_leading_comments_inline_aware(parts, printer);
    }

    /// Emit a gap nothing pulled as ONE leading run: every comment in it except a `//`
    /// trailing the delimiter (whose caller places it on the delimiter's line) leads the first
    /// item through the shared leading emitter ([`Printer::push_leading_comment_run`]). Its
    /// separators are prettier's `printLeadingComment`: a space where the author glued a pair
    /// (`fn(/* c */ a)`), the soft `line` where a comment broke after (its own line when the
    /// list breaks, the glued bytes when it collapses), and a blank-preserving hardline for an
    /// author blank or an own-line comment. Returns whether it pushed that hardline, which a
    /// collapsible list cannot stay flat around. Every builder of the call family's
    /// `(`→first-argument gap takes this for a gap it does not pull.
    ///
    /// ⚠️ **A hand-rolled separator here is the bug class, and each builder once had one.** A
    /// space after a comment the author broke after welded it to the argument
    /// (`/* c2 */ /* c3 */⏎a, b` → `/* c2 */ /* c3 */ a,`) — including a run ending in a
    /// MULTI-line owned comment (`fn(/* c1 */⏎/* c2⏎*/ a)` → `/* c1 */ /* c2⏎*/ a`, a blank
    /// above `c2` dropped) and one glued to a stripped paren that holds a break
    /// (`/* c2 */ (⏎{…})` → `/* c1 */ /* c2 */ {`) — and a raw newline count read a blank INSIDE
    /// the argument's parens (`fn(/* c */ (⏎⏎a), b)`), or a multi-line comment's own newline, as
    /// the author's.
    pub(super) fn emit_unpulled_gap(&self, parts: &mut DocBuf, printer: &Printer<'_>) -> bool {
        printer.push_leading_comment_run(
            parts,
            self.trailing_block.iter().chain(&self.leading).copied(),
            self.end,
            LeadingGlue::AdjacentStrippedParen,
        )
    }

    /// Whether the author left a blank line in this inter-argument gap.
    ///
    /// The scan runs from the previous argument's end to the first leading comment (or,
    /// with none, the gap's end) — bounded there because a comment's own newlines would
    /// otherwise read as the author's blank.
    ///
    /// ⚠️ **The argument family measures from the ARGUMENT's end, not from past the
    /// comma** — `BlankRule::NextLineEmpty`, prettier's `print/call-arguments.js`
    /// (`isNextLineEmpty(arg, options)`), not the array/tuple rule its own
    /// `isLineAfterElementEmpty` advances to the comma for. The two agree on the ordinary
    /// authoring and part where the author pushed the comma onto its own line
    /// (`fn(a⏎⏎,⏎// c⏎b)`): scanning from past the comma cannot see the blank written
    /// above it, so the blank was DROPPED where prettier keeps it, and only a prettier
    /// compare could show it — the dropped-blank output is its own fixed point.
    /// `is_next_line_empty` is that predicate, and it already steps over a trailing
    /// comment on the argument's own line, so no hand-rolled `check_start` is needed.
    pub(super) fn has_blank_line_in_gap(&self, printer: &Printer<'_>) -> bool {
        let check_end = if !self.leading.is_empty() {
            self.leading[0].span.start
        } else {
            self.end
        };
        if self.behind_interior {
            // The comma was emitted against the argument, ahead of its interior, so a comma
            // the author gave a line of its own is not a line of the output — a blank below
            // it is the author's, measured from the end of what trails the argument.
            let from = self
                .trailing_run()
                .chain(self.leads.iter().copied())
                .map(|c| c.span.end)
                .max()
                .unwrap_or(self.start);
            return printer.blank_before_next_item(from, check_end);
        }
        printer.is_next_line_empty(self.start, check_end)
    }

    /// Emit trailing comments (block then line) with leading spaces to a parts vector.
    ///
    /// Used for comments that follow an argument, formatted as ` /* block */ // line`.
    /// Line comments go through `line_suffix` (zero width) so they never count against
    /// the argument's own group — flushing at the caller's following hardline (every
    /// caller is a forced-multiline context). Prettier's `lineSuffix`.
    /// The end of the last comment [`Self::emit_trailing_comments`] would emit — the anchor
    /// a delimiter-line pull measures its author blank from
    /// ([`Printer::push_delimiter_glued_blank`]). `None` when there is no trailing run.
    ///
    /// The max of both buckets, not the last of either: they are emitted blocks-then-lines
    /// but partition one source-ordered run, so a block written after the `//` still ends
    /// later in the source and is what the blank sits under.
    pub(super) fn trailing_end(&self) -> Option<u32> {
        self.trailing_block
            .iter()
            .chain(self.trailing_line.iter())
            .map(|c| c.span.end)
            .max()
    }

    fn emit_trailing_comments(&self, parts: &mut DocBuf, printer: &Printer<'_>) {
        let d = printer.d();
        for comment in &self.trailing_block {
            parts.push(d.text(" "));
            parts.push(printer.build_comment_doc(comment));
        }
        if let Some(comment) = self.trailing_line {
            parts.push(printer.build_trailing_line_comment_doc(comment));
        }
    }

    /// Emit a non-last arg's trailing comments split around its comma, then push the
    /// comma itself: before-comma block comments trail the arg (`arg /* c */,`),
    /// after-comma blocks and the same-line line comment follow the comma
    /// (`arg, /* c */ // c2`). The caller adds the line break after.
    ///
    /// Unlike [`Self::emit_trailing_comments`] (which the caller invokes *after* pushing
    /// the comma, so every block lands after it), this keeps a before-comma block in
    /// its authored position. Shared by the `new`-argument non-last paths
    /// (`build_new_doc_with_wrapping` and `build_call_args_with_blank_lines`) so they
    /// can't drift and relocate the block past the comma.
    pub(super) fn emit_trailing_comments_around_comma(
        &self,
        parts: &mut DocBuf,
        printer: &Printer<'_>,
    ) {
        let d = printer.d();
        let comma_pos = find_comma_pos(printer.source, self.start, self.end);
        if let Some(cpos) = comma_pos {
            for comment in &self.trailing_block {
                if is_comment_before_comma(comment, cpos) {
                    parts.push(d.text(" "));
                    parts.push(printer.build_comment_doc(comment));
                }
            }
        }
        parts.push(d.text(","));
        if let Some(cpos) = comma_pos {
            for comment in &self.trailing_block {
                if is_comment_after_comma(comment, cpos) {
                    parts.push(d.text(" "));
                    parts.push(printer.build_comment_doc(comment));
                }
            }
        }
        if let Some(comment) = self.trailing_line {
            parts.push(printer.build_trailing_line_comment_doc(comment));
        }
    }

    /// Emit own-line ("leading") comments, with no comma. The bare dangling-comment
    /// emission shared by every last-argument path (no trailing comma precedes them —
    /// trailingComma: 'none') and by comma-less shapes (dynamic `import()`). Without it,
    /// own-line comments before the closing paren are dropped (content loss).
    /// The dangling comments follow the gap `start` (the preceding element's end);
    /// that is the base for preserving an author blank line before the first own-line
    /// comment.
    ///
    /// The separator goes BEFORE each comment (`docs/comments.md` §Trailing and dangling
    /// runs) and the whole walk is the shared trailing-run emitter
    /// ([`Printer::push_trailing_comment_run`]): a comment the author glued to the
    /// previous one's line (`/* c */ // t`, `/* c1 */ /* c2 */`) stays on that line, and
    /// everything else takes the blank-preserving break. Giving each its own line
    /// unconditionally reads as the safer rule and is not — the run re-collapses on the
    /// next pass, because a comment printed onto a fresh line is no longer glued when it is
    /// reparsed, so the output never reaches a fixed point (F1). The first comment's
    /// separator is unconditional: it is own-line by construction (that is what put it in
    /// `leading`), which is exactly what a `None` predecessor answers.
    ///
    /// ⚠️ Despite the name this is not a *dangling* run in the
    /// [`Printer::push_dangling_comment_run`] sense (a container's only content, whose
    /// separator is unconditional): an argument precedes these, so the glue question
    /// applies. This walk asked it correctly — between the two comments — before the
    /// question was named, and that is the spelling
    /// [`Printer::trailing_run_hugs_previous`] adopted; the "what follows the `*/`" one is
    /// the paraphrase that breaks on a deleted comma.
    pub(super) fn emit_dangling_comments(&self, parts: &mut DocBuf, printer: &Printer<'_>) {
        // The run's own cursor is the gap's `start`, so the first comment's blank scan
        // preserves an author blank line before an own-line trailing comment
        // (`arg⏎⏎/* c */` before the closing `)`), matching prettier.
        printer.push_trailing_comment_run(parts, self.leading.iter().copied(), self.start);
    }

    /// Emit a last argument's complete trailing-comment region: same-line comments (via
    /// [`Self::emit_trailing_comments`]), then own-line dangling comments (via
    /// [`Self::emit_dangling_comments`]). No trailing comma is emitted (trailingComma: 'none'),
    /// so a same-line block trails the arg in source order whether it sat before or after
    /// the source comma — the last arg needs no split around the never-emitted comma.
    ///
    /// The last-argument counterpart to [`Printer::open_inter_arg_gap`] (the non-last
    /// gap): shared by the `new` and member-chain last-arg paths so the ordering lives in
    /// one place. (`call_formatting` keeps its own same-line loop, feeding
    /// `force_expansion`, and calls only [`Self::emit_dangling_comments`] directly.)
    pub(crate) fn emit_last_arg_comments(&self, parts: &mut DocBuf, printer: &Printer<'_>) {
        // `emit_trailing_comments` already no-ops when there are no trailing comments,
        // so no presence guard is needed.
        self.emit_trailing_comments(parts, printer);
        self.emit_dangling_comments(parts, printer);
    }

    /// Emit everything this gap puts ahead of the next argument: first a run the previous
    /// argument's stripped-paren interior displaced past the comma, when it leads this
    /// argument ([`Self::lead_run_blocks_behind_interior`], rendered by
    /// [`Printer::push_run_leading_next_item`]); then the gap's own leading run, through the
    /// shared leading-comment emitter ([`Printer::push_leading_comment_run`]) in the
    /// stripped-paren glue mode.
    ///
    /// Two things make that leading run different from a plain one, and both are the mode's:
    /// paren stripping can put two JSDoc casts in one gap
    /// (`/** @type {A} */ (⏎/** @type {B} */ (expr))`), where the outer cast is glued to a
    /// `(` the printer deletes — so the glue test has to see through it, or the pair the
    /// author wrote as one splits across lines.
    ///
    /// ⚠️ **The run's last separator is prettier's soft `line`, not a hardline.** A
    /// hand-rolled loop here reached for [`Printer::push_leading_run_separator`], whose
    /// two states (space or hardline) are right only at an already-broken site: it forced
    /// an argument list open around a glued pair the author gave its own line
    /// (`fn(a,⏎/* c1 */ /* c2 */⏎b)`), which prettier keeps flat.
    pub(super) fn emit_leading_comments_inline_aware(
        &self,
        parts: &mut DocBuf,
        printer: &Printer<'_>,
    ) {
        printer.push_run_leading_next_item(parts, &self.leads, self.end);
        printer.push_leading_comment_run(
            parts,
            self.leading.iter().copied(),
            self.end,
            LeadingGlue::AdjacentStrippedParen,
        );
    }
}