bun_js_printer 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
use core::cmp::Ordering;
use core::mem::ManuallyDrop;
use std::io::Write as _;

use bun_alloc::Arena as Bump;

use bun_ast as js_ast;
use bun_ast::lexer_tables::{
    self as js_lexer, KEYWORDS as Keywords, STRICT_MODE_RESERVED_WORDS as StrictModeReservedWords,
};
use bun_ast::symbol;
use bun_ast::symbol::SlotNamespace;
use bun_ast::{Ref, Symbol};
use bun_collections::hive_array::Fallback as HiveArrayFallback;
use bun_collections::{HashMap, StringHashMap, VecExt};
use bun_core::Output;
use bun_core::{MutableString, immutable as strings};
use bun_options_types::Format;
use enum_map::EnumMap;

/// Renamed-name strings are either borrowed from `Symbol.original_name` (AST
/// arena) or duped into the renamer's `bumpalo::Bump` arena. `StoreStr` is the
/// arena-backed lifetime-erased slice wrapper that centralises the raw deref
/// (one `unsafe` in `StoreStr::slice`), so the renamer's name-table reads stay
/// safe. Phase B may later thread `'bump` and rewrite to `&'bump [u8]`.
type NameStr = bun_ast::StoreStr;

#[inline]
const fn name_str_empty() -> NameStr {
    bun_ast::StoreStr::EMPTY
}

/// Const array for `inline for (SlotNamespace.values)` translation. Skips
/// `MustNotBeRenamed` (Zig's `inline for` over the renameable namespaces).
const SLOT_NAMESPACES: [SlotNamespace; 4] = [
    SlotNamespace::Default,
    SlotNamespace::Label,
    SlotNamespace::PrivateName,
    SlotNamespace::MangledProp,
];

/// Lifetime-erased name slice used as the key in `NumberScope::name_counts`.
///
/// `NumberScope` lives in a `HiveArrayFallback` pool inside `NumberRenamer`,
/// alongside the renamer's `arena: Bump`. A `&'a [u8]` key would make
/// `NumberScope<'a>` self-referential to its own owner, so the renamer (like
/// the rest of the AST layer) carries name slices as the lifetime-erased
/// [`bun_ast::StoreStr`] and re-borrows on read. Every key inserted here points
/// either at `Symbol::original_name` (an AST-arena slice that strictly outlives
/// the renamer) or at bytes bump-allocated from the renamer's own `arena: Bump`,
/// which is only reset on `NumberRenamer::Drop` after every `NumberScope` is
/// returned to the pool — so the borrow contract documented on `StoreStr::slice`
/// is always satisfied.
///
/// Replaces the previous `StringHashMap<u32>` (whose `put_no_clobber` heap-boxed
/// a `Box<[u8]>` copy of the key) with a `Copy` 16-byte key that needs no
/// allocation on insert and no free on the per-scope drop in the renamer's
/// pool walkback. Same shape as Zig's `StringHashMapUnmanaged([]const u8, u32)`.
#[derive(Clone, Copy)]
pub struct NameKey(NameStr);

impl NameKey {
    #[inline]
    fn as_bytes(&self) -> &[u8] {
        self.0.slice()
    }
}

impl core::hash::Hash for NameKey {
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        // Must match `<[u8] as Hash>::hash` so `Borrow<[u8]>` lookups agree.
        self.as_bytes().hash(state);
    }
}

impl PartialEq for NameKey {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}
impl Eq for NameKey {}

impl core::borrow::Borrow<[u8]> for NameKey {
    #[inline]
    fn borrow(&self) -> &[u8] {
        self.as_bytes()
    }
}

/// Per-`NumberScope` map of assigned names → next collision counter.
/// `bun_wyhash::BuildHasher` matches `StringHashMap` so the renamer keeps its
/// existing hash quality; `NameKey` is a `Copy` lifetime-erased slice so insert
/// never heap-allocates a key copy and drop never frees one.
pub(crate) type NameCountMap =
    bun_collections::hashbrown::HashMap<NameKey, u32, bun_wyhash::BuildHasher>;

pub struct NoOpRenamer<'a> {
    // PORT NOTE: Zig `Symbol.Map` is a non-owning `BabyList(BabyList(Symbol))`
    // slice header passed by value (renamer.zig:2,126,452 — no `deinit` ever
    // frees it). In the Rust port `symbol::Map` is `Vec<Vec<Symbol>>` (owning).
    // Unlike `MinifyRenamer`/`NumberRenamer` (which the bundler builds over a
    // *borrowed* `LinkerGraph.symbols` and so wrap in `ManuallyDrop`),
    // `NoOpRenamer` is only constructed by `print_ast`/`print_common_js`, whose
    // callers always pass an *owned* Map freshly built by
    // `Map::init_with_one_list(mem::take(&mut ast.symbols))`. Owning + dropping
    // here is required: `ManuallyDrop` leaked the per-file `Vec<Symbol>` on
    // every transpile (require-cache.test.ts "files transpiled and loaded don't
    // leak the output source code" — `await import()` re-transpiles each
    // iteration, so the leak compounds to OOM).
    pub symbols: symbol::Map,
    pub source: &'a bun_ast::Source,
}

