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
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
//! Port of `src/js_parser/js_parser.zig`.
//!
//! NOTE on arena slices: this is the AST crate. Nearly every `[]const u8` /
//! `[]T` struct field in the Zig points into either the source text or the
//! parser arena and is bulk-freed at end-of-parse. Per PORTING.md, lifetime
//! params are not added to AST structs; arena-owned slices are typed as
//! `StoreSlice<T>` / `StoreStr` here. TODO(refactor): thread a crate-wide
//! `'bump` and rewrite these to `&'bump [T]` / `&'bump mut [T]`.

// `lexer::NewLexer<J: JsonOptionsT>` models Zig's `NewLexer(comptime
// json_options)`: the option set is a ZST *type* parameter and the comptime
// branches read its associated consts (`if J::IS_JSON { … }`), which
// monomorphize exactly like const-generic `bool` slots. Stable-compatible
// since #63 W3 — no `generic_const_exprs` (assoc-const projection into const
// args) and no `adt_const_params` (`JSONOptions` as a const-param type) any
// more; `JSONOptions` survives as the runtime reification
// (`JsonOptionsT::OPTIONS`).
pub use bun_collections::VecExt as _VecExtReexport;

// ─── module layout (see docs/REFACTOR_BUN_AST.md) ───────────────────────────
pub mod parser;
// Re-export parser-helper types at crate root so p.rs can `use crate::{...}`.
pub use parser::*;
pub mod lexer;

pub mod fold;
pub mod lower;
pub mod p;
pub mod parse;
pub mod repl_transforms;
pub mod scan;
pub mod typescript;
pub mod visit;

pub use p::P;
pub use parse::parse_entry::{Options as ParserOptions, Parser};

// `pub const Macro = @import("../js_parser_jsc/Macro.zig");`
// Full impl lives in *_jsc; this stub re-exposes the JSC-free constants and a
// placeholder `MacroContext` so lower-tier crates (bundler, transpiler) that
// only need the namespace strings / a context handle stay unblocked.
#[allow(non_snake_case)]
pub mod Macro {
    /// Zig: `pub const namespace: string = "macro";`
    pub const NAMESPACE: &[u8] = b"macro";
    /// Zig: `pub const namespaceWithColon: string = namespace ++ ":";`
    pub const NAMESPACE_WITH_COLON: &[u8] = b"macro:";

    #[inline]
    pub fn is_macro_path(str_: &[u8]) -> bool {
        str_.starts_with(NAMESPACE_WITH_COLON)
    }

    /// Spec `bundler_jsc/PluginRunner.zig:MacroJSCtx` (= `JSC.JSValue`).
    ///
    /// `JSValue` is `#[repr(transparent)] i64` (PORTING.md §JSC types). This
    /// newtype carries the encoded bits at the lowest tier that needs them so
    /// `Transpiler::ParseOptions.macro_js_ctx` and `MacroContext.javascript_object`
    /// share one canonical type without `bun_js_parser` / `bun_bundler` taking a
    /// `bun_jsc` dep. Higher tiers convert with `JSValue(ctx.0)` / `MacroJSCtx(v.0)`.
    #[repr(transparent)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug)]
    pub struct MacroJSCtx(pub i64);
    impl MacroJSCtx {
        /// Spec `default_macro_js_value` = `JSValue.zero`.
        pub const ZERO: Self = MacroJSCtx(0);
    }
    impl Default for MacroJSCtx {
        #[inline]
        fn default() -> Self {
            Self::ZERO
        }
    }

    /// Lower-tier handle for `js_parser_jsc::Macro::MacroContext`.
    ///
    /// Real fields (`env`, `macros`, `remap`, `resolver`, `bump`) reference
    /// `Transpiler` and JSC types that live in crates which depend on
    /// `bun_js_parser`. To break the dep cycle the higher-tier `_jsc` crate
    /// owns that state behind `data`; the visit pass reaches it via
    /// link-time-resolved `extern "Rust"` fns so `visitExpr.rs` stays a
    /// faithful port of `visitExpr.zig:415` / `:1443` without an upward
    /// import. `javascript_object` is surfaced here so `Transpiler::parse` can
    /// thread `this_parse.macro_js_ctx` through (spec transpiler.zig:938-940)
    /// without this crate depending on `bun_jsc::JSValue`.
    pub struct MacroContext {
        /// Encoded `JSC.JSValue` (the caller-supplied macro JS context).
        /// `bun_js_parser_jsc` reinterprets the bits as a `JSValue`.
        pub javascript_object: MacroJSCtx,
        /// Opaque pointer to the higher-tier macro-runner state
        /// (resolver/env/macros/remap/bump). Allocated by `init` and leaked
        /// (matches Zig's process-lifetime `default_allocator`);
        /// `bun_js_parser` never dereferences it.
        pub data: *mut core::ffi::c_void,
    }
    impl Default for MacroContext {
        #[inline]
        fn default() -> Self {
            Self {
                javascript_object: MacroJSCtx::ZERO,
                data: core::ptr::null_mut(),
            }
        }
    }
    unsafe extern "Rust" {
        /// Defined `#[no_mangle]` in `bun_js_parser_jsc::Macro`. `transpiler`
        /// is `*mut bun_bundler::Transpiler<'_>` — erased because this crate
        /// cannot name it (dep-cycle).
        // NOT `safe fn`: callee derefs `transpiler` as `&mut Transpiler<'_>` —
        // caller must guarantee it is non-null, exclusively borrowed, and of
        // that exact concrete type.
        fn __bun_macro_context_init(transpiler: *mut core::ffi::c_void) -> MacroContext;
        // NOT `safe fn`: when non-null, `data` must be the exact `Box::into_raw`
        // value produced by `__bun_macro_context_init` and uniquely owned
        // (callee `Box::from_raw`s it → double-free / aliasing UB otherwise).
        fn __bun_macro_context_deinit(data: *mut core::ffi::c_void);
        // All args are safe Rust-ABI types (refs/slices/by-value); the only
        // raw pointer involved is `ctx.data`, which is a struct invariant
        // maintained by `init`/`Default` — not a caller precondition. The
        // `#[no_mangle]` body in `bun_js_parser_jsc` is itself a safe `pub fn`.
        safe fn __bun_macro_context_call(
            ctx: &mut MacroContext,
            import_record_path: &[u8],
            source_dir: &[u8],
            log: &mut bun_ast::Log,
            source: &bun_ast::Source,
            import_range: bun_ast::Range,
            caller: bun_ast::Expr,
            function_name: &[u8],
        ) -> Result<bun_ast::Expr, bun_core::Error>;
        // NOT `safe fn`: callee derefs `data` unconditionally as
        // `&MacroContext` — caller must guarantee non-null + produced by
        // `__bun_macro_context_init` + the backing `Transpiler.options` table
        // outlives the returned `'static` borrow.
        fn __bun_macro_context_get_remap(
            data: *mut core::ffi::c_void,
            path: &[u8],
        ) -> Option<&'static MacroRemapEntry>;
        // No raw-pointer args; the body is a safe `pub fn` in
        // `bun_js_parser_jsc`. See [`collect_vm_garbage`] for the call-site
        // contract.
        safe fn __bun_macro_collect_vm_garbage();
    }

