oxc_coverage_instrument 0.3.2

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
//! 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 {
    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>,
    /// 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>,
    /// When true, skip instrumentation for the next node.
    skip_next: 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 function coverage.
    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 CoverageTransform {
    pub fn new(
        source: &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 {
            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_stmts: Vec::new(),
            pending_fn_counters: Vec::new(),
            skip_next: 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 offset_to_position(&self, offset: u32) -> Position {
        let line = self.line_offsets.partition_point(|&o| o <= offset).saturating_sub(1);
        let col = offset - self.line_offsets[line];
        Position { line: (line + 1) as u32, column: col }
    }

    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, locations: &[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: locations.iter().map(|s| self.span_to_location(*s)).collect(),
            },
        );
        id_num
    }

    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)
}

/// 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_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 gcv = '{coverage_var}'; var coverageData = ");
    buf.push_str(&serde_json::to_string(coverage)?);
    let _ = writeln!(
        buf,
        "; 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] = 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) -> Vec<Span> {
    let mut spans = Vec::new();
    collect_logical_leaves_inner(&expr.left, &mut spans);
    collect_logical_leaves_inner(&expr.right, &mut spans);
    spans
}

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

/// 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_logical_leaf<'a>(
    operand: &mut Expression<'a>,
    cov_fn_name: &str,
    branch_id: usize,
    path_idx: usize,
    report_logic: bool,
    ctx: &TraverseCtx<'a, CoverageState>,
) {
    let counter = build_branch_counter_expr(cov_fn_name, branch_id, path_idx, ctx);
    let orig = mem::replace(operand, dummy_expr(ctx));
    let mut items = ctx.ast.vec();
    items.push(counter);
    items.push(orig);
    let branch_wrapped = ctx.ast.expression_sequence(SPAN, items);

    if report_logic {
        // Wrap with truthy tracking helper: cov_fn_bt(wrapped, branch_id, path_idx)
        let bt_name = alloc_str(&format!("{cov_fn_name}_bt"), 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,
            branch_id as f64,
            None,
            oxc_syntax::number::NumberBase::Decimal,
        )));
        args.push(Argument::from(ctx.ast.expression_numeric_literal(
            SPAN,
            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;
    }
}

/// 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>,
    cov_fn_name: &str,
    branch_id: usize,
    path_idx: &mut usize,
    report_logic: bool,
    ctx: &mut TraverseCtx<'a, CoverageState>,
) {
    wrap_logical_operand(&mut expr.left, cov_fn_name, branch_id, path_idx, report_logic, ctx);
    wrap_logical_operand(&mut expr.right, cov_fn_name, branch_id, path_idx, report_logic, ctx);
}

