oxc_coverage_instrument 0.3.13

Istanbul-compatible JavaScript/TypeScript coverage instrumentation using the Oxc AST
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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
//! AST-level coverage transform using `oxc_traverse`.
//!
//! Replaces the source-level text injection approach with proper AST mutation.
//! The transform:
//! 1. Collects coverage span metadata (same as the old visitor)
//! 2. Injects counter expression statements (`cov_fn().s[N]++`) into the AST
//! 3. Converts arrow expression bodies to block bodies when needed
//! 4. Prepends the coverage initialization preamble to the program

use std::collections::BTreeMap;
use std::fmt::Write;
use std::mem;

use oxc_allocator::Vec as ArenaVec;
use oxc_ast::ast::*;
use oxc_span::{GetSpan, SPAN, Span};
use oxc_syntax::operator::{LogicalOperator, UpdateOperator};
use oxc_traverse::{Traverse, TraverseCtx};

use crate::pragma::{IgnoreType, PragmaMap};
use crate::types::{BranchEntry, FileCoverage, FnEntry, Location, Position};

/// State carried through the traverse for coverage instrumentation.
pub struct CoverageState {
    /// Pragma map for istanbul/v8 ignore directives.
    pub pragmas: PragmaMap,
}

/// Collects coverage metadata and injects counter expressions via AST mutation.
pub struct CoverageTransform<'src> {
    source: &'src str,
    line_offsets: Vec<u32>,
    fn_counter: usize,
    stmt_counter: usize,
    branch_counter: usize,
    pub fn_map: BTreeMap<String, FnEntry>,
    pub statement_map: BTreeMap<String, Location>,
    pub branch_map: BTreeMap<String, BranchEntry>,
    /// Name inherited from a parent node (variable declarator, method definition).
    pending_name: Option<String>,
    /// `decl` span inherited from a class `MethodDefinition`. A method's inner
    /// `Function` has no `id` of its own, so without this override
    /// `enter_function` would fall back to the anonymous one-char marker at
    /// the start of `function`. For methods that start with a parameter list
    /// (e.g. `bar(x) {}`), `func.span.start` points at `(` — which is not a
    /// meaningful `decl`. We carry the method key span down instead.
    pending_method_decl: Option<Span>,
    /// Accumulated statements to inject before specific statements.
    pending_stmts: Vec<PendingInsertion>,
    /// Stack of pending function entry counters. Supports nested functions/arrows
    /// where an inner function is entered before the outer's body is visited.
    pending_fn_counters: Vec<usize>,
    /// Per-frame record of whether the current function or arrow is being ignored
    /// (i.e. its subtree should not be instrumented). Mirrors Istanbul's `path.skip()`:
    /// when true at any ancestor frame, statements in the body are not counted.
    ignored_fn_stack: Vec<bool>,
    /// Per-statement record of whether an `ignore next` pragma targets that
    /// statement. While any frame is true, the full statement subtree is skipped.
    ignored_stmt_stack: Vec<bool>,
    /// Per-class-property record of whether an `ignore next` pragma targets
    /// the property. Property definitions are not statements in Oxc's AST, but
    /// Istanbul still treats their initializer subtree as skippable.
    ignored_prop_stack: Vec<bool>,
    /// Per-switch-case record of whether an `ignore next` pragma targets the
    /// case label or its first consequent statement.
    ignored_switch_case_stack: Vec<bool>,
    /// Spans for `if` arms suppressed by `/* istanbul ignore if */` or
    /// `/* istanbul ignore else */`. The branch visitor decides which arm is
    /// suppressed, while statement/function visitors use this to skip nested
    /// counters as Istanbul does.
    ignored_if_arm_spans: Vec<Span>,
    /// Number of ignored arm spans pushed by each entered `if`, so exit can pop
    /// only the spans owned by that node.
    ignored_if_arm_push_counts: Vec<usize>,
    /// When true, skip instrumentation for the next node.
    skip_next: bool,
    /// When true, the next function/arrow should skip its own function counter
    /// without setting `skip_next`. Used for private class methods: Istanbul
    /// instruments their bodies but does not add function counters for them.
    skip_fn_counter_only: bool,
    /// True while traversing a `VariableDeclaration` carrying an `ignore next`
    /// pragma. Consumed by `enter_variable_declarator` to skip both the
    /// per-declarator statement counter and any inner function counter.
    skip_current_var_decl: bool,
    /// Coverage function name, cached to avoid cloning from state on every hook.
    cov_fn_name: String,
    /// When true, adds truthy-value tracking (`bT`) for logical expression operands.
    report_logic: bool,
    /// Class method names to exclude from coverage instrumentation.
    ignore_class_methods: Vec<String>,
    /// Branch IDs of logical expression branches (for building the `bT` map).
    pub logical_branch_ids: Vec<usize>,
}

struct PendingInsertion {
    /// The span.start of the target statement (used for matching).
    target_start: u32,
    /// Counter expression to inject before the target.
    counter_id: usize,
    counter_type: CounterType,
}

#[derive(Clone, Copy)]
enum CounterType {
    Statement,
    /// Left branch of a logical assignment (path index 0).
    BranchLeft,
}

impl<'src> CoverageTransform<'src> {
    pub fn new(
        source: &'src str,
        cov_fn_name: String,
        report_logic: bool,
        ignore_class_methods: Vec<String>,
    ) -> Self {
        let line_offsets: Vec<u32> = std::iter::once(0)
            .chain(
                source
                    .bytes()
                    .enumerate()
                    .filter(|(_, b)| *b == b'\n')
                    .map(|(i, _)| (i + 1) as u32),
            )
            .collect();

        Self {
            source,
            line_offsets,
            fn_counter: 0,
            stmt_counter: 0,
            branch_counter: 0,
            fn_map: BTreeMap::new(),
            statement_map: BTreeMap::new(),
            branch_map: BTreeMap::new(),
            pending_name: None,
            pending_method_decl: None,
            pending_stmts: Vec::new(),
            pending_fn_counters: Vec::new(),
            ignored_fn_stack: Vec::new(),
            ignored_stmt_stack: Vec::new(),
            ignored_prop_stack: Vec::new(),
            ignored_switch_case_stack: Vec::new(),
            ignored_if_arm_spans: Vec::new(),
            ignored_if_arm_push_counts: Vec::new(),
            skip_next: false,
            skip_fn_counter_only: false,
            skip_current_var_decl: false,
            cov_fn_name,
            report_logic,
            ignore_class_methods,
            logical_branch_ids: Vec::new(),
        }
    }

    fn span_to_location(&self, span: Span) -> Location {
        Location {
            start: self.offset_to_position(span.start),
            end: self.offset_to_position(span.end),
        }
    }