    /// Sweep this thread's bundler-macro VM so JS-wrapper-owned native boxes
    /// (e.g. a `new Bun.Transpiler()` constructed inside a macro body) are
    /// finalized before the worker thread's TLS root vanishes. Only call from
    /// `bun_bundler::ThreadPool::Worker::deinit` after both per-worker
    /// `MacroContext` boxes are freed — every other `MacroContext::deinit`
    /// path is either inside JS execution or inside a GC sweep, where
    /// re-entering `run_gc(true)` is unsound.
    #[inline]
    pub fn collect_vm_garbage() {
        __bun_macro_collect_vm_garbage();
    }
    impl MacroContext {
        /// Zig: `pub fn call(self: *MacroContext, import_record_path, source_dir,
        /// log, source, import_range, caller, function_name) !Expr`.
        #[inline]
        pub fn call(
            &mut self,
            import_record_path: &[u8],
            source_dir: &[u8],
            log: &mut bun_ast::Log,
            source: &bun_ast::Source,
            import_range: bun_ast::Range,
            caller: bun_ast::Expr,
            function_name: &[u8],
        ) -> Result<bun_ast::Expr, bun_core::Error> {
            __bun_macro_context_call(
                self,
                import_record_path,
                source_dir,
                log,
                source,
                import_range,
                caller,
                function_name,
            )
        }
        /// Zig: `pub fn init(transpiler: *Transpiler) MacroContext`.
        ///
        /// `T` is always `bun_bundler::Transpiler<'_>`; generic so callers in
        /// `bun_bundler`/`bun_runtime` compile without `bun_js_parser` taking
        /// an upward dep on the bundler. The `_jsc` crate reads the concrete
        /// type back inside `__bun_macro_context_init`.
        #[inline]
        pub fn init<T>(transpiler: &mut T) -> Self {
            // SAFETY: `transpiler` is a live `&mut T` (exclusive, non-null,
            // aligned) for the duration of the call; the callee casts it back to
            // `&mut Transpiler<'_>` and only reads/borrows fields — it does not
            // retain the pointer past return (the boxed state it allocates owns
            // its own data).
            unsafe {
                __bun_macro_context_init(
                    core::ptr::from_mut(transpiler).cast::<core::ffi::c_void>(),
                )
            }
        }
        /// Free the boxed higher-tier state behind `data`. Only call when the
        /// owning `Transpiler` is a short-lived bytewise clone (e.g. the
        /// off-thread `RuntimeTranspilerStore` worker) — the long-lived
        /// `vm.transpiler` instance leaks it intentionally (process-lifetime).
        #[inline]
        pub fn deinit(self) {
            // SAFETY: `self.data` is either null (callee no-ops) or the exact
            // `Box::into_raw` produced by `__bun_macro_context_init`; `self` is
            // taken by value so this is the unique owner and no double-free is
            // possible.
            unsafe { __bun_macro_context_deinit(self.data) }
        }
        /// Zig: `pub fn getRemap(self: *MacroContext, path: []const u8) ?MacroRemapEntry`.
        /// Returns `'static` so callers can keep the result across `&mut self`
        /// parser calls without a borrowck conflict; the table lives in
        /// `Transpiler.options` which outlives every parse.
        #[inline]
        pub fn get_remap(&self, path: &[u8]) -> Option<&'static MacroRemapEntry> {
            if self.data.is_null() {
                return None;
            }
            // SAFETY: `self.data` is non-null (checked above) and was produced by
            // `__bun_macro_context_init`, so it points at a live `Macro::Data`
            // whose remap table the callee borrows. The table is owned by
            // `Transpiler.options` (process-lifetime), justifying the `'static`
            // return.
            unsafe { __bun_macro_context_get_remap(self.data, path) }
        }
    }

    /// Zig: `MacroImportReplacementMap` — `bun.StringArrayHashMap([]const u8)`.
    /// Values are owned (`Box<[u8]>`) so callers can populate without `unsafe`
    /// lifetime-extension casts; matches `bun_resolver::package_json::MacroImportReplacementMap`.
    pub type MacroRemapEntry = bun_collections::StringArrayHashMap<Box<[u8]>>;
}
use bun_ast::{Ast, Ref};