impl<'a> NoOpRenamer<'a> {
    pub(crate) fn init(symbols: symbol::Map, source: &'a bun_ast::Source) -> NoOpRenamer<'a> {
        NoOpRenamer { symbols, source }
    }

    #[inline]
    pub(crate) fn original_name(&self, ref_: Ref) -> &[u8] {
        self.name_for_symbol(ref_)
    }

    pub(crate) fn name_for_symbol(&self, ref_: Ref) -> &[u8] {
        if ref_.is_source_contents_slice() {
            return &self.source.contents[ref_.source_index() as usize
                ..(ref_.source_index() + ref_.inner_index()) as usize];
        }

        let resolved = self.symbols.follow(ref_);

        if let Some(symbol) = self.symbols.get_const(resolved) {
            // SAFETY: `original_name` is an AST-arena slice that outlives the renamer.
            symbol.original_name.slice()
        } else {
            // TODO(port): include `self.source.path.text` once `bun_paths::fs::Path<'static>`
            // exposes the text accessor.
            Output::panic(format_args!("Invalid symbol {}", ref_));
        }
    }

    pub(crate) fn to_renamer(&mut self) -> Renamer<'_, 'a> {
        Renamer::NoOpRenamer(self)
    }
}

// PORT NOTE: two lifetime params — `'r` is the borrow of the underlying renamer,
// `'src` is `NoOpRenamer`'s borrow of the `Source`. The Zig `Renamer` was a
// tag+ptr union that erased both; using `&'a mut NoOpRenamer<'a>` would make
// `'a` invariant and lock the source borrow to the renamer borrow.
pub enum Renamer<'r, 'src> {
    NumberRenamer(&'r mut NumberRenamer),
    NoOpRenamer(&'r mut NoOpRenamer<'src>),
    MinifyRenamer(&'r mut MinifyRenamer),
}

impl<'r, 'src> Renamer<'r, 'src> {
    pub fn symbols(&self) -> &symbol::Map {
        match self {
            Renamer::NumberRenamer(r) => &r.symbols,
            Renamer::NoOpRenamer(r) => &r.symbols,
            Renamer::MinifyRenamer(r) => &r.symbols,
        }
    }

    pub fn name_for_symbol(&mut self, ref_: Ref) -> &[u8] {
        match self {
            Renamer::NumberRenamer(r) => r.name_for_symbol(ref_),
            Renamer::NoOpRenamer(r) => r.name_for_symbol(ref_),
            Renamer::MinifyRenamer(r) => r.name_for_symbol(ref_),
        }
    }

    pub fn original_name(&self, ref_: Ref) -> Option<&[u8]> {
        match self {
            Renamer::NumberRenamer(r) => Some(r.original_name(ref_)),
            Renamer::NoOpRenamer(r) => Some(r.original_name(ref_)),
            Renamer::MinifyRenamer(r) => r.original_name(ref_),
        }
    }
}

// PORT NOTE: Zig `Renamer.deinit` freed NumberRenamer/MinifyRenamer internals.
// In Rust all three variants are `&'r mut` (caller-owned, Drop on caller's
// storage). No explicit deinit needed.

#[derive(Clone, Copy)]
pub struct SymbolSlot {
    // Most minified names are under 15 bytes
    // Instead of allocating a string for every symbol slot
    // We can store the string inline!
    // But we have to be very careful of where it's used.
    // Or we WILL run into memory bugs.
    pub name: TinyString,
    pub count: u32,
    pub needs_capital_for_jsx: bool,
}

impl Default for SymbolSlot {
    fn default() -> Self {
        SymbolSlot {
            name: TinyString::String(name_str_empty()),
            count: 0,
            needs_capital_for_jsx: false,
        }
    }
}

pub(crate) type SymbolSlotList = EnumMap<symbol::SlotNamespace, Vec<SymbolSlot>>;

#[derive(Clone, Copy, Default)]
pub struct InlineString {
    pub bytes: [u8; 15],
    pub len: u8,
}

impl InlineString {
    pub(crate) fn init(str_: &[u8]) -> InlineString {
        let mut this = InlineString {
            len: u8::try_from(str_.len().min(15)).expect("int cast"),
            ..Default::default()
        };
        for (b, c) in this.bytes[0..this.len as usize]
            .iter_mut()
            .zip(&str_[0..this.len as usize])
        {
            *b = *c;
        }
        this
    }

    // do not make this *const or you will run into memory bugs.
    // we cannot let the compiler decide to copy this struct because
    // that would cause this to become a pointer to stack memory.
    pub(crate) fn slice(&mut self) -> &[u8] {
        &self.bytes[0..self.len as usize]
    }
}

#[derive(Clone, Copy)]
pub enum TinyString {
    InlineString(InlineString),
    // Arena-owned slice when len > 15 (allocated from `MinifyRenamer.arena`).
    String(NameStr),
}

impl TinyString {
    pub(crate) fn init(input: &[u8], arena: &Bump) -> Result<TinyString, bun_alloc::AllocError> {
        if input.len() <= 15 {
            Ok(TinyString::InlineString(InlineString::init(input)))
        } else {
            // Zig: `allocator.dupe(u8, input)` — allocate into the renamer arena.
            let duped: &[u8] = arena.alloc_slice_copy(input);
            Ok(TinyString::String(bun_ast::StoreStr::new(duped)))
        }
    }

    // do not make this *const or you will run into memory bugs.
    // we cannot let the compiler decide to copy this struct because
    // that would cause this to become a pointer to stack memory.
    pub(crate) fn slice(&mut self) -> &[u8] {
        match self {
            TinyString::InlineString(s) => s.slice(),
            // `StoreStr::slice` centralises the arena-backed deref; the payload
            // outlives `self` (the arena lives on the owning renamer).
            TinyString::String(s) => s.slice(),
        }
    }
}

pub struct MinifyRenamer {
    pub reserved_names: StringHashMap<u32>,
    pub slots: SymbolSlotList,
    pub top_level_symbol_to_slot: TopLevelSymbolSlotMap,
    pub symbols: ManuallyDrop<symbol::Map>,
    pub owns_symbols: bool,
    /// Backs `TinyString::String` slot-name allocations (Zig: `this.allocator`).
    pub arena: Bump,
}

impl Drop for MinifyRenamer {
    fn drop(&mut self) {
        if self.owns_symbols {
            // SAFETY: `owns_symbols` is only set on the owned-Map path; dropped exactly once.
            unsafe { ManuallyDrop::drop(&mut self.symbols) };
        }
    }
}

// TODO(port): Zig used `std.HashMapUnmanaged(Ref, usize, RefCtx, 80)` —
// bun_collections::HashMap should be parameterized with RefCtx hasher.
pub(crate) type TopLevelSymbolSlotMap = HashMap<Ref, usize>;

impl MinifyRenamer {
    pub fn init(
        symbols: symbol::Map,
        first_top_level_slots: &js_ast::SlotCounts,
        reserved_names: StringHashMap<u32>,
    ) -> Result<Box<MinifyRenamer>, bun_alloc::AllocError> {
        let mut slots = SymbolSlotList::default();

        for (ns, &count) in first_top_level_slots.slots.iter() {
            let count = count as usize;
            let mut v = Vec::with_capacity(count);
            v.resize(count, SymbolSlot::default());
            slots[ns] = v;
        }

        Ok(Box::new(MinifyRenamer {
            symbols: ManuallyDrop::new(symbols),
            owns_symbols: false,
            reserved_names,
            slots,
            top_level_symbol_to_slot: TopLevelSymbolSlotMap::default(),
            arena: Bump::new(),
        }))
    }

    pub fn to_renamer(&mut self) -> Renamer<'_, 'static> {
        Renamer::MinifyRenamer(self)
    }

    pub fn name_for_symbol(&mut self, ref_: Ref) -> &[u8] {
        let ref_ = self.symbols.follow(ref_);
        let symbol: &Symbol = self.symbols.get_const(ref_).unwrap();

        let ns = symbol.slot_namespace();
        if ns == SlotNamespace::MustNotBeRenamed {
            // SAFETY: `original_name` is an AST-arena slice that outlives the renamer.
            return symbol.original_name.slice();
        }

        let i = match symbol
            .nested_scope_slot()
            .map(|s| s as usize)
            .or_else(|| self.top_level_symbol_to_slot.get(&ref_).copied())
        {
            Some(i) => i,
            // SAFETY: as above.
            None => return symbol.original_name.slice(),
        };

        // This has to be a pointer because the string might be stored inline
        self.slots[ns][i].name.slice()
    }

    pub fn original_name(&self, _ref: Ref) -> Option<&[u8]> {
        None
    }

    pub fn accumulate_symbol_use_counts(
        &mut self,
        top_level_symbols: &mut Vec<StableSymbolCount>,
        symbol_uses: &js_ast::part::SymbolUseMap,
        stable_source_indices: &[u32],
    ) -> Result<(), bun_alloc::AllocError> {
        // PORT NOTE: ArrayHashMap exposes parallel keys()/values() slices, no .iter().
        for (key, value) in symbol_uses.keys().iter().zip(symbol_uses.values().iter()) {
            self.accumulate_symbol_use_count(
                top_level_symbols,
                *key,
                value.count_estimate,
                stable_source_indices,
            )?;
        }
        Ok(())
    }

    pub fn accumulate_symbol_use_count(
        &mut self,
        top_level_symbols: &mut Vec<StableSymbolCount>,
        ref_: Ref,
        count: u32,
        stable_source_indices: &[u32],
    ) -> Result<(), bun_alloc::AllocError> {
        let mut ref_ = self.symbols.follow(ref_);
        let mut symbol: &Symbol = self.symbols.get_const(ref_).unwrap();

        while let Some(alias) = &symbol.namespace_alias {
            let new_ref = self.symbols.follow(alias.namespace_ref);
            if new_ref.eql(ref_) {
                break;
            }
            ref_ = new_ref;
            symbol = self.symbols.get_const(new_ref).unwrap();
        }

        let ns = symbol.slot_namespace();
        if ns == SlotNamespace::MustNotBeRenamed {
            return Ok(());
        }

        if let Some(i) = symbol.nested_scope_slot() {
            let slot = &mut self.slots[ns][i as usize];
            slot.count += count;
            if symbol.must_start_with_capital_letter_for_jsx {
                slot.needs_capital_for_jsx = true;
            }
            return Ok(());
        }

        top_level_symbols.push(StableSymbolCount {
            stable_source_index: stable_source_indices[ref_.source_index() as usize],
            ref_,
            count,
        });
        Ok(())
    }

    pub fn allocate_top_level_symbol_slots(
        &mut self,
        top_level_symbols: &[StableSymbolCount],
    ) -> Result<(), bun_alloc::AllocError> {
        for stable in top_level_symbols {
            let symbol: &Symbol = self.symbols.get_const(stable.ref_).unwrap();
            // PORT NOTE: reshaped for borrowck — capture symbol fields before mut-borrowing slots
            let ns = symbol.slot_namespace();
            let must_start_with_capital = symbol.must_start_with_capital_letter_for_jsx;
            let slots = &mut self.slots[ns];

            let gpe = self.top_level_symbol_to_slot.get_or_put(stable.ref_)?;
            if gpe.found_existing {
                let slot = &mut slots[*gpe.value_ptr];
                slot.count += stable.count;
                if must_start_with_capital {
                    slot.needs_capital_for_jsx = true;
                }
            } else {
                *gpe.value_ptr = slots.len();
                slots.push(SymbolSlot {
                    name: TinyString::String(name_str_empty()),
                    count: stable.count,
                    needs_capital_for_jsx: must_start_with_capital,
                });
            }
        }
        Ok(())
    }

    pub fn assign_names_by_frequency(
        &mut self,
        name_minifier: &js_ast::NameMinifier,
    ) -> Result<(), bun_core::Error> {
        let mut name_buf: Vec<u8> = Vec::with_capacity(64);

        let mut sorted: Vec<SlotAndCount> = Vec::new();

        // PERF(port): was `inline for` over enum values — profile
        for &ns in SLOT_NAMESPACES.iter() {
            let slots = &mut self.slots[ns];
            sorted.clear();
            sorted.extend(slots.iter().enumerate().map(|(i, slot)| SlotAndCount {
                slot: u32::try_from(i).expect("int cast"),
                count: slot.count,
            }));
            sorted.sort_unstable_by(|a, b| SlotAndCount::less_than(*a, *b));

            let mut next_name: isize = 0;

            for data in sorted.iter() {
                name_minifier.number_to_minified_name(&mut name_buf, next_name)?;
                next_name += 1;

                // Make sure we never generate a reserved name. We only have to worry
                // about collisions with reserved identifiers for normal symbols, and we
                // only have to worry about collisions with keywords for labels. We do
                // not have to worry about either for private names because they start
                // with a "#" character.
                match ns {
                    symbol::SlotNamespace::Default => {
                        while self.reserved_names.contains_key(name_buf.as_slice()) {
                            name_minifier.number_to_minified_name(&mut name_buf, next_name)?;
                            next_name += 1;
                        }

                        if slots[data.slot as usize].needs_capital_for_jsx {
                            while name_buf[0] >= b'a' && name_buf[0] <= b'z' {
                                name_minifier.number_to_minified_name(&mut name_buf, next_name)?;
                                next_name += 1;
                            }
                        }
                    }
                    symbol::SlotNamespace::Label => {
                        while js_lexer::keyword(name_buf.as_slice()).is_some() {
                            name_minifier.number_to_minified_name(&mut name_buf, next_name)?;
                            next_name += 1;
                        }
                    }
                    symbol::SlotNamespace::PrivateName => {
                        name_buf.insert(0, b'#');
                    }
                    _ => {}
                }

                slots[data.slot as usize].name =
                    TinyString::init(name_buf.as_slice(), &self.arena).expect("unreachable");
            }
        }
        Ok(())
    }
}

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

pub(crate) type StableSymbolCountArray = Vec<StableSymbolCount>;

impl StableSymbolCount {
    pub fn less_than(i: &StableSymbolCount, j: &StableSymbolCount) -> Ordering {
        if i.count > j.count {
            return Ordering::Less;
        }
        if i.count < j.count {
            return Ordering::Greater;
        }
        if i.stable_source_index < j.stable_source_index {
            return Ordering::Less;
        }
        if i.stable_source_index > j.stable_source_index {
            return Ordering::Greater;
        }

        i.ref_.inner_index().cmp(&j.ref_.inner_index())
    }
}

// PORT NOTE: Zig `packed struct(u64)`. Packed layout is not load-bearing here
// (never bitcast/FFI — only sorted in a local Vec), so two named u32 fields
// instead of a #[repr(transparent)] u64 with shift accessors.
#[repr(C)]
#[derive(Clone, Copy)]
struct SlotAndCount {
    slot: u32,
    count: u32,
}

impl SlotAndCount {
    fn less_than(a: SlotAndCount, b: SlotAndCount) -> Ordering {
        // Sort by descending count, then ascending slot.
        b.count.cmp(&a.count).then_with(|| a.slot.cmp(&b.slot))
    }
}

pub struct NumberRenamer {
    // PORT NOTE: see `NoOpRenamer.symbols` — non-owning view; Zig
    // `NumberRenamer.deinit` (renamer.zig:462) never frees `symbols`.
    pub symbols: ManuallyDrop<symbol::Map>,
    pub names: Box<[Vec<NameStr>]>,
    // PERF(port): Zig had separate allocator/temp_allocator; global mimalloc now
    pub number_scope_pool: HiveArrayFallback<NumberScope, 128>,
    // PERF(port): was arena bulk-free for NumberScope pool + name temp buffers
    pub root: NumberScope,
    /// Backs renamed-name slices written into `names` (Zig: `r.allocator`).
    pub arena: Bump,
    // PERF(port): was StackFallbackAllocator(512) — profile
}

impl NumberRenamer {
    pub fn to_renamer(&mut self) -> Renamer<'_, 'static> {
        Renamer::NumberRenamer(self)
    }

    pub fn original_name(&self, ref_: Ref) -> &[u8] {
        if ref_.is_source_contents_slice() {
            unreachable!();
        }

        let resolved = self.symbols.follow(ref_);
        // SAFETY: `original_name` is an AST-arena slice that outlives the renamer.
        self.symbols
            .get_const(resolved)
            .unwrap()
            .original_name
            .slice()
    }

    pub fn assign_name(&mut self, scope: &mut NumberScope, input_ref: Ref) {
        let ref_ = self.symbols.follow(input_ref);

        // Don't rename the same symbol more than once
        let inner: &mut Vec<NameStr> = &mut self.names[ref_.source_index() as usize];
        if inner.len() > ref_.inner_index() as usize && inner[ref_.inner_index() as usize].len() > 0
        {
            return;
        }

        // Don't rename unbound symbols, symbols marked as reserved names, labels, or private names
        let symbol: &Symbol = self.symbols.get_const(ref_).unwrap();
        if symbol.slot_namespace() != SlotNamespace::Default {
            return;
        }

        // SAFETY: `original_name` is an AST-arena slice that outlives the renamer.
        let original_name: &[u8] = symbol.original_name.slice();
        // PERF(port): Zig reset stack-fallback FBA here; arena reset semantics differ
        let name: NameStr = match scope.find_unused_name(&self.arena, original_name) {
            UnusedName::Renamed(name) => name,
            UnusedName::NoCollision => symbol.original_name,
        };
        let new_len = inner.len().max(ref_.inner_index() as usize + 1);
        if inner.len() < new_len {
            inner.resize(new_len, name_str_empty());
        }
        inner[ref_.inner_index() as usize] = name;
    }

    pub fn init(
        symbols: symbol::Map,
        root_names: &StringHashMap<u32>,
    ) -> Result<Box<NumberRenamer>, bun_alloc::AllocError> {
        let len = symbols.symbols_for_source.len();
        let names: Box<[Vec<NameStr>]> = core::iter::repeat_with(Vec::<NameStr>::default)
            .take(len)
            .collect();

        // PERF(port): HiveArray.Fallback was bound to arena.arena() in Zig
        let number_scope_pool = HiveArrayFallback::<NumberScope, 128>::init();

        // The arena is created here (before `root.name_counts`) so the
        // reserved-name keys can be duped into it: `root_names` owns its keys
        // as `Box<[u8]>` and is dropped at the end of this function, while
        // `NameKey` is a lifetime-erased borrow that must outlive `root`.
        // The set is bounded by the unique unbound/must-not-be-renamed globals
        // across the chunk (typically a few hundred names), and this copy
        // happens once per chunk vs. the millions of per-symbol ops below.
        let arena = Bump::new();
        let mut root = NumberScope::default();
        root.name_counts.reserve(root_names.len());
        for (key, &value) in root_names.iter() {
            let duped = arena.alloc_slice_copy(&**key);
            root.name_counts.insert(NameKey(NameStr::new(duped)), value);
        }

        // TODO(b2-blocked): bun_core::env_var::BUN_DUMP_SYMBOLS — typed accessor
        // not yet declared upstream; debug-only `symbols.dump()` call elided.

        // PORT NOTE: Zig @memset(sliceAsBytes(names), 0) — Vec::default() is already zeroed.

        Ok(Box::new(NumberRenamer {
            symbols: ManuallyDrop::new(symbols),
            names,
            number_scope_pool,
            root,
            arena,
        }))
    }

    pub fn assign_names_recursive(
        &mut self,
        scope: &js_ast::Scope,
        source_index: u32,
        parent: Option<bun_ptr::ParentRef<NumberScope>>,
        sorted: &mut Vec<u32>,
    ) {
        let s: *mut NumberScope = self
            .number_scope_pool
            .get_init(NumberScope {
                parent,
                name_counts: NameCountMap::default(),
            })
            .as_ptr();

        self.assign_names_recursive_with_number_scope(s, scope, source_index, sorted);

        // PORT NOTE: Zig `defer { s.deinit(); pool.put(s) }` — fn is infallible,
        // so no scopeguard needed; cleanup runs unconditionally below.
        // SAFETY: s came from number_scope_pool.get() and was initialized above;
        // `put` drops `name_counts` in place before recycling the slot.
        unsafe { self.number_scope_pool.put(s) };
    }

    fn assign_names_in_scope(
        &mut self,
        s: &mut NumberScope,
        scope: &js_ast::Scope,
        source_index: u32,
        sorted: &mut Vec<u32>,
    ) {
        {
            sorted.clear();
            sorted.extend(scope.members.values().map(|value_ref| {
                debug_assert!(!value_ref.ref_.is_source_contents_slice());
                value_ref.ref_.inner_index()
            }));
            debug_assert_eq!(sorted.len(), scope.members.count());
            sorted.sort_unstable();

            for &inner_index in sorted.iter() {
                self.assign_name(s, Ref::init(inner_index, source_index, false));
            }
        }

        for ref_ in scope.generated.slice() {
            self.assign_name(s, *ref_);
        }
    }

    pub fn assign_names_recursive_with_number_scope(
        &mut self,
        initial_scope: *mut NumberScope,
        scope_: &js_ast::Scope,
        source_index: u32,
        sorted: &mut Vec<u32>,
    ) {
        let mut s: *mut NumberScope = initial_scope;
        let mut scope = scope_;
        // TODO(port): defer cleanup of `s` if s != initial_scope — handled at end

        loop {
            let symbol_count = scope.members.count() + scope.generated.len_u32() as usize;
            if symbol_count > 0 {
                let new_child_scope: *mut NumberScope = self
                    .number_scope_pool
                    .get_init(NumberScope {
                        // `s` is non-null (either `initial_scope` or a fresh
                        // pool slot from a prior iteration); the new child
                        // outlives this `ParentRef` only until `put()` below.
                        parent: Some(bun_ptr::ParentRef::from(
                            core::ptr::NonNull::new(s).expect("number_scope non-null"),
                        )),
                        // Pre-size to the AST scope's symbol count so the
                        // per-name insert path doesn't realloc the table
                        // 0→4→8→… as names are assigned. Most scopes assign
                        // every member exactly once, so this is the exact
                        // final size; symbols skipped by `assign_name`
                        // (already renamed, non-default namespace) just leave
                        // a little slack.
                        name_counts: NameCountMap::with_capacity_and_hasher(
                            symbol_count,
                            Default::default(),
                        ),
                    })
                    .as_ptr();
                s = new_child_scope;

                // SAFETY: s is a valid pool slot just initialized above
                self.assign_names_in_scope(unsafe { &mut *s }, scope, source_index, sorted);
            }

            if scope.children.len_u32() == 1 {
                // `StoreRef<Scope>: Deref<Target = Scope>` — safe arena-backed deref.
                scope = scope.children.at(0).get();
            } else {
                break;
            }
        }

        // Symbols in child scopes may also have to be renamed to avoid conflicts
        for child in scope.children.slice() {
            // `StoreRef<Scope>: Deref<Target = Scope>` — safe arena-backed deref.
            self.assign_names_recursive_with_number_scope(s, child, source_index, sorted);
        }

        // PORT NOTE: Zig (renamer.zig:594-598) only put the final `s` because
        // both the pool fallback (`.init(renamer.arena.allocator())`) and
        // `name_counts` data lived in arenas bulk-freed by `NumberRenamer.deinit
        // -> arena.deinit()`. The Rust port moved both to the global heap
        // (HiveArrayFallback::init() uses Box, StringHashMap uses global alloc),
        // so we must walk the parent chain and `put` every intermediate scope
        // we allocated in the loop above — not just the deepest one.
        while s != initial_scope {
            // SAFETY: `s` is a pool slot we allocated and initialized in the
            // loop above; every such slot has `parent: Some(...)`. Read parent
            // before `put` (which drops/frees the slot).
            let parent = unsafe { (*s).parent }
                .map(|p| p.as_mut_ptr())
                .unwrap_or(initial_scope);
            // SAFETY: `s` came from `number_scope_pool.get()` in the loop above
            // and was fully initialized; `put` drops `name_counts` in place
            // before recycling/freeing the slot.
            unsafe { self.number_scope_pool.put(s) };
            s = parent;
        }
    }

    pub fn add_top_level_symbol(&mut self, ref_: Ref) {
        // PORT NOTE: reshaped for borrowck — root is a field of self
        // TODO(port): self.assign_name needs &mut self AND &mut self.root simultaneously
        let root: *mut NumberScope = &raw mut self.root;
        // SAFETY: assign_name does not touch self.root through `self`
        self.assign_name(unsafe { &mut *root }, ref_);
    }

    pub fn add_top_level_declared_symbols(
        &mut self,
        declared_symbols: &mut js_ast::DeclaredSymbolList,
    ) {
        js_ast::DeclaredSymbol::for_each_top_level_symbol(declared_symbols, self, |r, ref_| {
            r.add_top_level_symbol(ref_)
        });
    }

    pub fn name_for_symbol(&self, ref_: Ref) -> &[u8] {
        if ref_.is_source_contents_slice() {
            unreachable!("Unexpected unbound symbol!\n{}", ref_);
        }

        let resolved = self.symbols.follow(ref_);

        let source_index = resolved.source_index();
        let inner_index = resolved.inner_index();

        let renamed_list = &self.names[source_index as usize];

        if renamed_list.len() > inner_index as usize {
            let renamed: NameStr = renamed_list[inner_index as usize];
            if renamed.raw_len() > 0 {
                // `StoreStr::slice` centralises the deref; allocated from
                // `self.arena` or borrows an AST-arena `original_name`, both
                // of which outlive `self`.
                return renamed.slice();
            }
        }

        // SAFETY: `original_name` is an AST-arena slice that outlives the renamer.
        self.symbols.symbols_for_source[source_index as usize][inner_index as usize]
            .original_name
            .slice()
    }
}

#[derive(Default)]
pub struct NumberScope {
    /// Backreference to the enclosing `NumberScope`. The parent is either
    /// `NumberRenamer::root` or a pool slot allocated earlier in the same
    /// `assign_names_recursive_with_number_scope` call, both of which strictly
    /// outlive this child (children are `put()` back before their parent), so
    /// `ParentRef::get()` is sound without per-site `unsafe`.
    pub parent: Option<bun_ptr::ParentRef<NumberScope>>,
    pub name_counts: NameCountMap,
}

pub(crate) enum NameUse {
    Unused,
    SameScope(u32),
    Used,
}

impl NameUse {
    pub(crate) fn find(this: &NumberScope, name: &[u8]) -> NameUse {
        // This version doesn't allocate
        #[cfg(debug_assertions)]
        debug_assert!(js_lexer::is_identifier(name));

        // Hash `name` once and probe each scope in the parent chain with the
        // same precomputed hash via hashbrown's raw-entry API; the previous
        // `get_adapted`/`contains_adapted` calls re-hashed `name` per scope.
        let hash = {
            use core::hash::BuildHasher;

            <bun_wyhash::BuildHasher as Default>::default().hash_one(name)
        };

        if let Some((_, &count)) = this
            .name_counts
            .raw_entry()
            .from_hash(hash, |k| k.as_bytes() == name)
        {
            return NameUse::SameScope(count);
        }

        let mut s: Option<bun_ptr::ParentRef<NumberScope>> = this.parent;

        while let Some(scope) = s {
            // `ParentRef<NumberScope>: Deref` — safe backref deref under the
            // parent-outlives-child invariant documented on the field.
            if scope
                .name_counts
                .raw_entry()
                .from_hash(hash, |k| k.as_bytes() == name)
                .is_some()
            {
                return NameUse::Used;
            }
            s = scope.parent;
        }

        NameUse::Unused
    }
}

pub enum UnusedName {
    NoCollision,
    Renamed(NameStr),
}

/// Fast-path for `MutableString::ensure_valid_identifier`: returns `true` iff
/// `s` is a non-empty ASCII identifier (`[A-Za-z_$][A-Za-z0-9_$]*`). This is
/// the exact condition under which Zig's `ensureValidIdentifier` returns the
/// input slice unchanged (modulo the strict-mode-reserved-word remap, handled
/// by the caller). The Rust port of that function currently always allocates
/// a `Box<[u8]>` even on the borrow path — see its `TODO(port)` — so hoisting
/// this check into the renamer restores Zig's zero-alloc behaviour for the
/// overwhelmingly common case (`symbol.original_name` is parser-produced and
/// almost always satisfies this).
#[inline]
fn is_simple_ascii_identifier(s: &[u8]) -> bool {
    let Some((&first, rest)) = s.split_first() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || first == b'_' || first == b'$') {
        return false;
    }
    for &c in rest {
        if !(c.is_ascii_alphanumeric() || c == b'_' || c == b'$') {
            return false;
        }
    }
    true
}

impl NumberScope {
    /// Caller must use an arena allocator
    pub fn find_unused_name(&mut self, arena: &Bump, input_name: &[u8]) -> UnusedName {
        // PORT NOTE: Zig's `MutableString.ensureValidIdentifier` borrows the
        // input when it is already a valid ASCII identifier; the Rust port
        // always heap-allocates (Box<[u8]>). Skip the call entirely for the
        // common case so this stays alloc-free, matching the .zig fast path.
        // The strict-mode-reserved-word remap (`let` → `_let`, etc.) is the
        // only transform that fires for an otherwise-valid ASCII name, so
        // gate on that too and fall through to the full normalizer when it
        // would apply.
        let owned_name;
        let normalized;
        let mut name: &[u8] = if is_simple_ascii_identifier(input_name)
            && !bun_ast::lexer_tables::is_strict_mode_reserved_word(input_name)
        {
            normalized = false;
            input_name
        } else {
            normalized = true;
            owned_name = MutableString::ensure_valid_identifier(input_name).expect("unreachable");
            &owned_name
        };
        // PORT NOTE: hoisted from inside the match arm so `name` (which may borrow
        // it) stays valid through the trailing dupe.
        let mut mutable_name = MutableString::init_empty();
        // True iff a "name2"/"name3" suffix was appended below (i.e. `name` was
        // reassigned to `mutable_name.slice()`). On the hot ASCII path
        // `!collided && !normalized` implies `name == input_name` so the tail
        // check skips the byte compare; the rare `normalized` path still
        // compares (see the comment at the tail).
        let mut collided = false;

        match NameUse::find(self, name) {
            NameUse::Unused => {}
            use_ => {
                collided = true;
                let mut tries: u32 = if matches!(use_, NameUse::Used) {
                    1
                } else {
                    // To avoid O(n^2) behavior, the number must start off being the number
                    // that we used last time there was a collision with this name. Otherwise
                    // if there are many collisions with the same name, each name collision
                    // would have to increment the counter past all previous name collisions
                    // which is a O(n^2) time algorithm. Only do this if this symbol comes
                    // from the same scope as the previous one since sibling scopes can reuse
                    // the same name without problems.
                    match use_ {
                        NameUse::SameScope(n) => n,
                        _ => unreachable!(),
                    }
                };

                let prefix = name;

                tries += 1;

                mutable_name
                    .grow_if_needed(prefix.len() + 4)
                    .expect("unreachable");
                mutable_name.append_slice(prefix).expect("unreachable");
                mutable_name.append_int(tries as u64).expect("unreachable");

                match NameUse::find(self, mutable_name.slice()) {
                    NameUse::Unused => {
                        if matches!(use_, NameUse::SameScope(_)) {
                            // `prefix` may borrow the local `owned_name`; if a
                            // new entry is needed, dupe into the renamer arena
                            // so the `NameKey` outlives this function. Mirrors
                            // Zig's conditional `allocator.dupe(u8, prefix)`.
                            *self.entry_or_arena_dup(prefix, arena) = tries;
                        }
                        name = mutable_name.slice();
                    }
                    cur_use => loop {
                        mutable_name.reset_to(prefix.len());
                        mutable_name.append_int(tries as u64).expect("unreachable");

                        tries += 1;

                        match NameUse::find(self, mutable_name.slice()) {
                            NameUse::Unused => {
                                if matches!(cur_use, NameUse::SameScope(_)) {
                                    *self.entry_or_arena_dup(prefix, arena) = tries;
                                }

                                name = mutable_name.slice();
                                break;
                            }
                            _ => {}
                        }
                    },
                }
            }
        }

        // Each name starts off with a count of 1 so that the first collision with
        // "name" is called "name2".
        //
        // `name` may still equal `input_name` bytewise even when `normalized`
        // is true: `ensure_valid_identifier` returns the input bytes unchanged
        // for an identifier whose first codepoint is a non-ASCII ID_Start
        // (e.g. `é`, `π`), since only `is_simple_ascii_identifier` is
        // ASCII-restricted. The hot ASCII path skips the byte compare via
        // `!normalized`; the rare non-ASCII path falls back to it.
        if !collided && (!normalized || strings::eql_long(name, input_name, true)) {
            // `input_name` is `Symbol::original_name.slice()` — an AST-arena
            // slice that outlives the renamer (see [`NameKey`] doc). No copy.
            let prev = self
                .name_counts
                .insert(NameKey(NameStr::new(input_name)), 1);
            debug_assert!(prev.is_none(), "put_no_clobber: key already present");
            return UnusedName::NoCollision;
        }

        // Zig: `allocator.dupe(u8, name)` — allocate into the renamer arena.
        let duped: &[u8] = arena.alloc_slice_copy(name);
        let name: NameStr = bun_ast::StoreStr::new(duped);

        // `duped` is bump-allocated from the renamer's `arena: Bump`, which
        // outlives every `NumberScope` (see [`NameKey`] doc). No copy.
        let prev = self.name_counts.insert(NameKey(name), 1);
        debug_assert!(prev.is_none(), "put_no_clobber: key already present");
        UnusedName::Renamed(name)
    }