    fn in_ignored_subtree(&self) -> bool {
        self.ignored_fn_stack.iter().any(|&ignored| ignored)
            || self.ignored_stmt_stack.iter().any(|&ignored| ignored)
            || self.ignored_prop_stack.iter().any(|&ignored| ignored)
            || self.ignored_switch_case_stack.iter().any(|&ignored| ignored)
    }

    fn is_in_ignored_if_arm(&self, span: Span) -> bool {
        self.ignored_if_arm_spans
            .iter()
            .any(|ignored| ignored.start <= span.start && span.end <= ignored.end)
    }

    fn offset_to_position(&self, offset: u32) -> Position {
        let line = self.line_offsets.partition_point(|&o| o <= offset).saturating_sub(1);
        let line_start = self.line_offsets[line] as usize;
        let end = (offset as usize).min(self.source.len());
        // Istanbul/Babel report columns as UTF-16 code units (JavaScript string indices),
        // not UTF-8 bytes. Convert by walking chars from line start to the offset.
        let column =
            self.source[line_start..end].chars().map(char::len_utf16).sum::<usize>() as u32;
        Position { line: (line + 1) as u32, column }
    }

    fn add_function(&mut self, name: String, decl_span: Span, body_span: Span) -> usize {
        let id_num = self.fn_counter;
        let id = id_num.to_string();
        self.fn_counter += 1;
        let line = self.offset_to_position(decl_span.start).line;
        self.fn_map.insert(
            id,
            FnEntry {
                name,
                line,
                decl: self.span_to_location(decl_span),
                loc: self.span_to_location(body_span),
            },
        );
        id_num
    }

    fn add_statement(&mut self, span: Span) -> usize {
        let id_num = self.stmt_counter;
        let id = id_num.to_string();
        self.stmt_counter += 1;
        self.statement_map.insert(id, self.span_to_location(span));
        id_num
    }

    fn add_branch(&mut self, branch_type: &str, span: Span) -> usize {
        let id_num = self.branch_counter;
        let id = id_num.to_string();
        self.branch_counter += 1;
        let loc = self.span_to_location(span);
        let line = loc.start.line;
        self.branch_map.insert(
            id,
            BranchEntry { loc, line, branch_type: branch_type.to_string(), locations: Vec::new() },
        );
        id_num
    }

    fn add_branch_path(&mut self, branch_id: usize, span: Span) -> usize {
        let location = self.span_to_location(span);
        self.add_branch_path_location(branch_id, location)
    }

    fn add_branch_path_unknown(&mut self, branch_id: usize) -> usize {
        self.add_branch_path_location(
            branch_id,
            Location {
                start: Position { line: 0, column: 0 },
                end: Position { line: 0, column: 0 },
            },
        )
    }

    fn add_branch_path_location(&mut self, branch_id: usize, location: Location) -> usize {
        let entry = self
            .branch_map
            .get_mut(&branch_id.to_string())
            .expect("branch path must reference an existing branch");
        let path_idx = entry.locations.len();
        entry.locations.push(location);
        path_idx
    }

    fn drain_pending_insertions_for_target(&mut self, target_start: u32) -> Vec<PendingInsertion> {
        let mut drained = Vec::new();
        let mut remaining = Vec::with_capacity(self.pending_stmts.len());
        for pending in self.pending_stmts.drain(..) {
            if pending.target_start == target_start {
                drained.push(pending);
            } else {
                remaining.push(pending);
            }
        }
        self.pending_stmts = remaining;
        drained
    }

    fn retarget_pending_insertions(&mut self, from_start: u32, to_start: u32) {
        for pending in &mut self.pending_stmts {
            if pending.target_start == from_start {
                pending.target_start = to_start;
            }
        }
    }

    fn inject_pending_counters_into_statement_child<'a>(
        &mut self,
        body: &mut Statement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if matches!(body, Statement::BlockStatement(_)) {
            return;
        }

        let span = body.span();
        if span.start == 0 && span.end == 0 {
            return;
        }

        let pending = self.drain_pending_insertions_for_target(span.start);
        if pending.is_empty() {
            return;
        }

        let cov_fn = self.cov_fn_name.as_str();
        let scope_id = ctx.create_child_scope_of_current(oxc_syntax::scope::ScopeFlags::empty());
        let original = mem::replace(body, ctx.ast.statement_empty(SPAN));
        let mut stmts = ctx.ast.vec();
        for insertion in pending {
            stmts.push(build_pending_counter_stmt(cov_fn, &insertion, ctx));
        }
        stmts.push(original);
        *body = ctx.ast.statement_block_with_scope_id(SPAN, stmts, scope_id);
    }

    fn resolve_function_name(&mut self, func: &Function) -> String {
        if let Some(name) = self.pending_name.take() {
            return name;
        }
        if let Some(id) = &func.id {
            return id.name.to_string();
        }
        format!("(anonymous_{})", self.fn_counter)
    }
}

/// Allocate a string into the arena so it has lifetime `'a`.
fn alloc_str<'a>(s: &str, ctx: &TraverseCtx<'a, CoverageState>) -> &'a str {
    ctx.ast.allocator.alloc_str(s)
}

/// Build a counter expression: `cov_fn().type[id]++`
fn build_counter_expr<'a>(
    cov_fn_name: &str,
    counter_type: &str,
    counter_id: usize,
    ctx: &TraverseCtx<'a, CoverageState>,
) -> Expression<'a> {
    let name = alloc_str(cov_fn_name, ctx);
    let callee = ctx.ast.expression_identifier(SPAN, name);
    let call = ctx.ast.expression_call(
        SPAN,
        callee,
        None::<TSTypeParameterInstantiation>,
        ctx.ast.vec(),
        false,
    );

    let ct = alloc_str(counter_type, ctx);
    let member =
        ctx.ast.member_expression_static(SPAN, call, ctx.ast.identifier_name(SPAN, ct), false);
    let member_expr = Expression::from(member);

    let computed = ctx.ast.member_expression_computed(
        SPAN,
        member_expr,
        ctx.ast.expression_numeric_literal(
            SPAN,
            counter_id as f64,
            None,
            oxc_syntax::number::NumberBase::Decimal,
        ),
        false,
    );

    let target = SimpleAssignmentTarget::from(computed);
    ctx.ast.expression_update(SPAN, UpdateOperator::Increment, true, target)
}