// NOTE: shadows the prelude `Result` for this module — all error-union return
// types in this file are spelled `core::result::Result<T, E>` to disambiguate.
//
// PERF NOTE: `bun_ast::Ast` is ~1 KB (40+ fields incl. Scope, NamedImports,
// NamedExports, CharFreq, several HashMaps). Storing it inline made this enum
// ~1 KB and forced a ~1 KB memmove at every layer of the return chain
// `P::to_ast → _parse → parse → cache::JavaScript::parse → Transpiler::parse_*`
// (Zig sidesteps this via result-location semantics; Rust does not). Boxing the
// `Ast` variant collapses `Result` to 16 B so only a thin pointer is moved up
// the stack — one mimalloc-arena alloc per parsed module is far cheaper than
// 4+ kilobyte memmoves. The other variants are already tiny.
pub enum Result<'a> {
    AlreadyBundled(AlreadyBundled),
    Cached,
    Ast(Box<Ast<'a>>),
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum AlreadyBundled {
    Bun,
    BunCjs,
    Bytecode,
    BytecodeCjs,
}

/// `impl EqlParser for P` — moved out of `bun_ast::expr` (next to `P`).
impl<'a, const IS_TS: bool, const SCAN: bool> bun_ast::expr::EqlParser
    for crate::p::P<'a, IS_TS, SCAN>
{
    #[inline]
    fn arena(&self) -> &bun_alloc::Arena {
        self.arena
    }
    #[inline]
    fn module_ref(&self) -> Ref {
        self.module_ref
    }
}

pub mod defines_table;

// ─── from bun_bundler::defines (src/bundler/defines.zig) ────────────────────
// B-3 UNIFIED: canonical `Define` / `DefineData` / `DotDefine` live here so the
// parser (`P.define: &'a Define`) and the bundler (`BundleOptions.define:
// Box<Define>`) share one nominal type. `bun_bundler::defines` re-exports these
// and layers the json-parse / dotenv `init` on top via an extension trait. The
// pure-global fallback table also lives at this tier (`defines_table`) so
// `for_identifier` reads its own const — no cross-crate hook.
pub mod defines {
    use bun_collections::{StringArrayHashMap, StringHashMap};
    use bun_core::strings;

    use bun_ast::E;
    use bun_ast::StoreRef;
    use bun_ast::expr::Data as ExprData;

    // Zig: `bun.StringArrayHashMap(string)` / `bun.StringArrayHashMap(DefineData)`.
    pub type RawDefines = StringArrayHashMap<Box<[u8]>>;
    pub type UserDefines = StringHashMap<DefineData>;
    pub type UserDefinesArray = StringArrayHashMap<DefineData>;

    pub type IdentifierDefine = DefineData;

    #[derive(Clone)]
    pub struct DotDefine {
        // Zig stored borrowed `[][]const u8` into static tables / user-define
        // key strings; the Rust port owns the part strings (small, allocated
        // once at startup). PERF(port): tiny copies.
        pub parts: Vec<Box<[u8]>>,
        pub data: DefineData,
    }

    /// Zig: `packed struct(u8)` — `_padding: u3, valueless: bool,
    /// can_be_removed_if_unused: bool, call_can_be_unwrapped_if_unused:
    /// E.CallUnwrap (u2), method_call_must_be_replaced_with_undefined: bool`.
    /// Packed LSB-first → bit positions below match the Zig layout exactly.
    #[repr(transparent)]
    #[derive(Clone, Copy, Default, PartialEq, Eq)]
    pub struct Flags(u8);

    impl Flags {
        const VALUELESS_SHIFT: u8 = 3;
        const CAN_BE_REMOVED_SHIFT: u8 = 4;
        const CALL_UNWRAP_SHIFT: u8 = 5;
        const CALL_UNWRAP_MASK: u8 = 0b11 << Self::CALL_UNWRAP_SHIFT;
        const METHOD_CALL_UNDEF_SHIFT: u8 = 7;

        #[inline]
        pub const fn valueless(self) -> bool {
            (self.0 >> Self::VALUELESS_SHIFT) & 1 != 0
        }
        #[inline]
        pub fn set_valueless(&mut self, v: bool) {
            self.0 =
                (self.0 & !(1 << Self::VALUELESS_SHIFT)) | ((v as u8) << Self::VALUELESS_SHIFT);
        }
        #[inline]
        pub const fn can_be_removed_if_unused(self) -> bool {
            (self.0 >> Self::CAN_BE_REMOVED_SHIFT) & 1 != 0
        }
        #[inline]
        pub fn set_can_be_removed_if_unused(&mut self, v: bool) {
            self.0 = (self.0 & !(1 << Self::CAN_BE_REMOVED_SHIFT))
                | ((v as u8) << Self::CAN_BE_REMOVED_SHIFT);
        }
        #[inline]
        pub fn call_can_be_unwrapped_if_unused(self) -> E::CallUnwrap {
            // 2-bit field; `E::CallUnwrap` only has discriminants 0/1/2, so
            // an explicit match keeps bit-pattern 3 sound.
            match (self.0 & Self::CALL_UNWRAP_MASK) >> Self::CALL_UNWRAP_SHIFT {
                1 => E::CallUnwrap::IfUnused,
                2 => E::CallUnwrap::IfUnusedAndToStringSafe,
                _ => E::CallUnwrap::Never,
            }
        }
        #[inline]
        pub fn set_call_can_be_unwrapped_if_unused(&mut self, v: E::CallUnwrap) {
            self.0 = (self.0 & !Self::CALL_UNWRAP_MASK)
                | (((v as u8) & 0b11) << Self::CALL_UNWRAP_SHIFT);
        }
        #[inline]
        pub const fn method_call_must_be_replaced_with_undefined(self) -> bool {
            (self.0 >> Self::METHOD_CALL_UNDEF_SHIFT) & 1 != 0
        }
        #[inline]
        pub fn set_method_call_must_be_replaced_with_undefined(&mut self, v: bool) {
            self.0 = (self.0 & !(1 << Self::METHOD_CALL_UNDEF_SHIFT))
                | ((v as u8) << Self::METHOD_CALL_UNDEF_SHIFT);
        }
        pub fn new(
            valueless: bool,
            can_be_removed_if_unused: bool,
            call_can_be_unwrapped_if_unused: E::CallUnwrap,
            method_call_must_be_replaced_with_undefined: bool,
        ) -> Self {
            let mut f = Flags(0);
            f.set_valueless(valueless);
            f.set_can_be_removed_if_unused(can_be_removed_if_unused);
            f.set_call_can_be_unwrapped_if_unused(call_can_be_unwrapped_if_unused);
            f.set_method_call_must_be_replaced_with_undefined(
                method_call_must_be_replaced_with_undefined,
            );
            f
        }
    }

    #[derive(Clone)]
    pub struct DefineData {
        pub value: ExprData,
        // Zig stored `original_name_ptr: ?[*]const u8` + `original_name_len: u32`
        // borrowing into caller-owned strings (defines.zig:24-25 — the 48→40-byte
        // packing trick). The Rust port owns the `RawDefines` value bytes
        // (`Box<[u8]>`), so borrowing would be a use-after-free once the
        // `RawDefines` map is dropped after `Define::init`. Own the bytes here
        // instead — these are tiny startup-time copies.
        // Kept `pub` so the bundler-side `parse`/`from_input` (which live a
        // tier up for json-parser access) can construct directly.
        pub original_name: Option<Box<[u8]>>,
        pub flags: Flags,
    }

    // SAFETY: `ExprData` contains `StoreRef` raw pointers into immutable,
    // process-lifetime AST stores. `DefineData` is only shared across threads
    // via the read-only `Box<Define>` after init. Never written through.
    unsafe impl Send for DefineData {}
    // SAFETY: see `Send` impl above — the `StoreRef` targets are immutable and
    // process-lifetime, and `DefineData` is read-only after init.
    unsafe impl Sync for DefineData {}

    impl Default for DefineData {
        fn default() -> Self {
            Self {
                // Zig: `.e_missing = .{}`
                value: ExprData::EMissing(E::Missing),
                original_name: None,
                flags: Flags::default(),
            }
        }
    }

    /// Named-init shim (mirrors Zig anonymous-struct init).
    #[derive(Clone, Copy)]
    pub struct Options<'a> {
        pub original_name: Option<&'a [u8]>,
        pub value: ExprData,
        pub valueless: bool,
        pub can_be_removed_if_unused: bool,
        pub call_can_be_unwrapped_if_unused: E::CallUnwrap,
        pub method_call_must_be_replaced_with_undefined: bool,
    }
    impl<'a> Default for Options<'a> {
        fn default() -> Self {
            Self {
                original_name: None,
                value: ExprData::EMissing(E::Missing),
                valueless: false,
                can_be_removed_if_unused: false,
                call_can_be_unwrapped_if_unused: E::CallUnwrap::Never,
                method_call_must_be_replaced_with_undefined: false,
            }
        }
    }

    impl DefineData {
        pub fn init(options: Options<'_>) -> DefineData {
            DefineData {
                value: options.value,
                flags: Flags::new(
                    options.valueless,
                    options.can_be_removed_if_unused,
                    options.call_can_be_unwrapped_if_unused,
                    options.method_call_must_be_replaced_with_undefined,
                ),
                original_name: options.original_name.map(Box::<[u8]>::from),
            }
        }

        #[inline]
        pub fn original_name(&self) -> Option<&[u8]> {
            match &self.original_name {
                Some(name) if !name.is_empty() => Some(name.as_ref()),
                _ => None,
            }
        }

        /// True if accessing this value is known to not have any side effects.
        #[inline]
        pub fn can_be_removed_if_unused(&self) -> bool {
            self.flags.can_be_removed_if_unused()
        }
        /// True if a call to this value is known to not have any side effects.
        #[inline]
        pub fn call_can_be_unwrapped_if_unused(&self) -> E::CallUnwrap {
            self.flags.call_can_be_unwrapped_if_unused()
        }
        #[inline]
        pub fn method_call_must_be_replaced_with_undefined(&self) -> bool {
            self.flags.method_call_must_be_replaced_with_undefined()
        }
        #[inline]
        pub fn valueless(&self) -> bool {
            self.flags.valueless()
        }

        pub fn init_boolean(value: bool) -> DefineData {
            let mut flags = Flags::default();
            flags.set_can_be_removed_if_unused(true);
            DefineData {
                value: ExprData::EBoolean(E::Boolean { value }),
                flags,
                ..Default::default()
            }
        }

        pub fn init_static_string(str: &'static E::EString) -> DefineData {
            let mut flags = Flags::default();
            flags.set_can_be_removed_if_unused(true);
            DefineData {
                // Zig: @constCast(str) — Expr.Data.e_string stores *E.String.
                value: ExprData::EString(StoreRef::from_static(str)),
                flags,
                ..Default::default()
            }
        }

        pub fn merge(a: &DefineData, b: DefineData) -> DefineData {
            DefineData {
                value: b.value,
                flags: Flags::new(
                    // TODO: investigate if this is correct. This is what it was before.
                    a.method_call_must_be_replaced_with_undefined()
                        || b.method_call_must_be_replaced_with_undefined(),
                    a.can_be_removed_if_unused(),
                    a.call_can_be_unwrapped_if_unused(),
                    a.method_call_must_be_replaced_with_undefined()
                        || b.method_call_must_be_replaced_with_undefined(),
                ),
                original_name: b.original_name,
            }
        }
    }

    #[derive(Default)]
    pub struct Define {
        pub identifiers: StringHashMap<IdentifierDefine>,
        pub dots: StringHashMap<Vec<DotDefine>>,
        pub drop_debugger: bool,
    }

    impl Define {
        pub fn for_identifier(&self, name: &[u8]) -> Option<&IdentifierDefine> {
            if let Some(data) = self.identifiers.get(name) {
                return Some(data);
            }
            crate::defines_table::lookup_pure_global_identifier(name).map(|v| v.value())
        }

        // Zig: `comptime Iterator: type, iter: Iterator` — type param dropped.
        pub fn insert_from_iterator<'a, I>(&mut self, iter: I) -> Result<(), bun_alloc::AllocError>
        where
            I: Iterator<Item = (&'a [u8], &'a DefineData)>,
        {
            for (key, value) in iter {
                self.insert(key, value.clone())?;
            }
            Ok(())
        }

        pub fn insert(
            &mut self,
            key: &[u8],
            value: DefineData,
        ) -> Result<(), bun_alloc::AllocError> {
            // If it has a dot, then it's a DotDefine. e.g. process.env.NODE_ENV
            if let Some(last_dot) = strings::last_index_of_char(key, b'.') {
                let tail = &key[last_dot + 1..key.len()];
                let remainder = &key[0..last_dot];
                let count = remainder.iter().filter(|&&b| b == b'.').count() + 1;
                let mut parts: Vec<Box<[u8]>> = Vec::with_capacity(count + 1);
                for split in remainder.split(|b| *b == b'.') {
                    parts.push(Box::from(split));
                }
                parts.push(Box::from(tail));

                let mut initial_values: &[DotDefine] = &[];
                // PORT NOTE: reshaped for borrowck — getOrPut split into get/insert.
                if let Some(existing) = self.dots.get_mut(tail) {
                    for part in existing.iter_mut() {
                        if are_parts_equal(&part.parts, &parts) {
                            part.data = DefineData::merge(&part.data, value);
                            return Ok(());
                        }
                    }
                    initial_values = existing.as_slice();
                }

                let mut list: Vec<DotDefine> = Vec::with_capacity(initial_values.len() + 1);
                if !initial_values.is_empty() {
                    list.extend_from_slice(initial_values);
                }
                list.push(DotDefine { data: value, parts });
                self.dots.put_assume_capacity(tail, list);
            } else {
                // e.g. IS_BROWSER
                self.identifiers.put_assume_capacity(key, value);
            }
            Ok(())
        }
    }

    pub fn are_parts_equal(a: &[Box<[u8]>], b: &[Box<[u8]>]) -> bool {
        if a.len() != b.len() {
            return false;
        }
        for i in 0..a.len() {
            if !strings::eql(&a[i], &b[i]) {
                return false;
            }
        }
        true
    }
}
pub use defines::{Define, DefineData};