    /// `name_counts.entry(prefix).or_insert(0)` with a vacant-only arena dup:
    /// when the key is already present we mutate it in place; when it is not,
    /// the bytes are bump-allocated into `arena` so the resulting [`NameKey`]
    /// outlives the renamer. Mirrors Zig's `getOrPut` + conditional
    /// `allocator.dupe(u8, prefix)` shape.
    fn entry_or_arena_dup(&mut self, prefix: &[u8], arena: &Bump) -> &mut u32 {
        use bun_collections::hashbrown::hash_map::RawEntryMut;
        match self.name_counts.raw_entry_mut().from_key(prefix) {
            RawEntryMut::Occupied(o) => o.into_mut(),
            RawEntryMut::Vacant(v) => {
                let duped = arena.alloc_slice_copy(prefix);
                v.insert(NameKey(NameStr::new(duped)), 0).1
            }
        }
    }
}

pub struct ExportRenamer {
    pub string_buffer: MutableString,
    pub used: StringHashMap<u32>,
    pub count: isize,
    /// Backs renamed export-name slices returned to the caller (Zig: caller's allocator).
    pub arena: Bump,
}

impl ExportRenamer {
    pub fn init() -> ExportRenamer {
        ExportRenamer {
            string_buffer: MutableString::init_empty(),
            used: StringHashMap::default(),
            count: 0,
            arena: Bump::new(),
        }
    }