/// Build a branch counter expression: `cov_fn().b[branch_id][path_idx]++`
fn build_branch_counter_expr<'a>(
    cov_fn_name: &str,
    branch_id: usize,
    path_idx: usize,
    ctx: &TraverseCtx<'a, CoverageState>,
) -> Expression<'a> {
    let name = alloc_str(cov_fn_name, ctx);
    let callee = ctx.ast.expression_identifier(SPAN, name);
    let call = ctx.ast.expression_call(
        SPAN,
        callee,
        None::<TSTypeParameterInstantiation>,
        ctx.ast.vec(),
        false,
    );

    let member =
        ctx.ast.member_expression_static(SPAN, call, ctx.ast.identifier_name(SPAN, "b"), false);
    let member_expr = Expression::from(member);

    let computed1 = ctx.ast.member_expression_computed(
        SPAN,
        member_expr,
        ctx.ast.expression_numeric_literal(
            SPAN,
            branch_id as f64,
            None,
            oxc_syntax::number::NumberBase::Decimal,
        ),
        false,
    );
    let computed1_expr = Expression::from(computed1);

    let computed2 = ctx.ast.member_expression_computed(
        SPAN,
        computed1_expr,
        ctx.ast.expression_numeric_literal(
            SPAN,
            path_idx as f64,
            None,
            oxc_syntax::number::NumberBase::Decimal,
        ),
        false,
    );

    let target = SimpleAssignmentTarget::from(computed2);
    ctx.ast.expression_update(SPAN, UpdateOperator::Increment, true, target)
}

/// Build a counter expression statement: `cov_fn().type[id]++;`
fn build_counter_stmt<'a>(
    cov_fn_name: &str,
    counter_type: &str,
    counter_id: usize,
    ctx: &TraverseCtx<'a, CoverageState>,
) -> Statement<'a> {
    let expr = build_counter_expr(cov_fn_name, counter_type, counter_id, ctx);
    ctx.ast.statement_expression(SPAN, expr)
}

/// Build a branch counter statement: `cov_fn().b[branch_id][path_idx]++;`
fn build_branch_counter_stmt<'a>(
    cov_fn_name: &str,
    branch_id: usize,
    path_idx: usize,
    ctx: &TraverseCtx<'a, CoverageState>,
) -> Statement<'a> {
    let expr = build_branch_counter_expr(cov_fn_name, branch_id, path_idx, ctx);
    ctx.ast.statement_expression(SPAN, expr)
}

fn build_pending_counter_stmt<'a>(
    cov_fn_name: &str,
    pending: &PendingInsertion,
    ctx: &TraverseCtx<'a, CoverageState>,
) -> Statement<'a> {
    match pending.counter_type {
        CounterType::Statement => build_counter_stmt(cov_fn_name, "s", pending.counter_id, ctx),
        CounterType::BranchLeft => {
            build_branch_counter_stmt(cov_fn_name, pending.counter_id, 0, ctx)
        }
    }
}

/// Generate the preamble as source text.
///
/// Since building the IIFE via AST nodes is verbose and error-prone,
/// we generate the preamble as a source string and prepend it.
/// This matches the approach used by istanbul-lib-instrument.
pub fn generate_preamble_source(
    coverage: &FileCoverage,
    coverage_hash: &str,
    coverage_var: &str,
    cov_fn_name: &str,
    report_logic: bool,
) -> Result<String, serde_json::Error> {
    let estimated_size = 256
        + coverage.statement_map.len() * 80
        + coverage.fn_map.len() * 120
        + coverage.branch_map.len() * 120;
    let mut buf = String::with_capacity(estimated_size);
    let _ = write!(buf, "var {cov_fn_name} = (function () {{ var path = ");
    buf.push_str(&serde_json::to_string(&coverage.path)?);
    let _ = write!(buf, "; var hash = ");
    buf.push_str(&serde_json::to_string(coverage_hash)?);
    let _ = write!(buf, "; var gcv = '{coverage_var}'; var coverageData = ");
    buf.push_str(&serde_json::to_string(coverage)?);
    let _ = writeln!(
        buf,
        "; coverageData.hash = hash; var coverage = typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this; if (!coverage[gcv]) {{ coverage[gcv] = {{}}; }} if (!coverage[gcv][path] || coverage[gcv][path].hash !== hash) {{ coverage[gcv][path] = coverageData; }} var actualCoverage = coverage[gcv][path]; return actualCoverage; }});"
    );
    if report_logic {
        // Declare temp variable and truthy tracking helper function.
        // The helper captures the value, checks if it's a "non-trivial" truthy
        // value, and if so increments the bT counter. Returns the original value.
        //
        // Istanbul's non-trivial check:
        //   _temp && (!Array.isArray(_temp) || _temp.length)
        //         && (Object.getPrototypeOf(_temp) !== Object.prototype
        //             || Object.values(_temp).length)
        //
        // This means empty arrays [] and empty plain objects {} are NOT counted
        // as truthy. Non-plain objects (class instances, etc.) are always counted.
        let _ = writeln!(buf, "var {cov_fn_name}_temp;");
        let _ = writeln!(
            buf,
            "function {cov_fn_name}_bt(val, id, idx) {{ {cov_fn_name}_temp = val; if ({cov_fn_name}_temp && (!Array.isArray({cov_fn_name}_temp) || {cov_fn_name}_temp.length) && (Object.getPrototypeOf({cov_fn_name}_temp) !== Object.prototype || Object.values({cov_fn_name}_temp).length)) {{ ++{cov_fn_name}().bT[id][idx]; }} return {cov_fn_name}_temp; }}"
        );
    }
    Ok(buf)
}

/// Generate a deterministic coverage function name from the file path.
pub fn generate_cov_fn_name(file_path: &str) -> String {
    let mut hash: u64 = 0;
    for byte in file_path.bytes() {
        hash = hash.wrapping_mul(31).wrapping_add(u64::from(byte));
    }
    format!("cov_{hash:x}")
}

/// Create a dummy expression for `mem::replace` operations.
fn dummy_expr<'a>(ctx: &TraverseCtx<'a, CoverageState>) -> Expression<'a> {
    ctx.ast.expression_numeric_literal(SPAN, 0.0, None, oxc_syntax::number::NumberBase::Decimal)
}

/// Check if the nearest non-parenthesized ancestor is a logical expression.
/// Oxc preserves `ParenthesizedExpression` nodes (Babel strips them), so to
/// match istanbul-lib-instrument's chain flattening we must look through
/// any wrapping parens when deciding if we are an inner logical operand.
fn is_parent_logical(ctx: &TraverseCtx<'_, CoverageState>) -> bool {
    use oxc_traverse::Ancestor;
    for a in ctx.ancestors() {
        match a {
            Ancestor::ParenthesizedExpressionExpression(_) => {}
            Ancestor::LogicalExpressionLeft(_) | Ancestor::LogicalExpressionRight(_) => {
                return true;
            }
            _ => return false,
        }
    }
    false
}