pub mod defines_full_draft {
    use bstr::BStr;
    use bun_collections::{ArrayHashMap, StringHashMap};
    use bun_core::strings;

    use bun_ast::base::Ref;
    use bun_ast::e as E;
    use bun_ast::expr;

    use crate::lexer as js_lexer;
    use bun_ast::StoreRef;

    // Zig: `bun.StringArrayHashMap(string)` / `bun.StringHashMap(DefineData)`
    pub type RawDefines = ArrayHashMap<Box<[u8]>, Box<[u8]>>;
    pub type UserDefines = StringHashMap<DefineData>;
    pub type UserDefinesArray = ArrayHashMap<Box<[u8]>, DefineData>;

    pub type IdentifierDefine = DefineData;

    #[derive(Clone)]
    pub struct DotDefine {
        // Zig stored borrowed `[][]const u8` into the user-define key strings;
        // the Rust port owns the part bytes (small, allocated once at startup)
        // so the `RawDefines` map can be dropped after `Define::init`.
        pub parts: Vec<Box<[u8]>>,
        pub data: DefineData,
    }

    bitflags::bitflags! {
        // Zig: `packed struct(u8) { _padding: u3, valueless, can_be_removed_if_unused,
        //        call_can_be_unwrapped_if_unused: E.CallUnwrap (u2), method_call_must_be_replaced_with_undefined }`
        // Packed LSB-first → bit positions below match the Zig layout exactly.
        #[derive(Copy, Clone, Default)]
        pub struct DefineDataFlags: u8 {
            const VALUELESS                                  = 1 << 3;
            const CAN_BE_REMOVED_IF_UNUSED                   = 1 << 4;
            // bits 5..7 hold `E::CallUnwrap` (2 bits) — read via accessor below.
            const METHOD_CALL_MUST_BE_REPLACED_WITH_UNDEFINED = 1 << 7;
        }
    }
    const CALL_UNWRAP_SHIFT: u8 = 5;
    const CALL_UNWRAP_MASK: u8 = 0b11 << CALL_UNWRAP_SHIFT;

