bun_js_parser 0.1.1

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
#![warn(unused_must_use)]
use bun_collections::VecExt;
use core::cmp::Ordering;

use crate::p::P;
use crate::parser::{ExprIn, float_to_int32, prefill};
use crate::scan::scan_side_effects::SideEffects;
use bun_ast::fold_string_addition::{FoldStringAdditionKind, fold_string_addition};
use bun_ast::{
    self as js_ast, E, Expr, ExprData, Op, StoreRef, Symbol,
    expr::{Equality, LooseEql, StrictEql},
};

// PORT NOTE: The Zig `CreateBinaryExpressionVisitor(comptime ts, comptime jsx, comptime scan_only) type`
// returned an anonymous namespace struct whose only public item was `BinaryExpressionVisitor`.
// Round-C lowered `const JSX: JSXTransformType` → `J: JsxT`, so `BinaryExpressionVisitor` carries
// the parser generics directly.
// Diff readers should map:
//   Zig: CreateBinaryExpressionVisitor(TS, JSX, SCAN).BinaryExpressionVisitor
//   Rust: BinaryExpressionVisitor<'arena, TS, J, SCAN>

/// Try to optimize "typeof x === 'undefined'" to "typeof x > 'u'" or similar
/// Returns the optimized expression if successful, None otherwise
fn try_optimize_typeof_undefined<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool>(
    e_: &mut E::Binary,
    p: &mut P<'a, TYPESCRIPT, SCAN_ONLY>,
    replacement_op: js_ast::op::Code,
) -> Option<Expr> {
    // Check if this is a typeof comparison with "undefined"
    let (typeof_expr, string_expr, flip_comparison) = 'exprs: {
        // Try left side as typeof, right side as string
        if let ExprData::EUnary(unary) = &e_.left.data {
            if unary.op == Op::Code::UnTypeof {
                if let ExprData::EString(s) = &e_.right.data {
                    if s.eql_comptime(b"undefined") {
                        break 'exprs (e_.left, e_.right, false);
                    }
                }
                return None;
            }
        }

        // Try right side as typeof, left side as string
        if let ExprData::EUnary(unary) = &e_.right.data {
            if unary.op == Op::Code::UnTypeof {
                if let ExprData::EString(s) = &e_.left.data {
                    if s.eql_comptime(b"undefined") {
                        break 'exprs (e_.right, e_.left, true);
                    }
                }
                return None;
            }
        }

        return None;
    };

    // Create new string with "u"
    let u_string = p.new_expr(E::EString::from_static(b"u"), string_expr.loc);

    // Create the optimized comparison
    let left = if flip_comparison {
        u_string
    } else {
        typeof_expr
    };
    let right = if flip_comparison {
        typeof_expr
    } else {
        u_string
    };

    Some(p.new_expr(
        E::Binary {
            left,
            right,
            op: replacement_op,
        },
        e_.left.loc,
    ))
}

// PORT NOTE: `Expr.Data.eql(left, right, p, .{loose,strict})` — thin adapter
// from the `const STRICT: bool` shape used at the four call sites below to the
// canonical `ExprData::eql<P, K: EqlKindT>` (Expr.rs). Kept as a free fn so
// the call sites don't each repeat the `LooseEql`/`StrictEql` type-select.
#[inline]
fn data_eql<'a, const STRICT: bool, const TYPESCRIPT: bool, const SCAN_ONLY: bool>(
    left: &ExprData,
    right: &ExprData,
    p: &mut P<'a, TYPESCRIPT, SCAN_ONLY>,
) -> Equality {
    if STRICT {
        ExprData::eql::<_, StrictEql>(left, right, p)
    } else {
        ExprData::eql::<_, LooseEql>(left, right, p)
    }
}

pub struct BinaryExpressionVisitor {
    /// Arena handle to the in-place `E::Binary` node (Zig: `*E.Binary`).
    /// `StoreRef` is the safe arena back-reference: `Copy` + `Deref`/`DerefMut`
    /// encapsulate the AST-store invariant, so call sites need no raw-pointer
    /// round-trip to forge an `'arena` borrow.
    pub e: StoreRef<E::Binary>,
    pub loc: bun_ast::Loc,
    // PORT NOTE: Zig field name `in` is a Rust keyword; renamed to `in_`.
    pub in_: ExprIn,