/// Collect all leaf operand spans from a chained logical expression.
/// For `a && b || c`, returns spans of [a, b, c]. Also flattens through
/// `ParenthesizedExpression` nodes so `a && (b || c)` is treated as one
/// three-leaf chain, matching istanbul-lib-instrument.
fn collect_logical_leaf_spans(expr: &LogicalExpression, pragmas: &PragmaMap) -> Vec<Span> {
    let mut spans = Vec::new();
    collect_logical_leaves_inner(&expr.left, pragmas, &mut spans);
    collect_logical_leaves_inner(&expr.right, pragmas, &mut spans);
    spans
}

fn collect_logical_leaves_inner(expr: &Expression, pragmas: &PragmaMap, spans: &mut Vec<Span>) {
    if let Expression::ParenthesizedExpression(paren) = expr {
        collect_logical_leaves_inner(&paren.expression, pragmas, spans);
        return;
    }
    if pragmas.get(expr.span().start) == Some(IgnoreType::Next) {
        return;
    }
    if let Expression::LogicalExpression(logical) = expr {
        collect_logical_leaves_inner(&logical.left, pragmas, spans);
        collect_logical_leaves_inner(&logical.right, pragmas, spans);
    } else {
        spans.push(expr.span());
    }
}

fn is_ignored_case(case: &SwitchCase, pragmas: &PragmaMap) -> bool {
    pragmas.get(case.span.start) == Some(IgnoreType::Next)
        || case
            .consequent
            .first()
            .is_some_and(|stmt| pragmas.get(stmt.span().start) == Some(IgnoreType::Next))
}

struct LogicalWrapState<'b> {
    cov_fn_name: &'b str,
    branch_id: usize,
    report_logic: bool,
    path_idx: usize,
}

impl<'b> LogicalWrapState<'b> {
    fn new(cov_fn_name: &'b str, branch_id: usize, report_logic: bool) -> Self {
        Self { cov_fn_name, branch_id, report_logic, path_idx: 0 }
    }

    fn current_path_idx(&self) -> usize {
        self.path_idx
    }

    fn advance_path(&mut self) {
        self.path_idx += 1;
    }
}

/// Wrap a single logical expression leaf with its branch counter.
/// Without report_logic: `(cov().b[id][pathIdx]++, operand)`
/// With report_logic: additionally wrapped with truthy tracking via a
/// preamble helper function.
fn wrap_expression_with_branch_counter<'a>(
    operand: &mut Expression<'a>,
    state: &LogicalWrapState<'_>,
    ctx: &TraverseCtx<'a, CoverageState>,
) {
    let counter = build_branch_counter_expr(
        state.cov_fn_name,
        state.branch_id,
        state.current_path_idx(),
        ctx,
    );
    let orig = mem::replace(operand, dummy_expr(ctx));
    let mut items = ctx.ast.vec();
    items.push(counter);
    items.push(orig);
    *operand = ctx.ast.expression_sequence(SPAN, items);
}

fn wrap_logical_leaf<'a>(
    operand: &mut Expression<'a>,
    state: &mut LogicalWrapState<'_>,
    ctx: &TraverseCtx<'a, CoverageState>,
) {
    wrap_expression_with_branch_counter(operand, state, ctx);
    let branch_wrapped = mem::replace(operand, dummy_expr(ctx));

    if state.report_logic {
        // Wrap with truthy tracking helper: cov_fn_bt(wrapped, branch_id, path_idx)
        let bt_name = alloc_str(&format!("{}_bt", state.cov_fn_name), ctx);
        let callee = ctx.ast.expression_identifier(SPAN, bt_name);
        let mut args = ctx.ast.vec();
        args.push(Argument::from(branch_wrapped));
        args.push(Argument::from(ctx.ast.expression_numeric_literal(
            SPAN,
            state.branch_id as f64,
            None,
            oxc_syntax::number::NumberBase::Decimal,
        )));
        args.push(Argument::from(ctx.ast.expression_numeric_literal(
            SPAN,
            state.current_path_idx() as f64,
            None,
            oxc_syntax::number::NumberBase::Decimal,
        )));
        *operand = ctx.ast.expression_call(
            SPAN,
            callee,
            None::<TSTypeParameterInstantiation>,
            args,
            false,
        );
    } else {
        *operand = branch_wrapped;
    }
    state.advance_path();
}

/// Recursively wrap each leaf operand in a chained logical expression with
/// its branch counter: `(cov().b[id][pathIdx]++, operand)`. Looks through
/// `ParenthesizedExpression` so `a && (b || c)` wraps all three leaves.
fn wrap_logical_leaves<'a>(
    expr: &mut LogicalExpression<'a>,
    state: &mut LogicalWrapState<'_>,
    ctx: &mut TraverseCtx<'a, CoverageState>,
) {
    wrap_logical_operand(&mut expr.left, state, ctx);
    wrap_logical_operand(&mut expr.right, state, ctx);
}

fn wrap_logical_operand<'a>(
    operand: &mut Expression<'a>,
    state: &mut LogicalWrapState<'_>,
    ctx: &mut TraverseCtx<'a, CoverageState>,
) {
    // Unwrap parens transparently (matches Babel's AST shape).
    if let Expression::ParenthesizedExpression(paren) = operand {
        return wrap_logical_operand(&mut paren.expression, state, ctx);
    }
    if ctx.state.pragmas.get(operand.span().start) == Some(IgnoreType::Next) {
        return;
    }
    if let Expression::LogicalExpression(inner) = operand {
        wrap_logical_leaves(inner, state, ctx);
    } else {
        wrap_logical_leaf(operand, state, ctx);
    }
}