    #[derive(Clone)]
    pub struct DefineData {
        pub value: expr::Data,
        // Zig stored `original_name_ptr: ?[*]const u8` + `original_name_len: u32`
        // borrowing into caller-owned strings (defines.zig:24-25 — the 48→40-byte
        // packing trick). The Rust port owns the `RawDefines` value bytes
        // (`Box<[u8]>`), so borrowing would be a use-after-free once the
        // `RawDefines` map is dropped after `Define::init`. Own the bytes here
        // instead — these are tiny startup-time copies.
        pub original_name: Option<Box<[u8]>>,
        pub flags: DefineDataFlags,
    }

    impl Default for DefineData {
        fn default() -> Self {
            Self {
                value: expr::Data::EUndefined(E::Undefined {}),
                original_name: None,
                flags: DefineDataFlags::empty(),
            }
        }
    }

    impl DefineData {
        #[inline]
        pub fn original_name(&self) -> Option<&[u8]> {
            match &self.original_name {
                Some(name) if !name.is_empty() => Some(name.as_ref()),
                _ => None,
            }
        }

        /// True if accessing this value is known to not have any side effects. For
        /// example, a bare reference to "Object.create" can be removed because it
        /// does not have any observable side effects.
        #[inline]
        pub fn can_be_removed_if_unused(&self) -> bool {
            self.flags
                .contains(DefineDataFlags::CAN_BE_REMOVED_IF_UNUSED)
        }

        /// True if a call to this value is known to not have any side effects. For
        /// example, a bare call to "Object()" can be removed because it does not
        /// have any observable side effects.
        #[inline]
        pub fn call_can_be_unwrapped_if_unused(&self) -> E::CallUnwrap {
            // 2-bit field; explicit match keeps bit-pattern 3 sound.
            match (self.flags.bits() & CALL_UNWRAP_MASK) >> CALL_UNWRAP_SHIFT {
                0 => E::CallUnwrap::Never,
                1 => E::CallUnwrap::IfUnused,
                2 => E::CallUnwrap::IfUnusedAndToStringSafe,
                _ => E::CallUnwrap::Never,
            }
        }

        #[inline]
        pub fn method_call_must_be_replaced_with_undefined(&self) -> bool {
            self.flags
                .contains(DefineDataFlags::METHOD_CALL_MUST_BE_REPLACED_WITH_UNDEFINED)
        }

        #[inline]
        pub fn valueless(&self) -> bool {
            self.flags.contains(DefineDataFlags::VALUELESS)
        }

        pub fn init_boolean(value: bool) -> DefineData {
            DefineData {
                value: expr::Data::EBoolean(E::Boolean { value }),
                flags: DefineDataFlags::CAN_BE_REMOVED_IF_UNUSED,
                ..Default::default()
            }
        }

        pub fn init_static_string(str_: &'static E::String) -> DefineData {
            DefineData {
                // Zig `@constCast` — Expr.Data stores StoreRef (NonNull); the static is never mutated.
                value: expr::Data::EString(StoreRef::from_static(str_)),
                flags: DefineDataFlags::CAN_BE_REMOVED_IF_UNUSED,
                ..Default::default()
            }
        }

        pub fn merge(a: &DefineData, b: &DefineData) -> DefineData {
            let mut flags = DefineDataFlags::empty();
            if a.can_be_removed_if_unused() {
                flags |= DefineDataFlags::CAN_BE_REMOVED_IF_UNUSED;
            }
            flags = DefineDataFlags::from_bits_retain(
                flags.bits() | ((a.call_can_be_unwrapped_if_unused() as u8) << CALL_UNWRAP_SHIFT),
            );
            // TODO: investigate if this is correct. This is what it was before. But that looks strange.
            if a.method_call_must_be_replaced_with_undefined()
                || b.method_call_must_be_replaced_with_undefined()
            {
                flags |= DefineDataFlags::VALUELESS;
                flags |= DefineDataFlags::METHOD_CALL_MUST_BE_REPLACED_WITH_UNDEFINED;
            }
            DefineData {
                value: b.value,
                flags,
                original_name: b.original_name.clone(),
            }
        }

        // REFACTOR_BUN_AST: `bun_js_parser` is a sibling of `bun_parsers`, so the
        // JSON-value branch takes a parser callback (the bundler passes
        // `bun_parsers::json::parse_env_json`). With the unified `Expr` type,
        // the result is the same `bun_ast::Expr` the rest of the parser uses —
        // the former `json_data_to_expr_data` lift is gone.
        pub fn parse(
            key: &[u8],
            value_str: &[u8],
            value_is_undefined: bool,
            method_call_must_be_replaced_with_undefined: bool,
            log: &mut bun_ast::Log,
            bump: &bun_alloc::Arena,
            parse_json: &dyn Fn(
                &bun_ast::Source,
                &mut bun_ast::Log,
                &bun_alloc::Arena,
            )
                -> core::result::Result<bun_ast::Expr, bun_core::Error>,
        ) -> core::result::Result<DefineData, bun_core::Error> {
            for part in key.split(|&c| c == b'.') {
                if !js_lexer::is_identifier(part) {
                    if strings::eql(part, key) {
                        log.add_error_fmt(
                            None,
                            bun_ast::Loc::default(),
                            format_args!(
                                "define key \"{}\" must be a valid identifier",
                                BStr::new(key)
                            ),
                        );
                    } else {
                        log.add_error_fmt(
                            None,
                            bun_ast::Loc::default(),
                            format_args!(
                                "define key \"{}\" contains invalid identifier \"{}\"",
                                BStr::new(part),
                                BStr::new(value_str)
                            ),
                        );
                    }
                    break;
                }
            }

            // check for nested identifiers
            let mut is_ident = true;
            for part in value_str.split(|&c| c == b'.') {
                if !js_lexer::is_identifier(part) || js_lexer::keyword(part).is_some() {
                    is_ident = false;
                    break;
                }
            }

            let mut flags = DefineDataFlags::empty();
            if value_is_undefined {
                flags |= DefineDataFlags::VALUELESS;
            }
            if method_call_must_be_replaced_with_undefined {
                flags |= DefineDataFlags::METHOD_CALL_MUST_BE_REPLACED_WITH_UNDEFINED;
            }

            if is_ident {
                // Special-case undefined. it's not an identifier here
                // https://github.com/evanw/esbuild/issues/1407
                let value = if value_is_undefined || value_str == b"undefined" {
                    expr::Data::EUndefined(E::Undefined {})
                } else {
                    expr::Data::EIdentifier(
                        E::Identifier::init(Ref::NONE).with_can_be_removed_if_unused(true),
                    )
                };
                flags |= DefineDataFlags::CAN_BE_REMOVED_IF_UNUSED;
                return Ok(DefineData {
                    value,
                    original_name: if value_str.is_empty() {
                        None
                    } else {
                        Some(Box::<[u8]>::from(value_str))
                    },
                    flags,
                });
            }

            // Value is JSON — round-trip through the env-JSON parser.
            let source = bun_ast::Source {
                contents: std::borrow::Cow::Owned(value_str.to_vec()),
                path: bun_paths::fs::Path::init_with_namespace(b"defines.json", b"internal"),
                ..Default::default()
            };
            let expr = parse_json(&source, log, bump)?;
            // Zig: `expr.data.deepClone(arena)` followed by `expr.isPrimitiveLiteral()`.
            // With one `Expr` type the parser result is already in the target
            // shape; `deep_clone` re-roots payloads in `bump`.
            let cloned = expr.data.deep_clone(bump)?;
            if expr.is_primitive_literal() {
                flags |= DefineDataFlags::CAN_BE_REMOVED_IF_UNUSED;
            }
            Ok(DefineData {
                value: cloned,
                original_name: if value_str.is_empty() {
                    None
                } else {
                    Some(Box::<[u8]>::from(value_str))
                },
                flags,
            })
        }
    }