    pub fn clear_retaining_capacity(&mut self) {
        self.used.clear();
        self.string_buffer.reset();
        // Per-chunk in `computeCrossChunkDependencies`. The method *name* is
        // already `clear_retaining_capacity`; honour that for the arena too.
        self.arena.reset_retain_with_limit(8 * 1024 * 1024);
    }

    pub fn next_renamed_name(&mut self, input: &[u8]) -> &[u8] {
        let entry = self.used.get_or_put(input).expect("unreachable");
        let mut tries: u32 = 1;
        if entry.found_existing {
            loop {
                self.string_buffer.reset();
                write!(
                    self.string_buffer.writer(),
                    "{}{}",
                    bstr::BStr::new(input),
                    tries
                )
                .expect("unreachable");
                tries += 1;
                let attempt: &[u8] = self.string_buffer.slice();
                // PORT NOTE: reshaped for borrowck — `get_or_put` borrows `self.used`
                // mutably, so allocate the arena copy first.
                let to_use: &[u8] = self.arena.alloc_slice_copy(attempt);
                let entry = self.used.get_or_put(to_use).expect("unreachable");
                if !entry.found_existing {
                    // PORT NOTE: `StringHashMap` owns a boxed copy of the key on
                    // insert; the Zig key-ptr write is unnecessary.
                    *entry.value_ptr = tries;

                    let entry = self.used.get_or_put(input).expect("unreachable");
                    *entry.value_ptr = tries;
                    // `to_use` borrows `self.arena` (disjoint from `self.used`
                    // above); returnable directly under split-borrow rules.
                    return to_use;
                }
            }
        } else {
            *entry.value_ptr = tries;
        }

        // PORT NOTE: Zig returned `entry.key_ptr.*` (the map's owned copy of `input`).
        // `StringHashMap` does not expose a key pointer; allocate a copy in `self.arena`
        // so the returned slice is tied to `&self` (sub-borrow of `&mut self`).
        self.arena.alloc_slice_copy(input)
    }