impl<'a> Traverse<'a, CoverageState> for CoverageTransform<'_> {
    fn enter_function(
        &mut self,
        func: &mut Function<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let has_pragma = ctx.state.pragmas.get(func.span.start) == Some(IgnoreType::Next);
        let ignored_named_function_expression = func.r#type == FunctionType::FunctionExpression
            && func
                .id
                .as_ref()
                .is_some_and(|id| self.ignore_class_methods.contains(&id.name.to_string()));
        // Subtree skips cascade into the body (Istanbul semantics for pragmas
        // and ignoreClassMethods).
        let pragma_skip = has_pragma
            || self.skip_next
            || self.in_ignored_subtree()
            || ignored_named_function_expression;
        let fn_counter_only_skip = self.skip_fn_counter_only;
        self.skip_next = false;
        self.skip_fn_counter_only = false;
        self.ignored_fn_stack.push(pragma_skip);
        if pragma_skip || fn_counter_only_skip {
            self.pending_name = None;
            return;
        }

        let name = self.resolve_function_name(func);
        // `decl` should point at the identifier itself, matching istanbul-lib-instrument:
        //   `function foo(…)`               → decl is the `foo` identifier span
        //   class methods `bar(…) {…}`      → decl is the method key span (set by
        //                                      `enter_method_definition` before we get here)
        //   `function(…)` (anonymous)       → decl is a zero-ish-width marker at the start of
        //                                      `function`, which is where the name would go
        let decl_span = if let Some(id) = &func.id {
            id.span
        } else if let Some(span) = self.pending_method_decl.take() {
            span
        } else {
            // Anonymous: one-character span at the start of the `function` keyword.
            // Matches istanbul's output for `const f = function(…) {…}` (decl = col 10–11).
            Span::new(func.span.start, func.span.start + 1)
        };
        if let Some(body) = &func.body {
            let fn_id = self.add_function(name, decl_span, body.span);
            self.pending_fn_counters.push(fn_id);
        }
    }

    fn exit_function(
        &mut self,
        _func: &mut Function<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.ignored_fn_stack.pop();
    }

    fn enter_function_body(
        &mut self,
        body: &mut FunctionBody<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree() {
            return;
        }
        if let Some(fn_id) = self.pending_fn_counters.pop() {
            let cov_fn = self.cov_fn_name.as_str();
            let counter = build_counter_stmt(cov_fn, "f", fn_id, ctx);
            body.statements.insert(0, counter);
        }
    }

    fn enter_arrow_function_expression(
        &mut self,
        arrow: &mut ArrowFunctionExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let pragma_skip = ctx.state.pragmas.get(arrow.span.start) == Some(IgnoreType::Next)
            || self.skip_next
            || self.in_ignored_subtree();
        // Only pragma-driven skips suppress body statements.
        self.ignored_fn_stack.push(pragma_skip);
        if pragma_skip {
            self.skip_next = false;
            self.pending_name = None;
            return;
        }

        let name =
            self.pending_name.take().unwrap_or_else(|| format!("(anonymous_{})", self.fn_counter));
        let fn_id = self.add_function(
            name,
            Span::new(arrow.span.start, arrow.span.start + 1),
            arrow.body.span,
        );

        // DON'T modify body here — it breaks scope tracking in the traverse.
        // Set pending_fn_counter for enter_function_body to insert the counter.
        // For expression-bodied arrows, exit_arrow_function_expression converts
        // the body to a block with return after traversal completes.
        self.pending_fn_counters.push(fn_id);
    }

    fn exit_arrow_function_expression(
        &mut self,
        arrow: &mut ArrowFunctionExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // For expression-bodied arrows, if a counter was supposed to be inserted
        // but wasn't (because enter_function_body inserts into block bodies only),
        // we need to handle it here. However, enter_function_body SHOULD be called
        // for arrow bodies too. If the counter was already inserted, pending_fn_counter
        // will be None. Only need special handling if it wasn't inserted.
        // Actually, enter_function_body handles both block and expression bodies
        // by inserting at index 0 of the statements vec, which works even for
        // expression bodies (they have one ExpressionStatement).
        // The conversion to block body with return happens here, AFTER traversal
        // of the body is complete.
        if arrow.expression && !arrow.body.statements.is_empty() {
            // Convert expression body to block body: change ExpressionStatement to ReturnStatement
            if let Some(Statement::ExpressionStatement(expr_stmt)) =
                arrow.body.statements.last_mut()
            {
                let dummy = dummy_expr(ctx);
                let expr = mem::replace(&mut expr_stmt.expression, dummy);
                let last_idx = arrow.body.statements.len() - 1;
                arrow.body.statements[last_idx] = ctx.ast.statement_return(SPAN, Some(expr));
            }
            arrow.expression = false;
        }
        self.ignored_fn_stack.pop();
    }

    fn enter_variable_declaration(
        &mut self,
        decl: &mut VariableDeclaration<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // Honor `/* istanbul ignore next */` attached to this declaration.
        // `enter_statement` used to handle this for us, but variable declarations
        // are now treated as containers (per-declarator counters), so pragmas
        // must be consulted here instead.
        if ctx.state.pragmas.get(decl.span.start) == Some(IgnoreType::Next) {
            self.skip_current_var_decl = true;
        }
    }

    fn exit_variable_declaration(
        &mut self,
        _decl: &mut VariableDeclaration<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.skip_current_var_decl = false;
    }

    fn enter_variable_declarator(
        &mut self,
        decl: &mut VariableDeclarator<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // If the enclosing declaration is ignored, skip both the statement
        // counter wrap and any inner function counter. Set `skip_next` so the
        // inner arrow/function hook consumes it.
        if self.skip_current_var_decl {
            if matches!(
                decl.init,
                Some(Expression::ArrowFunctionExpression(_) | Expression::FunctionExpression(_))
            ) {
                self.skip_next = true;
            }
            return;
        }

        // Set inherited name for function/arrow init so coverFunction can use it.
        if let Some(id) = decl.id.get_binding_identifier()
            && decl.init.as_ref().is_some_and(|init| {
                matches!(
                    init,
                    Expression::ArrowFunctionExpression(_) | Expression::FunctionExpression(_)
                )
            })
        {
            self.pending_name = Some(id.name.to_string());
        }

        // Per-declarator statement counter: wrap the init with (++cov().s[N], init).
        // Mirrors istanbul-lib-instrument's coverVariableDeclarator, which calls
        // insertStatementCounter on path.get('init'). Declarators without an init
        // (`let x;`) produce no statement counter.
        let Some(init) = decl.init.as_mut() else { return };
        // Skip if inside an ignored function/arrow body.
        if self.in_ignored_subtree() {
            return;
        }
        let init_span = init.span();
        if init_span.start == 0 && init_span.end == 0 {
            return;
        }
        let stmt_id = self.add_statement(init_span);
        let cov_fn = self.cov_fn_name.as_str();
        let counter = build_counter_expr(cov_fn, "s", stmt_id, ctx);
        let orig = mem::replace(init, dummy_expr(ctx));
        let mut items = ctx.ast.vec();
        items.push(counter);
        items.push(orig);
        *init = ctx.ast.expression_sequence(SPAN, items);
    }

    fn exit_variable_declarator(
        &mut self,
        _decl: &mut VariableDeclarator<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.pending_name = None;
    }

    fn enter_method_definition(
        &mut self,
        method: &mut MethodDefinition<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let parent_ignored = self.in_ignored_subtree();
        let key_span = method.key.span();
        let is_private = matches!(method.key, PropertyKey::PrivateIdentifier(_));
        let ignore_by_pragma = !is_private
            && (ctx.state.pragmas.get(method.span.start) == Some(IgnoreType::Next)
                || ctx.state.pragmas.get(key_span.start) == Some(IgnoreType::Next)
                || self.skip_next);
        if ignore_by_pragma {
            self.ignored_prop_stack.push(true);
            self.skip_next = false;
            return;
        }
        self.ignored_prop_stack.push(false);
        if parent_ignored {
            return;
        }
        let (name, key_span) = match &method.key {
            PropertyKey::StaticIdentifier(id) => (id.name.to_string(), id.span),
            PropertyKey::StringLiteral(s) => (s.value.to_string(), s.span),
            PropertyKey::PrivateIdentifier(_) => {
                // Istanbul instruments private method bodies, but does not add
                // function counters for the private method itself.
                self.skip_fn_counter_only = true;
                return;
            }
            _ => return,
        };
        if self.ignore_class_methods.contains(&name) {
            if let Some(ignored) = self.ignored_prop_stack.last_mut() {
                *ignored = true;
            }
            return;
        }
        self.pending_name = Some(name);
        // `decl` for a method is the method key's span (e.g. `bar` in
        // `class C { bar(x) {} }`). Matches the rule we apply for named
        // function declarations — see `fn_decl_span_matches_istanbul`.
        self.pending_method_decl = Some(key_span);
    }

    fn exit_method_definition(
        &mut self,
        _method: &mut MethodDefinition<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.pending_name = None;
        self.pending_method_decl = None;
        self.ignored_prop_stack.pop();
    }

    fn enter_property_definition(
        &mut self,
        prop: &mut PropertyDefinition<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let parent_ignored = self.in_ignored_subtree();
        let has_ignore_next =
            ctx.state.pragmas.get(prop.span.start) == Some(IgnoreType::Next) || self.skip_next;
        self.ignored_prop_stack.push(has_ignore_next);
        if has_ignore_next {
            self.skip_next = false;
            return;
        }
        if parent_ignored {
            return;
        }

        // Class property initializers: class Foo { x = expr; #y = expr; }
        // Istanbul creates a statement counter for each initializer expression.
        // Since PropertyDefinition is a class element (not a Statement), enter_statement
        // won't catch it. We wrap the initializer: x = (++cov().s[N], expr).
        let Some(value) = &prop.value else { return };
        let span = value.span();
        if span.start == 0 && span.end == 0 {
            return;
        }
        let stmt_id = self.add_statement(span);
        let cov_fn = self.cov_fn_name.as_str();
        let counter = build_counter_expr(cov_fn, "s", stmt_id, ctx);
        let orig = mem::replace(prop.value.as_mut().unwrap(), dummy_expr(ctx));
        let mut items = ctx.ast.vec();
        items.push(counter);
        items.push(orig);
        *prop.value.as_mut().unwrap() = ctx.ast.expression_sequence(SPAN, items);
    }

    fn exit_property_definition(
        &mut self,
        _prop: &mut PropertyDefinition<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.ignored_prop_stack.pop();
    }

    fn enter_object_property(
        &mut self,
        prop: &mut ObjectProperty<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let is_method_like =
            prop.method || matches!(prop.kind, PropertyKind::Get | PropertyKind::Set);
        let key_has_ignore_next = ctx.state.pragmas.get(prop.span.start) == Some(IgnoreType::Next)
            || ctx.state.pragmas.get(prop.key.span().start) == Some(IgnoreType::Next)
            || self.skip_next;
        let has_ignore_next = is_method_like && key_has_ignore_next;
        let is_function_valued = matches!(
            prop.value,
            Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_)
        );
        let value_has_ignore_next = !is_method_like && !is_function_valued && key_has_ignore_next;
        let has_ignore_next = has_ignore_next || value_has_ignore_next;
        self.ignored_prop_stack.push(has_ignore_next);
        if has_ignore_next {
            self.skip_next = false;
        }
    }

    fn exit_object_property(
        &mut self,
        _prop: &mut ObjectProperty<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.ignored_prop_stack.pop();
    }

    fn enter_statement(
        &mut self,
        stmt: &mut Statement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let span = stmt.span();
        let parent_ignored = self.in_ignored_subtree();
        let is_injected = span.start == 0 && span.end == 0;
        let has_ignore_next = !is_injected
            && (ctx.state.pragmas.get(span.start) == Some(IgnoreType::Next)
                || self.is_in_ignored_if_arm(span));
        self.ignored_stmt_stack.push(has_ignore_next);
        // Injected nodes have SPAN = 0:0 — never treat them as real statements.
        if is_injected {
            return;
        }
        // istanbul-lib-instrument treats these variants as containers, not statements:
        //   FunctionDeclaration / ClassDeclaration  — covered via function counters
        //   VariableDeclaration                     — covered per-declarator (see
        //                                             enter_variable_declarator)
        //   Import / Export* / TS type-only decls   — skipped entirely
        //   BlockStatement / EmptyStatement         — never counted
        // See istanbul-lib-instrument's visitor.js wiring.
        if matches!(
            stmt,
            Statement::BlockStatement(_)
                | Statement::EmptyStatement(_)
                | Statement::FunctionDeclaration(_)
                | Statement::ClassDeclaration(_)
                | Statement::VariableDeclaration(_)
                | Statement::ImportDeclaration(_)
                | Statement::ExportNamedDeclaration(_)
                | Statement::ExportDefaultDeclaration(_)
                | Statement::ExportAllDeclaration(_)
                | Statement::TSTypeAliasDeclaration(_)
                | Statement::TSInterfaceDeclaration(_)
                | Statement::TSEnumDeclaration(_)
                | Statement::TSModuleDeclaration(_)
                | Statement::TSImportEqualsDeclaration(_)
                | Statement::TSExportAssignment(_)
                | Statement::TSNamespaceExportDeclaration(_)
        ) {
            return;
        }
        // If any enclosing function or arrow is ignored, skip its body statements
        // too. This matches Istanbul's subtree-skip semantics for
        // `/* istanbul ignore next */` on the enclosing callable.
        if parent_ignored {
            return;
        }
        // Check for ignore next pragma on this statement.
        // Setting `skip_next` lets nested functions/arrows in the subtree skip
        // their own counters. It must NOT leak to the next sibling statement —
        // `exit_statement` clears it defensively.
        if has_ignore_next {
            self.skip_next = true;
            return;
        }
        if self.skip_next {
            self.skip_next = false;
            return;
        }
        let stmt_id = self.add_statement(span);
        self.pending_stmts.push(PendingInsertion {
            target_start: span.start,
            counter_id: stmt_id,
            counter_type: CounterType::Statement,
        });
    }

    fn exit_statement(
        &mut self,
        _stmt: &mut Statement<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // Ensure `skip_next` cannot leak from an ignored statement to its next
        // sibling. Nested enter hooks consume it when they fire; if no such hook
        // fires (e.g. `/* istanbul ignore next */ return 1;`), this clears it.
        self.skip_next = false;
        self.ignored_stmt_stack.pop();
    }

    fn exit_statements(
        &mut self,
        stmts: &mut ArenaVec<'a, Statement<'a>>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.pending_stmts.is_empty() {
            return;
        }

        let cov_fn = self.cov_fn_name.as_str();
        let mut insertions: Vec<(usize, Statement<'a>)> = Vec::new();
        let pending = &mut self.pending_stmts;

        for (idx, stmt) in stmts.iter().enumerate() {
            if pending.is_empty() {
                break;
            }
            let span = stmt.span();
            // Skip injected nodes (SPAN = 0:0) to prevent offset-0 collision
            if span.start == 0 && span.end == 0 {
                continue;
            }
            let start = span.start;
            let mut i = 0;
            while i < pending.len() {
                if pending[i].target_start == start {
                    let p = pending.swap_remove(i);
                    let counter = build_pending_counter_stmt(cov_fn, &p, ctx);
                    insertions.push((idx, counter));
                } else {
                    i += 1;
                }
            }
        }

        if insertions.is_empty() {
            return;
        }

        insertions.sort_by_key(|insertion| std::cmp::Reverse(insertion.0));
        for (idx, counter) in insertions {
            stmts.insert(idx, counter);
        }
    }

    fn enter_if_statement(
        &mut self,
        stmt: &mut IfStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree() {
            self.ignored_if_arm_push_counts.push(0);
            return;
        }
        let pragma = ctx.state.pragmas.get(stmt.span.start);
        let mut ignored_arm_count = 0;
        if pragma == Some(IgnoreType::If) {
            self.ignored_if_arm_spans.push(stmt.consequent.span());
            ignored_arm_count += 1;
        } else if pragma == Some(IgnoreType::Else)
            && let Some(alt) = &stmt.alternate
        {
            self.ignored_if_arm_spans.push(alt.span());
            ignored_arm_count += 1;
        }
        self.ignored_if_arm_push_counts.push(ignored_arm_count);

        // istanbul-lib-instrument's `coverIfBranches` passes `n.loc` (the whole
        // `IfStatement` span) as the consequent location, not the consequent
        // block's narrower span. See istanbul-lib-instrument/src/visitor.js
        // insertBranchCounter(path.get('consequent'), branch, n.loc). Match it
        // so downstream reporters (html-reporter, sonar) highlight the same
        // range in hover tooltips.
        let consequent_span = stmt.span;
        let branch_id = self.add_branch("if", stmt.span);

        let cov_fn = self.cov_fn_name.clone();

        // istanbul ignore if: skip the if-branch counter
        if pragma != Some(IgnoreType::If) {
            let path_idx = self.add_branch_path(branch_id, consequent_span);
            inject_branch_counter_into_statement(
                &mut stmt.consequent,
                cov_fn.as_str(),
                branch_id,
                path_idx,
                ctx,
            );
        }

        // istanbul ignore else: skip the else-branch counter
        if pragma != Some(IgnoreType::Else) {
            if stmt.alternate.is_none() {
                let scope_id =
                    ctx.create_child_scope_of_current(oxc_syntax::scope::ScopeFlags::empty());
                stmt.alternate =
                    Some(ctx.ast.statement_block_with_scope_id(SPAN, ctx.ast.vec(), scope_id));
            }
            if let Some(alt) = &mut stmt.alternate {
                let path_idx = if alt.span().start == 0 && alt.span().end == 0 {
                    self.add_branch_path_unknown(branch_id)
                } else {
                    self.add_branch_path(branch_id, alt.span())
                };
                inject_branch_counter_into_statement(
                    alt,
                    cov_fn.as_str(),
                    branch_id,
                    path_idx,
                    ctx,
                );
            }
        }
    }

    fn exit_if_statement(
        &mut self,
        _stmt: &mut IfStatement<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if let Some(count) = self.ignored_if_arm_push_counts.pop() {
            for _ in 0..count {
                self.ignored_if_arm_spans.pop();
            }
        }
    }

    fn enter_conditional_expression(
        &mut self,
        expr: &mut ConditionalExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree()
            || ctx.state.pragmas.get(expr.span.start) == Some(IgnoreType::Next)
        {
            return;
        }
        let branch_id = self.add_branch("cond-expr", expr.span);
        let ignore_consequent =
            ctx.state.pragmas.get(expr.consequent.span().start) == Some(IgnoreType::Next);
        let ignore_alternate =
            ctx.state.pragmas.get(expr.alternate.span().start) == Some(IgnoreType::Next);

        let cov_fn = self.cov_fn_name.clone();

        if !ignore_consequent {
            // Wrap consequent: (cov().b[id][path]++, originalExpr)
            let path_idx = self.add_branch_path(branch_id, expr.consequent.span());
            let counter = build_branch_counter_expr(cov_fn.as_str(), branch_id, path_idx, ctx);
            let orig_consequent = mem::replace(&mut expr.consequent, dummy_expr(ctx));
            let mut items = ctx.ast.vec();
            items.push(counter);
            items.push(orig_consequent);
            expr.consequent = ctx.ast.expression_sequence(SPAN, items);
        }

        if !ignore_alternate {
            // Wrap alternate: (cov().b[id][path]++, originalExpr)
            let path_idx = self.add_branch_path(branch_id, expr.alternate.span());
            let counter = build_branch_counter_expr(cov_fn.as_str(), branch_id, path_idx, ctx);
            let orig_alternate = mem::replace(&mut expr.alternate, dummy_expr(ctx));
            let mut items = ctx.ast.vec();
            items.push(counter);
            items.push(orig_alternate);
            expr.alternate = ctx.ast.expression_sequence(SPAN, items);
        }
    }

    fn enter_switch_statement(
        &mut self,
        stmt: &mut SwitchStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree() {
            return;
        }
        let branch_id = self.add_branch("switch", stmt.span);

        let cov_fn = self.cov_fn_name.clone();
        for case in &mut stmt.cases {
            if is_ignored_case(case, &ctx.state.pragmas) {
                continue;
            }
            let path_idx = self.add_branch_path(branch_id, case.span);
            let branch_stmt = build_branch_counter_stmt(cov_fn.as_str(), branch_id, path_idx, ctx);
            case.consequent.insert(0, branch_stmt);
        }
    }

    fn enter_switch_case(
        &mut self,
        case: &mut SwitchCase<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.ignored_switch_case_stack.push(is_ignored_case(case, &ctx.state.pragmas));
    }

    fn exit_switch_case(
        &mut self,
        _case: &mut SwitchCase<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.ignored_switch_case_stack.pop();
    }

    fn enter_logical_expression(
        &mut self,
        expr: &mut LogicalExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree()
            || ctx.state.pragmas.get(expr.span.start) == Some(IgnoreType::Next)
        {
            return;
        }
        match expr.operator {
            LogicalOperator::And | LogicalOperator::Or | LogicalOperator::Coalesce => {
                // Check if parent is also a logical expression — if so, skip.
                // Istanbul flattens chained logical expressions into a single branch
                // with N locations (one per leaf operand). Only the outermost creates
                // the branch entry.
                if is_parent_logical(ctx) {
                    return;
                }

                let branch_id = self.add_branch("binary-expr", expr.span);
                for span in collect_logical_leaf_spans(expr, &ctx.state.pragmas) {
                    self.add_branch_path(branch_id, span);
                }

                if self.report_logic {
                    self.logical_branch_ids.push(branch_id);
                }

                // Wrap each leaf operand with its branch counter
                let cov_fn = self.cov_fn_name.as_str();
                let mut state = LogicalWrapState::new(cov_fn, branch_id, self.report_logic);
                wrap_logical_leaves(expr, &mut state, ctx);
            }
        }
    }

    // Note: Istanbul does NOT instrument for/while/do-while loops as branches.
    // Loop coverage is tracked purely via statement counters on the body.

    fn exit_with_statement(
        &mut self,
        stmt: &mut WithStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.inject_pending_counters_into_statement_child(&mut stmt.body, ctx);
    }

    fn exit_labeled_statement(
        &mut self,
        stmt: &mut LabeledStatement<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let body_span = stmt.body.span();
        if body_span.start != 0 || body_span.end != 0 {
            // Preserve labels on loops: wrapping `label: while (...)` in a block
            // would break `continue label`, so emit the child counter before the label.
            self.retarget_pending_insertions(body_span.start, stmt.span.start);
        }
    }

    fn exit_do_while_statement(
        &mut self,
        stmt: &mut DoWhileStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.inject_pending_counters_into_statement_child(&mut stmt.body, ctx);
    }

    fn exit_while_statement(
        &mut self,
        stmt: &mut WhileStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.inject_pending_counters_into_statement_child(&mut stmt.body, ctx);
    }

    fn exit_for_statement(
        &mut self,
        stmt: &mut ForStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.inject_pending_counters_into_statement_child(&mut stmt.body, ctx);
    }

    fn exit_for_in_statement(
        &mut self,
        stmt: &mut ForInStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.inject_pending_counters_into_statement_child(&mut stmt.body, ctx);
    }

    fn exit_for_of_statement(
        &mut self,
        stmt: &mut ForOfStatement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        self.inject_pending_counters_into_statement_child(&mut stmt.body, ctx);
    }

    fn enter_formal_parameter(
        &mut self,
        param: &mut FormalParameter<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree() {
            return;
        }
        // Default parameter values: function f(x = 1) { }
        // Istanbul creates a 'default-arg' branch with 1 location for the default expression.
        if let Some(init) = &mut param.initializer {
            let init_span = init.span();
            let branch_id = self.add_branch("default-arg", param.span);
            self.add_branch_path(branch_id, init_span);
            let cov_fn = self.cov_fn_name.as_str();
            let state = LogicalWrapState::new(cov_fn, branch_id, false);
            wrap_expression_with_branch_counter(init, &state, ctx);
        }
    }

    fn enter_assignment_pattern(
        &mut self,
        pattern: &mut AssignmentPattern<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree() {
            return;
        }
        // Destructuring defaults: const { x = 1 } = obj;
        // Istanbul also creates 'default-arg' for these.
        let right_span = pattern.right.span();
        let branch_id = self.add_branch("default-arg", pattern.span);
        self.add_branch_path(branch_id, right_span);
        let cov_fn = self.cov_fn_name.as_str();
        let state = LogicalWrapState::new(cov_fn, branch_id, false);
        wrap_expression_with_branch_counter(&mut pattern.right, &state, ctx);
    }

    fn enter_assignment_expression(
        &mut self,
        expr: &mut AssignmentExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        if self.in_ignored_subtree() {
            return;
        }
        use oxc_syntax::operator::AssignmentOperator;

        // Logical assignment operators: x ??= y, x ||= y, x &&= y
        // These short-circuit and only assign if the condition holds.
        // Track them as binary-expr branches with 2 locations (left, right).
        if matches!(
            expr.operator,
            AssignmentOperator::LogicalOr
                | AssignmentOperator::LogicalAnd
                | AssignmentOperator::LogicalNullish
        ) {
            let left_span = expr.left.span();
            let right_span = expr.right.span();
            let branch_id = self.add_branch("binary-expr", expr.span);
            self.add_branch_path(branch_id, left_span);
            self.add_branch_path(branch_id, right_span);

            let cov_fn = self.cov_fn_name.as_str();

            // The left branch (no assignment) is always entered — increment before
            // the assignment. The right branch (assignment happens) is conditional.
            // We insert the left counter as a pending statement before this expression,
            // and wrap the right side with the right counter.
            self.pending_stmts.push(PendingInsertion {
                target_start: expr.span.start,
                counter_id: branch_id,
                counter_type: CounterType::BranchLeft,
            });

            // Wrap the right side: x ??= (++cov().b[id][1], y)
            let counter = build_branch_counter_expr(cov_fn, branch_id, 1, ctx);
            let orig_right = mem::replace(&mut expr.right, dummy_expr(ctx));
            let mut items = ctx.ast.vec();
            items.push(counter);
            items.push(orig_right);
            expr.right = ctx.ast.expression_sequence(SPAN, items);
        }
    }
}

/// Inject a branch counter into a statement, wrapping in a block if necessary.
fn inject_branch_counter_into_statement<'a>(
    stmt: &mut Statement<'a>,
    cov_fn_name: &str,
    branch_id: usize,
    path_idx: usize,
    ctx: &mut TraverseCtx<'a, CoverageState>,
) {
    let counter_stmt = build_branch_counter_stmt(cov_fn_name, branch_id, path_idx, ctx);

    match stmt {
        Statement::BlockStatement(block) => {
            block.body.insert(0, counter_stmt);
        }
        _ => {
            // Replace statement with dummy, then build block with counter + original.
            // Must create a scope for the new block to avoid traverse panics.
            let scope_id =
                ctx.create_child_scope_of_current(oxc_syntax::scope::ScopeFlags::empty());
            let original = mem::replace(stmt, ctx.ast.statement_empty(SPAN));
            let mut stmts = ctx.ast.vec();
            stmts.push(counter_stmt);
            stmts.push(original);
            *stmt = ctx.ast.statement_block_with_scope_id(SPAN, stmts, scope_id);
        }
    }
}