    pub struct Define {
        pub identifiers: StringHashMap<IdentifierDefine>,
        pub dots: StringHashMap<Vec<DotDefine>>,
        pub drop_debugger: bool,
    }

    impl Define {
        // Zig: `pub const Data = DefineData;` — Rust callers import `DefineData` directly.

        pub fn for_identifier(&self, name: &[u8]) -> Option<&IdentifierDefine> {
            if let Some(data) = self.identifiers.get(name) {
                return Some(data);
            }
            // Draft module — pure-global table is wired into the canonical
            // `crate::defines::Define` (this draft type is unused).
            None
        }

        pub fn insert(
            &mut self,
            bump: &bun_alloc::Arena,
            key: &[u8],
            value: DefineData,
        ) -> core::result::Result<(), bun_alloc::AllocError> {
            let _ = bump;
            // If it has a dot, then it's a DotDefine.
            // e.g. process.env.NODE_ENV
            if let Some(last_dot) = strings::last_index_of_char(key, b'.') {
                let tail = &key[last_dot + 1..];
                let remainder = &key[..last_dot];
                let count = remainder.iter().filter(|&&c| c == b'.').count() + 1;
                // Zig allocated `[][]const u8` borrowing the input key; the Rust
                // port owns the part bytes (tiny startup-time copies) so the
                // caller can drop `key` after `Define::init`.
                let mut parts: Vec<Box<[u8]>> = Vec::with_capacity(count + 1);
                for split in remainder.split(|&c| c == b'.') {
                    parts.push(Box::from(split));
                }
                parts.push(Box::from(tail));

                // "NODE_ENV"
                let entry = self.dots.get_or_put(tail).unwrap().value_ptr;
                for part in entry.iter_mut() {
                    // ["process", "env"] === ["process", "env"]
                    if are_parts_equal(&part.parts, &parts) {
                        part.data = DefineData::merge(&part.data, &value);
                        return Ok(());
                    }
                }
                entry.push(DotDefine { data: value, parts });
            } else {
                // e.g. IS_BROWSER
                self.identifiers.put_assume_capacity(key, value);
            }
            Ok(())
        }

        pub fn init(
            user_defines: Option<UserDefines>,
            string_defines: Option<UserDefinesArray>,
            drop_debugger: bool,
            omit_unused_global_calls: bool,
            bump: &bun_alloc::Arena,
        ) -> core::result::Result<Box<Define>, bun_alloc::AllocError> {
            let _ = omit_unused_global_calls;
            let mut define = Box::new(Define {
                identifiers: StringHashMap::default(),
                dots: StringHashMap::default(),
                drop_debugger,
            });
            // TODO(port): Step 1/2 — load global_no_side_effect_* tables from
            // bun_bundler::defines_table once that table moves down. Omitting
            // here is safe-ish: only affects pure-annotation tree shaking.

            // Step 3. Load user data into hash tables
            // (Zig: `iter.next()` over `StringHashMap` — consume the inner map.)
            if let Some(mut user_defines) = user_defines {
                for (k, v) in core::mem::take(&mut *user_defines).into_iter() {
                    define.insert(bump, &k, v)?;
                }
            }
            // Step 4. Load environment data into hash tables.
            // (Zig: `it.next()` over `StringArrayHashMap` — `ArrayHashMap` has
            // no `IntoIterator`; walk insertion-order entries.)
            if let Some(mut string_defines) = string_defines {
                let mut it = string_defines.iterator();
                while let Some(entry) = it.next() {
                    define.insert(bump, &**entry.key_ptr, entry.value_ptr.clone())?;
                }
            }
            Ok(define)
        }
    }

    fn are_parts_equal(a: &[Box<[u8]>], b: &[Box<[u8]>]) -> bool {
        if a.len() != b.len() {
            return false;
        }
        for i in 0..a.len() {
            if !strings::eql(&a[i], &b[i]) {
                return false;
            }
        }
        true
    }
}

// ─── from bun_js_printer::renamer (src/js_printer/renamer.zig) ──────────────
// Only the slot-assignment helpers the parser calls (`P.rs:6658`) live here;
// the full `NumberRenamer`/`MinifyRenamer` machinery stays in `bun_js_printer`
// (it depends on the printer's name-buffer and reserved-names tables).
pub mod renamer {
    use bun_ast::SlotCounts;
    use bun_ast::base::Ref;
    use bun_ast::scope::Scope;
    use bun_ast::symbol::{INVALID_NESTED_SCOPE_SLOT, SlotNamespace, Symbol};
    use bun_collections::VecExt;

    pub(crate) fn assign_nested_scope_slots(
        _arena: &bun_alloc::Arena,
        module_scope: &Scope,
        symbols: &mut [Symbol],
    ) -> SlotCounts {
        let mut slot_counts = SlotCounts::default();
        let mut sorted_members: Vec<u32> = Vec::new();

        // Temporarily set the nested scope slots of top-level symbols to valid so
        // they aren't renamed in nested scopes. This prevents us from accidentally
        // assigning nested scope slots to variables declared using "var" in a nested
        // scope that are actually hoisted up to the module scope to become a top-
        // level symbol.
        const VALID_SLOT: u32 = 0;
        for member in module_scope.members.values() {
            symbols[member.ref_.inner_index() as usize].nested_scope_slot = VALID_SLOT;
        }
        for ref_ in module_scope.generated.slice() {
            symbols[ref_.inner_index() as usize].nested_scope_slot = VALID_SLOT;
        }

        for child in module_scope.children.slice() {
            // `StoreRef<Scope>: Deref<Target = Scope>` — safe arena-backed deref.
            slot_counts.union_max(assign_nested_scope_slots_helper(
                &mut sorted_members,
                child,
                symbols,
                SlotCounts::default(),
            ));
        }

        // Then set the nested scope slots of top-level symbols back to zero. Top-
        // level symbols are not supposed to have nested scope slots.
        for member in module_scope.members.values() {
            symbols[member.ref_.inner_index() as usize].nested_scope_slot =
                INVALID_NESTED_SCOPE_SLOT;
        }
        for ref_ in module_scope.generated.slice() {
            symbols[ref_.inner_index() as usize].nested_scope_slot = INVALID_NESTED_SCOPE_SLOT;
        }

        slot_counts
    }