    pub fn next_minified_name(&mut self) -> Result<Vec<u8>, bun_core::Error> {
        // TODO(port): narrow error set
        let name = js_ast::NameMinifier::default_number_to_minified_name(self.count)?;
        self.count += 1;
        Ok(name)
    }
}

pub fn compute_initial_reserved_names(
    output_format: Format,
) -> Result<StringHashMap<u32>, bun_alloc::AllocError> {
    #[cfg(target_arch = "wasm32")]
    {
        unreachable!();
    }

    let mut names = StringHashMap::<u32>::default();

    const EXTRAS: [&[u8]; 2] = [b"Promise", b"Require"];

    const CJS_NAMES: [&[u8]; 2] = [b"exports", b"module"];

    let cjs_names_len: u32 = if output_format == Format::Cjs {
        CJS_NAMES.len() as u32
    } else {
        0
    };

    names.ensure_total_capacity(
        cjs_names_len as usize
            + (Keywords.len() + StrictModeReservedWords.len() + 1 + EXTRAS.len()),
    )?;

    for keyword in Keywords.keys() {
        // PERF(port): was assume_capacity
        names.put_assume_capacity(keyword, 1);
    }

    for keyword in StrictModeReservedWords.iter() {
        // PERF(port): was assume_capacity
        names.put_assume_capacity(keyword, 1);
    }

    // Node contains code that scans CommonJS modules in an attempt to statically
    // detect the set of export names that a module will use. However, it doesn't
    // do any scope analysis so it can be fooled by local variables with the same
    // name as the CommonJS module-scope variables "exports" and "module". Avoid
    // using these names in this case even if there is not a risk of a name
    // collision because there is still a risk of node incorrectly detecting
    // something in a nested scope as an top-level export.
    if output_format == Format::Cjs {
        for name in CJS_NAMES {
            // PERF(port): was assume_capacity
            names.put_assume_capacity(name, 1);
        }
    }

    for extra in EXTRAS {
        // PERF(port): was assume_capacity
        names.put_assume_capacity(extra, 1);
    }

    Ok(names)
}

pub fn compute_reserved_names_for_scope(
    scope: &js_ast::Scope,
    symbols: &symbol::Map,
    names: &mut StringHashMap<u32>,
) {
    // PORT NOTE: Zig copied `names_.*` to a local and wrote back via defer.
    // In Rust we mutate through &mut directly.

    for member in scope.members.values() {
        let symbol: &Symbol = symbols.get_const(member.ref_).unwrap();
        if symbol.kind == symbol::Kind::Unbound || symbol.must_not_be_renamed {
            // SAFETY: `original_name` is an AST-arena slice.
            names
                .put(symbol.original_name.slice(), 1)
                .expect("unreachable");
        }
    }

    for ref_ in scope.generated.slice() {
        let symbol: &Symbol = symbols.get_const(*ref_).unwrap();
        if symbol.kind == symbol::Kind::Unbound || symbol.must_not_be_renamed {
            // SAFETY: `original_name` is an AST-arena slice.
            names
                .put(symbol.original_name.slice(), 1)
                .expect("unreachable");
        }
    }

    // If there's a direct "eval" somewhere inside the current scope, continue
    // traversing down the scope tree until we find it to get all reserved names
    if scope.contains_direct_eval {
        for child in scope.children.slice() {
            // `StoreRef<Scope>: Deref<Target = Scope>` — safe arena-backed deref.
            if child.contains_direct_eval {
                compute_reserved_names_for_scope(child, symbols, names);
            }
        }
    }
}

// ported from: src/js_printer/renamer.zig