    /// Input for visiting the left child
    pub left_in: ExprIn,

    /// "Local variables" passed from "checkAndPrepare" to "visitRightAndFinish"
    pub is_stmt_expr: bool, // = false (set by caller / Default)
}

impl BinaryExpressionVisitor {
    pub fn visit_right_and_finish<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool>(
        v: &mut Self,
        p: &mut P<'a, TYPESCRIPT, SCAN_ONLY>,
    ) -> Expr {
        // `v.e: StoreRef<E::Binary>` is the safe arena back-reference (Copy).
        // Snapshot the handle for the identity check / tail re-wrap, then take
        // the working `&mut` via `StoreRef::DerefMut` — the arena-backref
        // invariant is encapsulated there. The borrow is on the `v.e` field
        // only, so `v.loc` reads below split-borrow cleanly.
        let e_handle: StoreRef<E::Binary> = v.e;
        let e_ptr: *mut E::Binary = e_handle.as_ptr();
        let e_ = &mut *v.e;

        let is_call_target =
            matches!(p.call_target, ExprData::EBinary(ptr) if core::ptr::eq(ptr.as_ptr(), e_ptr));
        // const is_stmt_expr = @as(Expr.Tag, p.stmt_expr_value) == .e_binary and expr.data.e_binary == p.stmt_expr_value.e_binary;
        let was_anonymous_named_expr = e_.right.is_anonymous_named();
        let prev_decorator_class_name = p.decorator_class_name;

        // Propagate name for anonymous decorated class expressions in assignments
        if e_.op == Op::Code::BinAssign && was_anonymous_named_expr {
            if let ExprData::EClass(class) = &e_.right.data {
                if class.should_lower_standard_decorators {
                    if let ExprData::EIdentifier(ident) = e_.left.data {
                        p.decorator_class_name = Some(p.load_name_from_ref(ident.ref_));
                    }
                }
            }
        }

        // Mark the control flow as dead if the branch is never taken
        match e_.op {
            Op::Code::BinLogicalOr => {
                let side_effects = SideEffects::to_boolean(p, &e_.left.data);
                if side_effects.ok && side_effects.value {
                    // "true || dead"
                    let old = p.is_control_flow_dead;
                    p.is_control_flow_dead = true;
                    p.visit_expr(&mut e_.right);
                    p.is_control_flow_dead = old;
                } else {
                    p.visit_expr(&mut e_.right);
                }
            }
            Op::Code::BinLogicalAnd => {
                let side_effects = SideEffects::to_boolean(p, &e_.left.data);
                if side_effects.ok && !side_effects.value {
                    // "false && dead"
                    let old = p.is_control_flow_dead;
                    p.is_control_flow_dead = true;
                    p.visit_expr(&mut e_.right);
                    p.is_control_flow_dead = old;
                } else {
                    p.visit_expr(&mut e_.right);
                }
            }
            Op::Code::BinNullishCoalescing => {
                let side_effects = SideEffects::to_null_or_undefined(p, &e_.left.data);
                if side_effects.ok && !side_effects.value {
                    // "notNullOrUndefined ?? dead"
                    let old = p.is_control_flow_dead;
                    p.is_control_flow_dead = true;
                    p.visit_expr(&mut e_.right);
                    p.is_control_flow_dead = old;
                } else {
                    p.visit_expr(&mut e_.right);
                }
            }
            _ => {
                p.visit_expr(&mut e_.right);
            }
        }
        p.decorator_class_name = prev_decorator_class_name;

        // Always put constants on the right for equality comparisons to help
        // reduce the number of cases we have to check during pattern matching. We
        // can only reorder expressions that do not have any side effects.
        match e_.op {
            Op::Code::BinLooseEq
            | Op::Code::BinLooseNe
            | Op::Code::BinStrictEq
            | Op::Code::BinStrictNe => {
                if SideEffects::is_primitive_to_reorder(&e_.left.data)
                    && !SideEffects::is_primitive_to_reorder(&e_.right.data)
                {
                    let _left = e_.left;
                    let _right = e_.right;
                    e_.left = _right;
                    e_.right = _left;
                }
            }
            _ => {}
        }

        match e_.op {
            Op::Code::BinComma => {
                // "(1, 2)" => "2"
                // "(sideEffects(), 2)" => "(sideEffects(), 2)"
                // "(0, this.fn)" => "this.fn"
                // "(0, this.fn)()" => "(0, this.fn)()"
                if p.options.features.minify_syntax {
                    if let Some(simplified_left) = SideEffects::simplify_unused_expr(p, e_.left) {
                        if simplified_left.is_empty() {
                            return e_.right;
                        }
                        e_.left = simplified_left;
                    } else {
                        // The left operand has no side effects, but we need to preserve
                        // the comma operator semantics when used as a call target
                        if is_call_target && e_.right.has_value_for_this_in_call() {
                            // Keep the comma expression to strip "this" binding
                            e_.left = Expr {
                                data: prefill::data::ZERO,
                                loc: e_.left.loc,
                            };
                        } else {
                            return e_.right;
                        }
                    }
                }
            }
            Op::Code::BinLooseEq => {
                let equality =
                    data_eql::<false, TYPESCRIPT, SCAN_ONLY>(&e_.left.data, &e_.right.data, p);
                if equality.ok {
                    if equality.is_require_main_and_module {
                        p.ignore_usage_of_runtime_require();
                        p.ignore_usage(p.module_ref);
                        return p.value_for_import_meta_main(false, v.loc);
                    }

                    return p.new_expr(
                        E::Boolean {
                            value: equality.equal,
                        },
                        v.loc,
                    );
                }

                if p.options.features.minify_syntax {
                    // "typeof x == 'undefined'" => "typeof x > 'u'"
                    if let Some(optimized) = try_optimize_typeof_undefined(e_, p, Op::Code::BinGt) {
                        return optimized;
                    }

                    // "x == void 0" => "x == null"
                    if matches!(e_.left.data, ExprData::EUndefined(_)) {
                        e_.left.data = ExprData::ENull(E::Null {});
                    } else if matches!(e_.right.data, ExprData::EUndefined(_)) {
                        e_.right.data = ExprData::ENull(E::Null {});
                    }
                }

                // const after_op_loc = locAfterOp(e_.);
                // TODO: warn about equality check
                // TODO: warn about typeof string
            }
            Op::Code::BinStrictEq => {
                let equality =
                    data_eql::<true, TYPESCRIPT, SCAN_ONLY>(&e_.left.data, &e_.right.data, p);
                if equality.ok {
                    if equality.is_require_main_and_module {
                        p.ignore_usage(p.module_ref);
                        p.ignore_usage_of_runtime_require();
                        return p.value_for_import_meta_main(false, v.loc);
                    }

                    return p.new_expr(
                        E::Boolean {
                            value: equality.equal,
                        },
                        v.loc,
                    );
                }

                if p.options.features.minify_syntax {
                    // "typeof x === 'undefined'" => "typeof x > 'u'"
                    if let Some(optimized) = try_optimize_typeof_undefined(e_, p, Op::Code::BinGt) {
                        return optimized;
                    }
                }

                // const after_op_loc = locAfterOp(e_.);
                // TODO: warn about equality check
                // TODO: warn about typeof string
            }
            Op::Code::BinLooseNe => {
                let equality =
                    data_eql::<false, TYPESCRIPT, SCAN_ONLY>(&e_.left.data, &e_.right.data, p);
                if equality.ok {
                    if equality.is_require_main_and_module {
                        p.ignore_usage(p.module_ref);
                        p.ignore_usage_of_runtime_require();
                        return p.value_for_import_meta_main(true, v.loc);
                    }

                    return p.new_expr(
                        E::Boolean {
                            value: !equality.equal,
                        },
                        v.loc,
                    );
                }
                if p.options.features.minify_syntax {
                    // "typeof x != 'undefined'" => "typeof x < 'u'"
                    if let Some(optimized) = try_optimize_typeof_undefined(e_, p, Op::Code::BinLt) {
                        return optimized;
                    }
                }

                // const after_op_loc = locAfterOp(e_.);
                // TODO: warn about equality check
                // TODO: warn about typeof string

                // "x != void 0" => "x != null"
                if matches!(e_.right.data, ExprData::EUndefined(_)) {
                    e_.right = p.new_expr(E::Null {}, e_.right.loc);
                }
            }
            Op::Code::BinStrictNe => {
                let equality =
                    data_eql::<true, TYPESCRIPT, SCAN_ONLY>(&e_.left.data, &e_.right.data, p);
                if equality.ok {
                    if equality.is_require_main_and_module {
                        p.ignore_usage(p.module_ref);
                        p.ignore_usage_of_runtime_require();
                        return p.value_for_import_meta_main(true, v.loc);
                    }

                    return p.new_expr(
                        E::Boolean {
                            value: !equality.equal,
                        },
                        v.loc,
                    );
                }

                if p.options.features.minify_syntax {
                    // "typeof x !== 'undefined'" => "typeof x < 'u'"
                    if let Some(optimized) = try_optimize_typeof_undefined(e_, p, Op::Code::BinLt) {
                        return optimized;
                    }
                }
            }
            Op::Code::BinNullishCoalescing => {
                let null_or_undefined = SideEffects::to_null_or_undefined(p, &e_.left.data);
                if null_or_undefined.ok {
                    if !null_or_undefined.value {
                        return e_.left;
                    } else if null_or_undefined.side_effects == SideEffects::NoSideEffects {
                        // "(null ?? fn)()" => "fn()"
                        // "(null ?? this.fn)" => "this.fn"
                        // "(null ?? this.fn)()" => "(0, this.fn)()"
                        if is_call_target && e_.right.has_value_for_this_in_call() {
                            return Expr::join_with_comma(
                                Expr {
                                    data: ExprData::ENumber(E::Number { value: 0.0 }),
                                    loc: e_.left.loc,
                                },
                                e_.right,
                            );
                        }

                        return e_.right;
                    }
                }
            }
            Op::Code::BinLogicalOr => {
                let side_effects = SideEffects::to_boolean(p, &e_.left.data);
                if side_effects.ok && side_effects.value {
                    return e_.left;
                } else if side_effects.ok && side_effects.side_effects == SideEffects::NoSideEffects
                {
                    // "(0 || fn)()" => "fn()"
                    // "(0 || this.fn)" => "this.fn"
                    // "(0 || this.fn)()" => "(0, this.fn)()"
                    if is_call_target && e_.right.has_value_for_this_in_call() {
                        return Expr::join_with_comma(
                            Expr {
                                data: prefill::data::ZERO,
                                loc: e_.left.loc,
                            },
                            e_.right,
                        );
                    }

                    return e_.right;
                }
            }
            Op::Code::BinLogicalAnd => {
                let side_effects = SideEffects::to_boolean(p, &e_.left.data);
                if side_effects.ok {
                    if !side_effects.value {
                        return e_.left;
                    } else if side_effects.side_effects == SideEffects::NoSideEffects {
                        // "(1 && fn)()" => "fn()"
                        // "(1 && this.fn)" => "this.fn"
                        // "(1 && this.fn)()" => "(0, this.fn)()"
                        if is_call_target && e_.right.has_value_for_this_in_call() {
                            return Expr::join_with_comma(
                                Expr {
                                    data: prefill::data::ZERO,
                                    loc: e_.left.loc,
                                },
                                e_.right,
                            );
                        }

                        return e_.right;
                    }
                }
            }
            Op::Code::BinAdd => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: vals[0] + vals[1],
                            },
                            v.loc,
                        );
                    }

                    // "'abc' + 'xyz'" => "'abcxyz'"
                    if let Some(res) = fold_string_addition(
                        e_.left,
                        e_.right,
                        p.arena,
                        FoldStringAdditionKind::Normal,
                    ) {
                        return res;
                    }

                    // "(x + 'abc') + 'xyz'" => "'abcxyz'"
                    if let Some(left) = e_.left.data.e_binary() {
                        if left.op == Op::Code::BinAdd {
                            if let Some(result) = fold_string_addition(
                                left.right,
                                e_.right,
                                p.arena,
                                FoldStringAdditionKind::NestedLeft,
                            ) {
                                return p.new_expr(
                                    E::Binary {
                                        left: left.left,
                                        right: result,
                                        op: Op::Code::BinAdd,
                                    },
                                    e_.left.loc,
                                );
                            }
                        }
                    }
                }
            }
            Op::Code::BinSub => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: vals[0] - vals[1],
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinMul => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: vals[0] * vals[1],
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinDiv => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: vals[0] / vals[1],
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinRem => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        // TODO(port): move to <area>_sys
                        unsafe extern "C" {
                            // libc fmod is pure (value-type args, no errno, no pointers) → no caller preconditions.
                            safe fn fmod(x: f64, y: f64) -> f64;
                        }
                        return p.new_expr(
                            // Use libc fmod here to be consistent with what JavaScriptCore does
                            // https://github.com/oven-sh/WebKit/blob/7a0b13626e5db69aa5a32d037431d381df5dfb61/Source/JavaScriptCore/runtime/MathCommon.cpp#L574-L597
                            // PORT NOTE: Zig had a non-native fallback to std.math.mod; Rust targets are always native.
                            E::Number {
                                value: fmod(vals[0], vals[1]),
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinPow => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            // TODO(port): math arrives from move-in (was bun_jsc::math → js_parser)
                            E::Number {
                                value: bun_ast::math::pow(vals[0], vals[1]),
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinShl => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        let left = float_to_int32(vals[0]);
                        let right: u32 = (float_to_int32(vals[1]) as u32) % 32;
                        let result: i32 = left.wrapping_shl(right);
                        return p.new_expr(
                            E::Number {
                                value: result as f64,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinShr => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        let left = float_to_int32(vals[0]);
                        let right: u32 = (float_to_int32(vals[1]) as u32) % 32;
                        // std.math.shr on i32 is arithmetic shift right
                        let result: i32 = left.wrapping_shr(right);
                        return p.new_expr(
                            E::Number {
                                value: result as f64,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinUShr => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        let left: u32 = float_to_int32(vals[0]) as u32;
                        let right: u32 = (float_to_int32(vals[1]) as u32) % 32;
                        let result: u32 = left.wrapping_shr(right);
                        return p.new_expr(
                            E::Number {
                                value: result as f64,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinBitwiseAnd => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: (float_to_int32(vals[0]) & float_to_int32(vals[1])) as f64,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinBitwiseOr => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: (float_to_int32(vals[0]) | float_to_int32(vals[1])) as f64,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinBitwiseXor => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) = Expr::extract_numeric_values(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Number {
                                value: (float_to_int32(vals[0]) ^ float_to_int32(vals[1])) as f64,
                            },
                            v.loc,
                        );
                    }
                }
            }

            Op::Code::BinLt => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) =
                        Expr::extract_numeric_values_in_safe_range(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Boolean {
                                value: vals[0] < vals[1],
                            },
                            v.loc,
                        );
                    }
                    if let Some(vals) =
                        Expr::extract_string_values(&e_.left.data, &e_.right.data, p.arena)
                    {
                        let ord = vals[0].order(vals[1].get());
                        return p.new_expr(
                            E::Boolean {
                                value: ord == Ordering::Less,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinGt => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) =
                        Expr::extract_numeric_values_in_safe_range(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Boolean {
                                value: vals[0] > vals[1],
                            },
                            v.loc,
                        );
                    }
                    if let Some(vals) =
                        Expr::extract_string_values(&e_.left.data, &e_.right.data, p.arena)
                    {
                        let ord = vals[0].order(vals[1].get());
                        return p.new_expr(
                            E::Boolean {
                                value: ord == Ordering::Greater,
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinLe => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) =
                        Expr::extract_numeric_values_in_safe_range(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Boolean {
                                value: vals[0] <= vals[1],
                            },
                            v.loc,
                        );
                    }
                    if let Some(vals) =
                        Expr::extract_string_values(&e_.left.data, &e_.right.data, p.arena)
                    {
                        let ord = vals[0].order(vals[1].get());
                        return p.new_expr(
                            E::Boolean {
                                value: matches!(ord, Ordering::Equal | Ordering::Less),
                            },
                            v.loc,
                        );
                    }
                }
            }
            Op::Code::BinGe => {
                if p.should_fold_typescript_constant_expressions {
                    if let Some(vals) =
                        Expr::extract_numeric_values_in_safe_range(&e_.left.data, &e_.right.data)
                    {
                        return p.new_expr(
                            E::Boolean {
                                value: vals[0] >= vals[1],
                            },
                            v.loc,
                        );
                    }
                    if let Some(vals) =
                        Expr::extract_string_values(&e_.left.data, &e_.right.data, p.arena)
                    {
                        let ord = vals[0].order(vals[1].get());
                        return p.new_expr(
                            E::Boolean {
                                value: matches!(ord, Ordering::Equal | Ordering::Greater),
                            },
                            v.loc,
                        );
                    }
                }
            }

            // ---------------------------------------------------------------------------------------------------
            Op::Code::BinAssign => {
                // Optionally preserve the name
                if let ExprData::EIdentifier(ident) = e_.left.data {
                    // PORT NOTE: reshaped for borrowck — copy the `StoreStr` out of
                    // `p.symbols` before taking `&mut self` for `maybe_keep_expr_symbol_name`.
                    let name = p.symbols[ident.ref_.inner_index() as usize].original_name;
                    e_.right = p.maybe_keep_expr_symbol_name(
                        e_.right,
                        name.slice(),
                        was_anonymous_named_expr,
                    );
                }
            }
            Op::Code::BinNullishCoalescingAssign | Op::Code::BinLogicalOrAssign => {
                // Special case `{}.field ??= value` to minify to `value`
                // This optimization is specifically to target this pattern in HMR:
                //    `import.meta.hot.data.etc ??= init()`
                if let Some(dot) = e_.left.data.e_dot() {
                    if let Some(obj) = dot.target.data.e_object() {
                        if obj.properties.len_u32() == 0 {
                            if dot.name != b"__proto__" {
                                return e_.right;
                            }
                        }
                    }
                }
            }
            _ => {}
        }

        Expr {
            loc: v.loc,
            // Same arena slot Zig threads as `*E.Binary` — re-wrap the handle.
            data: ExprData::EBinary(e_handle),
        }
    }

    pub fn check_and_prepare<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool>(
        v: &mut Self,
        p: &mut P<'a, TYPESCRIPT, SCAN_ONLY>,
    ) -> Option<Expr> {
        // Snapshot the `Copy` arena handle before taking the working `&mut`
        // via `StoreRef::DerefMut`, so the early-return re-wrap below does not
        // overlap `e_`'s borrow of `v.e`.
        let e_handle: StoreRef<E::Binary> = v.e;
        let e_: &mut E::Binary = &mut *v.e;
        match e_.left.data {
            // Special-case private identifiers
            ExprData::EPrivateIdentifier(mut private) => {
                if e_.op == Op::Code::BinIn {
                    let name = p.load_name_from_ref(private.ref_);
                    let result = p.find_symbol(e_.left.loc, name).expect("unreachable");
                    private.ref_ = result.r#ref;

                    // Unlike regular identifiers, there are no unbound private identifiers
                    let kind = p.symbols[result.r#ref.inner_index() as usize].kind;
                    if !Symbol::is_kind_private(kind) {
                        let r = bun_ast::Range {
                            loc: e_.left.loc,
                            len: i32::try_from(name.len()).expect("int cast"),
                        };
                        p.log().add_range_error_fmt(
                            Some(p.source),
                            r,
                            format_args!(
                                "Private name \"{}\" must be declared in an enclosing class",
                                bstr::BStr::new(name)
                            ),
                        );
                    }

                    p.visit_expr(&mut e_.right);
                    e_.left = Expr {
                        data: ExprData::EPrivateIdentifier(private),
                        loc: e_.left.loc,
                    };

                    // privateSymbolNeedsToBeLowered
                    return Some(Expr {
                        loc: v.loc,
                        data: ExprData::EBinary(e_handle),
                    });
                }
            }
            _ => {}
        }

        v.is_stmt_expr = matches!(p.stmt_expr_value, ExprData::EBinary(ptr) if core::ptr::eq(ptr.as_ptr(), std::ptr::from_mut(e_)));

        v.left_in = ExprIn {
            assign_target: Op::Code::binary_assign_target(e_.op),
            ..ExprIn::default()
        };

        None
    }
}

// ported from: src/js_parser/ast/visitBinaryExpression.zig