    pub(crate) fn assign_nested_scope_slots_helper(
        sorted_members: &mut Vec<u32>,
        scope: &Scope,
        symbols: &mut [Symbol],
        slot_to_copy: SlotCounts,
    ) -> SlotCounts {
        let mut slot = slot_to_copy;

        // Sort member map keys for determinism
        {
            sorted_members.clear();
            sorted_members.reserve(scope.members.len());
            for member in scope.members.values() {
                sorted_members.push(member.ref_.inner_index());
            }
            sorted_members.sort_unstable();

            // Assign slots for this scope's symbols. Only do this if the slot is
            // not already assigned. Nested scopes have copies of symbols from parent
            // scopes and we want to use the slot from the parent scope, not child scopes.
            for &inner_index in sorted_members.iter() {
                let symbol = &mut symbols[inner_index as usize];
                let ns = symbol.slot_namespace();
                if ns != SlotNamespace::MustNotBeRenamed && symbol.nested_scope_slot().is_none() {
                    symbol.nested_scope_slot = slot.slots[ns];
                    slot.slots[ns] += 1;
                }
            }
        }

        for ref_ in scope.generated.slice() {
            let symbol = &mut symbols[ref_.inner_index() as usize];
            let ns = symbol.slot_namespace();
            if ns != SlotNamespace::MustNotBeRenamed && symbol.nested_scope_slot().is_none() {
                symbol.nested_scope_slot = slot.slots[ns];
                slot.slots[ns] += 1;
            }
        }

        // Labels are always declared in a nested scope, so we don't need to check.
        if let Some(ref_) = scope.label_ref {
            let symbol = &mut symbols[ref_.inner_index() as usize];
            let ns = SlotNamespace::Label;
            symbol.nested_scope_slot = slot.slots[ns];
            slot.slots[ns] += 1;
        }

        // Assign slots for the symbols of child scopes
        let mut slot_counts = slot;
        for child in scope.children.slice() {
            // `StoreRef<Scope>: Deref<Target = Scope>` — safe arena-backed deref.
            slot_counts.union_max(assign_nested_scope_slots_helper(
                sorted_members,
                child,
                symbols,
                slot,
            ));
        }

        slot_counts
    }

    #[derive(Copy, Clone)]
    pub struct StableSymbolCount {
        pub stable_source_index: u32,
        pub ref_: Ref,
        pub count: u32,
    }

    impl StableSymbolCount {
        pub fn less_than(i: &StableSymbolCount, j: &StableSymbolCount) -> bool {
            if i.count > j.count {
                return true;
            }
            if i.count < j.count {
                return false;
            }
            if i.stable_source_index < j.stable_source_index {
                return true;
            }
            if i.stable_source_index > j.stable_source_index {
                return false;
            }
            i.ref_.inner_index() < j.ref_.inner_index()
        }
    }

    // The remaining renamer types are only consumed by the printer and bundler
    // — they live in `bun_js_printer`.
}

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