fn wrap_logical_operand<'a>(
    operand: &mut Expression<'a>,
    cov_fn_name: &str,
    branch_id: usize,
    path_idx: &mut usize,
    report_logic: bool,
    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,
            cov_fn_name,
            branch_id,
            path_idx,
            report_logic,
            ctx,
        );
    }
    if let Expression::LogicalExpression(inner) = operand {
        wrap_logical_leaves(inner, cov_fn_name, branch_id, path_idx, report_logic, ctx);
    } else {
        wrap_logical_leaf(operand, cov_fn_name, branch_id, *path_idx, report_logic, ctx);
        *path_idx += 1;
    }
}

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 skip = has_pragma || self.skip_next;
        // Always clear skip_next here to prevent leaking into the next node
        // (e.g., when both ignoreClassMethods and a pragma target the same method).
        self.skip_next = false;
        if skip {
            self.pending_name = None;
            return;
        }

        let name = self.resolve_function_name(func);
        let decl_span = if let Some(id) = &func.id {
            Span::new(func.span.start, id.span.end)
        } else {
            // Anonymous function: span from keyword to body start.
            // Works for both "function() {" and "async function() {".
            let end = func.body.as_ref().map_or(func.span.start, |b| b.span.start);
            Span::new(func.span.start, end)
        };
        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 enter_function_body(
        &mut self,
        body: &mut FunctionBody<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        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>,
    ) {
        if ctx.state.pragmas.get(arrow.span.start) == Some(IgnoreType::Next) || self.skip_next {
            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;
        }
    }

    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 };
        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 name = match &method.key {
            PropertyKey::StaticIdentifier(id) => id.name.to_string(),
            PropertyKey::StringLiteral(s) => s.value.to_string(),
            _ => return,
        };
        if self.ignore_class_methods.contains(&name) {
            self.skip_next = true;
            return;
        }
        self.pending_name = Some(name);
    }

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

    fn enter_property_definition(
        &mut self,
        prop: &mut PropertyDefinition<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // 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;
        }
        if ctx.state.pragmas.get(prop.span.start) == Some(IgnoreType::Next) || self.skip_next {
            self.skip_next = false;
            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 enter_statement(
        &mut self,
        stmt: &mut Statement<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let span = stmt.span();
        // Injected nodes have SPAN = 0:0 — never treat them as real statements.
        if span.start == 0 && span.end == 0 {
            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;
        }
        // Check for ignore next pragma
        if ctx.state.pragmas.get(span.start) == Some(IgnoreType::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_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 = match p.counter_type {
                        CounterType::Statement => {
                            build_counter_stmt(cov_fn, "s", p.counter_id, ctx)
                        }
                        CounterType::BranchLeft => {
                            build_branch_counter_stmt(cov_fn, p.counter_id, 0, ctx)
                        }
                    };
                    insertions.push((idx, counter));
                } else {
                    i += 1;
                }
            }
        }

        if insertions.is_empty() {
            return;
        }

        insertions.sort_by(|a, b| b.0.cmp(&a.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>,
    ) {
        let pragma = ctx.state.pragmas.get(stmt.span.start);

        let consequent_span = stmt.consequent.span();
        let alternate_span = stmt
            .alternate
            .as_ref()
            .map_or_else(|| Span::new(stmt.span.end, stmt.span.end), |alt| alt.span());
        let branch_id = self.add_branch("if", stmt.span, &[consequent_span, alternate_span]);

        let cov_fn = self.cov_fn_name.as_str();

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

        // istanbul ignore else: skip the else-branch counter
        if let Some(alt) = &mut stmt.alternate
            && pragma != Some(IgnoreType::Else)
        {
            inject_branch_counter_into_statement(alt, cov_fn, branch_id, 1, ctx);
        }
    }

    fn enter_conditional_expression(
        &mut self,
        expr: &mut ConditionalExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        let branch_id = self.add_branch(
            "cond-expr",
            expr.span,
            &[expr.consequent.span(), expr.alternate.span()],
        );

        let cov_fn = self.cov_fn_name.as_str();

        // Wrap consequent: (cov().b[id][0]++, originalExpr)
        let counter0 = build_branch_counter_expr(cov_fn, branch_id, 0, ctx);
        let orig_consequent = mem::replace(&mut expr.consequent, dummy_expr(ctx));
        let mut items = ctx.ast.vec();
        items.push(counter0);
        items.push(orig_consequent);
        expr.consequent = ctx.ast.expression_sequence(SPAN, items);

        // Wrap alternate: (cov().b[id][1]++, originalExpr)
        let counter1 = build_branch_counter_expr(cov_fn, branch_id, 1, ctx);
        let orig_alternate = mem::replace(&mut expr.alternate, dummy_expr(ctx));
        let mut items = ctx.ast.vec();
        items.push(counter1);
        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>,
    ) {
        let case_spans: Vec<Span> = stmt.cases.iter().map(|c| c.span).collect();
        let branch_id = self.add_branch("switch", stmt.span, &case_spans);

        let cov_fn = self.cov_fn_name.as_str();
        for (path_idx, case) in stmt.cases.iter_mut().enumerate() {
            let branch_stmt = build_branch_counter_stmt(cov_fn, branch_id, path_idx, ctx);
            case.consequent.insert(0, branch_stmt);
        }
    }

    fn enter_logical_expression(
        &mut self,
        expr: &mut LogicalExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        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;
                }

                // Collect all leaf operand spans by flattening the chain
                let leaf_spans = collect_logical_leaf_spans(expr);
                let branch_id = self.add_branch("binary-expr", expr.span, &leaf_spans);

                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();
                wrap_logical_leaves(expr, cov_fn, branch_id, &mut 0, self.report_logic, 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 enter_formal_parameter(
        &mut self,
        param: &mut FormalParameter<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // Default parameter values: function f(x = 1) { }
        // Istanbul creates a 'default-arg' branch with 1 location for the default expression.
        if let Some(init) = &param.initializer {
            let init_span = init.span();
            self.add_branch("default-arg", param.span, &[init_span]);
        }
    }

    fn enter_assignment_pattern(
        &mut self,
        pattern: &mut AssignmentPattern<'a>,
        _ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        // Destructuring defaults: const { x = 1 } = obj;
        // Istanbul also creates 'default-arg' for these.
        let right_span = pattern.right.span();
        self.add_branch("default-arg", pattern.span, &[right_span]);
    }

    fn enter_assignment_expression(
        &mut self,
        expr: &mut AssignmentExpression<'a>,
        ctx: &mut TraverseCtx<'a, CoverageState>,
    ) {
        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, &[left_span, 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);
        }
    }
}