// ───────────────────────────────────────────────────────────────────────────
// StackCheck calibration test surface (task #20 item 3)
//
// The toml/json/yaml parsers each grew a `stack_check_tests` module during BCE
// sweep #15; the JS parser — the deepest-recursing parser in the tree — never
// did (a comment referencing a Zig-calibrated `depth = 25_000` test described
// a calibration that did not exist here). This is that minimal surface:
//
//   • deep-but-legal nesting parses clean with real stack headroom
//   • pathological depth fails as an ORDERLY "Maximum call stack size
//     exceeded" log error, never a segfault
//   • the guard boundary is CALIBRATED: the depth where orderly errors begin
//     scales linearly with the thread stack size (no fixed depth cap), and
//     `StackCheck::is_safe_to_recurse` itself trips with ~128 KiB of stack
//     remaining (the platform headroom threshold in `bun_core::util`)
// ───────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod stack_check_tests {
    // ── link seam (test-only) ────────────────────────────────────────────
    // `MacroContext`'s `#[no_mangle]` providers live in the higher
    // `bun_js_parser_jsc` layer, which a `bun_js_parser` test binary cannot
    // link (same upward-seam class as bun_install's `__bun_regex_*`, see
    // `install/lib.rs`). These tests never exercise macro paths
    // (`Options.macro_context` stays `None`), so provide link-time bodies
    // that fail loudly if ever reached.
    #[unsafe(no_mangle)]
    extern "Rust" fn __bun_macro_context_get_remap(
        data: *mut core::ffi::c_void,
        path: &[u8],
    ) -> Option<&'static crate::Macro::MacroRemapEntry> {
        unreachable!("test-only link seam: macro context data = {data:?}, path = {path:?}")
    }
    #[unsafe(no_mangle)]
    extern "Rust" fn __bun_macro_collect_vm_garbage() {
        unreachable!("test-only link seam: macro VM sweep is out of scope here")
    }

    // TranspilerCache's real provider lives in the jsc tier; the parser only
    // dispatches when `r#impl` is `Some`, which these tests never set. Use the
    // sanctioned no-op registration generated by `link_interface!`.
    bun_ast::link_noop_TranspilerCacheImpl!(Jsc);

    #[unsafe(no_mangle)]
    extern "Rust" fn __bun_macro_context_call(
        _ctx: &mut crate::Macro::MacroContext,
        _import_record_path: &[u8],
        _source_dir: &[u8],
        _log: &mut bun_ast::Log,
        _source: &bun_ast::Source,
        _import_range: bun_ast::Range,
        _caller: bun_ast::Expr,
        _function_name: &[u8],
    ) -> Result<bun_ast::Expr, bun_core::Error> {
        unreachable!("test-only link seam: macro invocation is out of scope here")
    }

    // ftrace backend providers live in `bao_runtime` (`linux_trace.rs`) —
    // not linkable from here. "Backend not ready" (0) is the honest answer
    // for a test binary; `Linux::is_supported` caches it and skips emits.
    #[unsafe(no_mangle)]
    extern "C" fn Bun__linux_trace_init() -> core::ffi::c_int {
        0
    }
    #[unsafe(no_mangle)]
    extern "C" fn Bun__linux_trace_close() {}
    #[unsafe(no_mangle)]
    extern "C" fn Bun__linux_trace_emit(
        _event_name: *const core::ffi::c_char,
        _duration_ns: i64,
    ) -> core::ffi::c_int {
        0
    }

    use crate::defines::Define;
    use crate::{Parser, ParserOptions};
    use bun_alloc::Arena;
    use bun_ast::StoreResetGuard;

    /// JS source `(((…(x)…)))` — every level recurses through the guarded
    /// `parse_expr`/`parse_prefix` chain.
    fn deep_parens(depth: usize) -> Vec<u8> {
        let mut v = Vec::with_capacity(depth * 2 + 1);
        v.resize(depth, b'(');
        v.push(b'x');
        v.resize(depth * 2 + 1, b')');
        v
    }

    struct ParseOutcome {
        /// `log.errors == 0` and `parse` returned `Ok` — no diagnostics at all.
        clean: bool,
        /// The parser's orderly recursion-guard error was logged.
        overflow_reported: bool,
    }

    fn parse_js(contents: Vec<u8>) -> ParseOutcome {
        bun_ast::initialize_store();
        let _store_scope = StoreResetGuard::new();
        let source = bun_ast::Source::init_path_string_owned("deep.js", contents);
        let mut log = bun_ast::Log::init();
        let arena = Arena::new();
        let define = Define::default();
        let options = ParserOptions::init(
            crate::parser::options::JSX::Pragma::default(),
            crate::parser::options::Loader::Js,
        );
        let parsed = Parser::init(options, &mut log, &source, &define, &arena)
            .and_then(Parser::parse);
        let overflow_reported = log
            .msgs
            .iter()
            .any(|m| m.data.text.as_ref() == b"Maximum call stack size exceeded");
        ParseOutcome {
            clean: parsed.is_ok() && log.errors == 0,
            overflow_reported,
        }
    }

    fn parse_on_thread(stack: usize, contents: Vec<u8>) -> ParseOutcome {
        std::thread::Builder::new()
            .stack_size(stack)
            .spawn(move || {
                // `StackCheck::init()` reads the thread's real stack bounds via
                // `pthread_getattr_np`; `configure_thread()` mirrors the
                // runtime's per-thread setup (see `install/lib.rs` harness).
                bun_core::StackCheck::configure_thread();
                parse_js(contents)
            })
            .expect("spawn")
            .join()
            .expect("join")
    }

    #[test]
    fn deep_but_legal_nesting_parses_clean_with_headroom() {
        // ~1000 levels on a 64 MiB stack is far inside the boundary the
        // calibration test below measures; the guard must stay quiet.
        let out = parse_on_thread(64 * 1024 * 1024, deep_parens(1_000));
        assert!(out.clean, "depth-1000 parens must parse without diagnostics");
        assert!(!out.overflow_reported);
    }

    #[test]
    fn pathological_depth_reports_orderly_stack_overflow() {
        // 1M levels exhaust any thread stack long before the input ends. The
        // guard must surface its orderly error — a segfault here means a
        // recursion path skipped its `is_safe_to_recurse` check.
        let out = parse_on_thread(8 * 1024 * 1024, deep_parens(1_000_000));
        assert!(
            out.overflow_reported,
            "1M-deep parens must report `Maximum call stack size exceeded`"
        );
    }

    /// Smallest depth (found by doubling + bisection) whose parse reports the
    /// orderly overflow error on a thread with `stack` bytes.
    fn calibration_boundary(stack: usize) -> usize {
        let fails = |depth: usize| {
            parse_on_thread(stack, deep_parens(depth)).overflow_reported
        };
        // The deep-but-legal probe must hold: at tiny depths the guard is
        // silent, so doubling from 8 terminates at a real boundary.
        let mut lo = 8usize;
        assert!(!fails(lo), "depth {lo} must not trip the guard on {stack}-byte stack");
        let mut hi = lo * 2;
        while fails(hi) == false {
            lo = hi;
            hi = hi.saturating_mul(2);
            assert!(hi < 1_000_000, "no boundary found — guard never fires?");
        }
        while hi - lo > 1 {
            let mid = lo + (hi - lo) / 2;
            if fails(mid) {
                hi = mid;
            } else {
                lo = mid;
            }
        }
        hi
    }

    #[test]
    fn guard_boundary_scales_linearly_with_stack_size() {
        // The guard is stack-bound (frame_address vs thread end), NOT a fixed
        // depth cap: quadrupling the stack must roughly quadruple the depth at
        // which orderly errors begin. Ratio bounds [3.0, 5.0] absorb frame-size
        // jitter between probes.
        let small = calibration_boundary(2 * 1024 * 1024);
        let large = calibration_boundary(8 * 1024 * 1024);
        // Calibration record (visible with --nocapture): the depth at which
        // the guard begins reporting orderly stack-overflow errors, per stack.
        eprintln!(
            "StackCheck calibration: orderly-error boundary = {small} levels (2 MiB), {large} levels (8 MiB)"
        );
        assert!(small > 0, "boundary on 2 MiB must exist");
        assert!(large > small, "8 MiB boundary ({large}) must exceed 2 MiB boundary ({small})");
        let ratio = large as f64 / small as f64;
        assert!(
            (3.0..=5.0).contains(&ratio),
            "boundary ratio {small} → {large} = {ratio} must be ~4x for a 4x stack"
        );
    }

    #[test]
    fn is_safe_to_recurse_trips_with_platform_headroom_remaining() {
        // Direct linkage to the `is_safe_to_recurse` threshold: recurse on a
        // thread of known size, tracking stack consumption per level (address
        // of a local as an SP proxy — tests run without ASAN fake stacks).
        // The guard must trip while roughly the 128 KiB headroom (linux; the
        // threshold inside `bun_core::StackCheck::is_safe_to_recurse`) is
        // still unused — i.e. consumed stays just under the thread size, and
        // well over half of it (proving the comparison is against the stack
        // END, not the origin — the inverted-check regression from BCE #15).
        const STACK: usize = 4 * 1024 * 1024;
        #[derive(Debug)]
        struct Trip {
            consumed_from_top: usize,
        }
        fn recurse(check: &mut bun_core::StackCheck, top: usize, levels: &mut usize) -> Trip {
            let probe = &levels as *const _ as usize;
            check.update();
            if !check.is_safe_to_recurse() {
                return Trip {
                    consumed_from_top: top - probe,
                };
            }
            *levels += 1;
            recurse(check, top, levels)
        }
        let trip = std::thread::Builder::new()
            .stack_size(STACK)
            .spawn(move || {
                bun_core::StackCheck::configure_thread();
                let mut check = bun_core::StackCheck::init();
                let mut levels = 0usize;
                // First frame's local is ~the high-water mark for this walk.
                let top = &levels as *const _ as usize;
                let trip = recurse(&mut check, top, &mut levels);
                assert!(levels > 16, "guard tripped after only {levels} levels — spurious");
                trip
            })
            .expect("spawn")
            .join()
            .expect("join");
        assert!(
            trip.consumed_from_top < STACK,
            "guard must trip before the stack is exhausted"
        );
        assert!(
            trip.consumed_from_top > STACK / 2,
            "guard trip at {:?} bytes consumed is too early — check compares against the wrong bound",
            trip
        );
    }
}