oxc_mangler 0.127.0

A collection of JavaScript tools written in Rust.
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
use std::iter::{self, repeat_with};

use itertools::Itertools;
use keep_names::collect_name_symbols;
use oxc_index::IndexVec;
use oxc_syntax::class::ClassId;
use rustc_hash::{FxHashMap, FxHashSet};

use base54::base54;
use oxc_allocator::{Allocator, BitSet, HashSet, Vec};
use oxc_ast::ast::{Declaration, Program, Statement};
use oxc_data_structures::inline_string::InlineString;
use oxc_semantic::{AstNodes, Reference, Scoping, Semantic, SemanticBuilder, SymbolId};
use oxc_span::SourceType;
use oxc_str::{CompactStr, Ident, Str};

pub(crate) mod base54;
mod keep_names;

pub use keep_names::MangleOptionsKeepNames;

#[derive(Default, Debug, Clone, Copy)]
pub struct MangleOptions {
    /// Pass true to mangle names declared in the top level scope.
    ///
    /// Default: `true` for [`ModuleKind::Module`] and [`ModuleKind::CommonJS`]. Otherwise `false`.
    ///
    /// [`ModuleKind::Module`]: oxc_span::ModuleKind::Module
    /// [`ModuleKind::CommonJS`]: oxc_span::ModuleKind::CommonJS
    pub top_level: Option<bool>,

    /// Keep function / class names
    pub keep_names: MangleOptionsKeepNames,

    /// Use more readable mangled names
    /// (e.g. `slot_0`, `slot_1`, `slot_2`, ...) for debugging.
    ///
    /// Uses base54 if false.
    pub debug: bool,
}

impl MangleOptions {
    fn top_level(self, source_type: SourceType) -> bool {
        self.top_level.unwrap_or(source_type.is_module() || source_type.is_commonjs())
    }
}

type Slot = u32;

/// Sentinel for symbols the main assignment pass skipped; repaired below.
/// Safe because `SymbolId` is `NonMaxU32`, so `symbols_len` maxes out at
/// `u32::MAX - 1` and real slot values can never reach `Slot::MAX`.
const SLOT_UNASSIGNED: Slot = Slot::MAX;

/// Enum to handle both owned and borrowed allocators. This is not `Cow` because that type
/// requires `ToOwned`/`Clone`, which is not implemented for `Allocator`. Although this does
/// incur some pointer indirection on each reference to the allocator, it allows the API to be
/// more ergonomic by either accepting an existing allocator, or allowing an internal one to
/// be created and used temporarily automatically.
enum TempAllocator<'t> {
    Owned(Allocator),
    Borrowed(&'t Allocator),
}

impl TempAllocator<'_> {
    /// Get a reference to the allocator, regardless of whether it's owned or borrowed
    fn as_ref(&self) -> &Allocator {
        match self {
            TempAllocator::Owned(allocator) => allocator,
            TempAllocator::Borrowed(allocator) => allocator,
        }
    }
}

pub struct ManglerReturn {
    pub scoping: Scoping,
    /// A vector where each element corresponds to a class in declaration order.
    /// Each element is a mapping from original private member names to their mangled names.
    pub class_private_mappings: IndexVec<ClassId, FxHashMap<String, CompactStr>>,
}

/// # Name Mangler / Symbol Minification
///
/// ## Example
///
/// ```rust,ignore
/// use oxc_codegen::{Codegen, CodegenOptions};
/// use oxc_ast::ast::Program;
/// use oxc_parser::Parser;
/// use oxc_allocator::Allocator;
/// use oxc_span::SourceType;
/// use oxc_mangler::{MangleOptions, Mangler};
///
/// let allocator = Allocator::default();
/// let source = "const result = 1 + 2;";
/// let parsed = Parser::new(&allocator, source, SourceType::mjs()).parse();
/// assert!(parsed.errors.is_empty());
///
/// let mangled_symbols = Mangler::new()
///     .with_options(MangleOptions { top_level: true, debug: true })
///     .build(&parsed.program);
///
/// let js = Codegen::new().with_symbol_table(mangled_symbols).build(&parsed.program);
/// // this will be `const a = 1 + 2;` if debug = false
/// assert_eq!(js.code, "const slot_0 = 1 + 2;\n");
/// ```
///
/// ## Implementation
///
/// See:
///   * [esbuild](https://github.com/evanw/esbuild/blob/v0.24.0/docs/architecture.md#symbol-minification)
///
/// This algorithm is based on the implementation of esbuild and additionally implements improved name reuse functionality.
/// It targets for better gzip compression.
///
/// A slot is a placeholder for binding identifiers that shares the same name.
/// Visually, it is the index position for binding identifiers:
///
/// ```javascript
/// function slot0(slot1, slot2, slot3) {
///     slot2 = 1;
/// }
/// function slot1(slot0) {
///     function slot2() {
///         slot0 = 1;
///     }
/// }
/// ```
///
/// The slot number for a new scope starts after the maximum slot of the parent scope.
///
/// Occurrences of slots and their corresponding newly assigned short identifiers are:
/// - slot2: 3 - a
/// - slot0: 2 - b
/// - slot1: 2 - c
/// - slot3: 1 - d
///
/// After swapping out the mangled names:
///
/// ```javascript
/// function b(c, a, d) {
///     a = 1;
/// }
/// function c(b) {
///     function a() {
///         b = 1;
///     }
/// }
/// ```
///
/// ### Name Reuse Calculation
///
/// This improvement was inspired by [evanw/esbuild#2614](https://github.com/evanw/esbuild/pull/2614).
///
/// For better compression, we shadow the variables where possible to reuse the same name.
/// For example, the following code:
/// ```javascript
/// var top_level_a = 0;
/// var top_level_b = 1;
/// function foo() {
///   var foo_a = 1;
///   console.log(top_level_b, foo_a);
/// }
/// function bar() {
///   var bar_a = 1;
///   console.log(top_level_b, bar_a);
/// }
/// console.log(top_level_a, foo(), bar())
/// ```
/// `top_level_a` is declared in the root scope, but is not used in function `foo` and function `bar`.
/// Therefore, we can reuse the same name for `top_level_a` and `foo_a` and `bar_a`.
///
/// To calculate whether the variable name can be reused in the descendant scopes,
/// this mangler introduces a concept of symbol liveness and slot liveness.
/// Symbol liveness is a subtree of the scope tree that contains the declared scope of the symbol and
/// all the scopes that the symbol is used in. It is a subtree, so any scopes that are between the declared scope and the used scope
/// are also included. This is to ensure that the symbol is not shadowed by a different symbol before the use in the descendant scope.
///
/// For the example above, the liveness of each symbols are:
/// - `top_level_a`: root_scope
/// - `top_level_b`: root_scope -> foo, root_scope -> bar
/// - `foo_a`: root_scope -> foo
/// - `bar_a`: root_scope -> bar
/// - `foo`: root_scope
/// - `bar`: root_scope
///
/// Slot liveness is the same as symbol liveness, but it is a subforest (multiple subtrees) of the scope tree that can contain
/// multiple symbol liveness.
///
/// Now that we have the liveness of each symbol, we want to assign symbols to minimal number of slots.
/// This is a graph coloring problem where the node of the graph is the symbol and the edge of the graph indicates whether
/// the symbols has a common alive scope and the color of the node is the slot.
/// This mangler uses a greedy algorithm to assign symbols to slots to achieve that.
/// In other words, it assigns symbols to the first slot that does not live in the liveness of the symbol.
/// For the example above, each symbol is assigned to the following slots:
/// - slot 0: `top_level_a`
/// - slot 1: `top_level_b`, `foo_a`, `bar_a`
/// - slot 2: `foo`
/// - slot 3: `bar`
pub struct Mangler<'t> {
    options: MangleOptions,
    /// An allocator meant to be used for temporary allocations during mangling.
    /// It can be cleared after mangling is done, to free up memory for subsequent
    /// files or other operations.
    temp_allocator: TempAllocator<'t>,
}

impl Default for Mangler<'_> {
    fn default() -> Self {
        Self {
            options: MangleOptions::default(),
            temp_allocator: TempAllocator::Owned(Allocator::default()),
        }
    }
}

impl<'t> Mangler<'t> {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new `Mangler` using an existing temporary allocator. This is an allocator
    /// that can be reset after mangling and is only used for temporary allocations during
    /// the mangling process. This makes processing multiple files at once much more efficient,
    /// because the same memory can be used for mangling each file.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use oxc_allocator::Allocator;
    /// use oxc_mangler::Mangler;
    /// use oxc_parser::Parser;
    /// use oxc_span::SourceType;
    ///
    /// let allocator = Allocator::default();
    /// let mut temp_allocator = Allocator::default();
    /// let source = "function myFunction(param) { return param + 1; }";
    ///
    /// let parsed = Parser::new(&allocator, source, SourceType::mjs()).parse();
    /// let mangled_symbols = Mangler::new_with_temp_allocator(&temp_allocator)
    ///     .build(&parsed.program);
    ///
    /// // Reset the allocator to free temporary memory
    /// temp_allocator.reset();
    /// ```
    ///
    /// Processing multiple files:
    ///
    /// ```rust
    /// # use oxc_allocator::Allocator;
    /// # use oxc_mangler::Mangler;
    /// # use oxc_parser::Parser;
    /// # use oxc_span::SourceType;
    /// let allocator = Allocator::default();
    /// let mut temp_allocator = Allocator::default();
    /// let files = ["function foo() {}", "function bar() {}"];
    ///
    /// for source in files {
    ///     let parsed = Parser::new(&allocator, source, SourceType::mjs()).parse();
    ///     let mangled_symbols = Mangler::new_with_temp_allocator(&temp_allocator)
    ///         .build(&parsed.program);
    ///     temp_allocator.reset(); // Free memory between files
    /// }
    /// ```
    #[must_use]
    pub fn new_with_temp_allocator(temp_allocator: &'t Allocator) -> Self {
        Self {
            options: MangleOptions::default(),
            temp_allocator: TempAllocator::Borrowed(temp_allocator),
        }
    }

    #[must_use]
    pub fn with_options(mut self, options: MangleOptions) -> Self {
        self.options = options;
        self
    }

    /// Mangles the program. The resulting SymbolTable contains the mangled symbols - `program` is not modified.
    /// Pass the symbol table to oxc_codegen to generate the mangled code.
    #[must_use]
    pub fn build(self, program: &Program<'_>) -> ManglerReturn {
        let mut semantic = SemanticBuilder::new().build(program).semantic;
        let class_private_mappings = self.build_with_semantic(&mut semantic, program);
        ManglerReturn { scoping: semantic.into_scoping(), class_private_mappings }
    }

    /// # Panics
    ///
    /// Panics if the child_ids does not exist in scope_tree.
    pub fn build_with_semantic(
        self,
        semantic: &mut Semantic<'_>,
        program: &Program<'_>,
    ) -> IndexVec<ClassId, FxHashMap<String, CompactStr>> {
        let class_private_mappings = Self::collect_private_members_from_semantic(semantic);
        if self.options.debug {
            self.build_with_semantic_impl(semantic, program, debug_name);
        } else {
            self.build_with_semantic_impl(semantic, program, base54);
        }
        class_private_mappings
    }

    fn build_with_semantic_impl<const CAPACITY: usize, G: Fn(u32) -> InlineString<CAPACITY, u8>>(
        self,
        semantic: &mut Semantic<'_>,
        program: &Program<'_>,
        generate_name: G,
    ) {
        let (scoping, ast_nodes) = semantic.scoping_mut_and_nodes();
        let symbols_len = scoping.symbols_len();

        let temp_allocator = self.temp_allocator.as_ref();

        let top_level = self.options.top_level(program.source_type);
        let (exported_names, exported_symbols) = if top_level && program.source_type.is_module() {
            Mangler::collect_exported_symbols(program, temp_allocator, symbols_len)
        } else {
            (HashSet::new_in(temp_allocator), None)
        };
        let (keep_name_names, keep_name_symbols) = Mangler::collect_keep_name_symbols(
            self.options.keep_names,
            temp_allocator,
            scoping,
            ast_nodes,
        );

        // All symbols with their assigned slots. Keyed by symbol id.
        let mut slots = Vec::from_iter_in(
            iter::repeat_n(SLOT_UNASSIGNED, scoping.symbols_len()),
            temp_allocator,
        );

        // Stores the lived scope ids for each slot. Keyed by slot number.
        // Pre-allocate capacity based on number of symbols (upper bound for slots).
        let mut slot_liveness: Vec<BitSet> =
            Vec::with_capacity_in(scoping.symbols_len(), temp_allocator);
        let mut tmp_bindings = Vec::with_capacity_in(100, temp_allocator);

        let mut reusable_slots = Vec::new_in(temp_allocator);
        // Pre-computed BitSet for ancestor membership tests - reused across iterations
        let mut ancestor_set = BitSet::new_in(scoping.scopes_len(), temp_allocator);
        // Reserved names from scopes containing direct eval - these names should not
        // be used as mangled names to avoid shadowing variables that eval can access.
        //
        // TODO: This is conservative, ideally, we would reserve names per-slot.
        let mut eval_reserved_names: FxHashSet<&str> = FxHashSet::default();
        // Walk down the scope tree and assign a slot number for each symbol.
        // It is possible to do this in a loop over the symbol list,
        // but walking down the scope tree seems to generate a better code.
        for (scope_id, bindings) in scoping.iter_bindings() {
            if bindings.is_empty() {
                continue;
            }
            // Scopes with direct eval: collect binding names as reserved (they can be
            // accessed by eval at runtime) and skip slot assignment (keep original names).
            if scoping.scope_flags(scope_id).contains_direct_eval() {
                for (name, _) in bindings {
                    eval_reserved_names.insert(name.as_str());
                }
                continue;
            }

            // Sort `bindings` in declaration order.
            tmp_bindings.clear();
            tmp_bindings.extend(bindings.values().copied().filter(|binding| {
                !keep_name_symbols
                    .as_ref()
                    .is_some_and(|keep_name_symbols| keep_name_symbols.has_bit(binding.index()))
            }));
            if tmp_bindings.is_empty() {
                continue;
            }
            tmp_bindings.sort_unstable();

            let mut slot = slot_liveness.len();

            reusable_slots.clear();
            reusable_slots.extend(
                // Slots that are already assigned to other symbols, but does not live in the current scope.
                slot_liveness
                    .iter()
                    .enumerate()
                    .filter(|(_, slot_liveness)| !slot_liveness.has_bit(scope_id.index()))
                    .map(
                        // `slot_liveness` is an arena `Vec`, so its indexes cannot exceed `u32::MAX`
                        #[expect(clippy::cast_possible_truncation)]
                        |(slot, _)| slot as Slot,
                    )
                    .take(tmp_bindings.len()),
            );

            // The number of new slots that needs to be allocated.
            let remaining_count = tmp_bindings.len() - reusable_slots.len();
            // There cannot be more slots than there are symbols, and `SymbolId` is a `u32`,
            // so truncation is not possible here
            #[expect(clippy::cast_possible_truncation)]
            reusable_slots.extend((slot as Slot)..(slot + remaining_count) as Slot);

            slot += remaining_count;
            if slot_liveness.len() < slot {
                slot_liveness.extend(
                    iter::repeat_with(|| BitSet::new_in(scoping.scopes_len(), temp_allocator))
                        .take(remaining_count),
                );
            }

            // Pre-compute the set of ancestors from root to scope_id (exclusive) for O(1) membership tests.
            // This avoids repeated `take_while` comparisons in the inner loop.
            ancestor_set.clear();
            for ancestor_id in scoping.scope_ancestors(scope_id).skip(1) {
                ancestor_set.set_bit(ancestor_id.index());
            }

            let scope_id_index = scope_id.index();
            for (&symbol_id, &assigned_slot) in tmp_bindings.iter().zip(&reusable_slots) {
                slots[symbol_id.index()] = assigned_slot;

                // If the symbol is declared by `var`, then it can be hoisted to
                // parent, so we need to include the scope where it is declared.
                // (for cases like `function foo() { { var x; let y; } }`)
                let declared_scope_id =
                    ast_nodes.get_node(scoping.symbol_declaration(symbol_id)).scope_id();

                let redeclared_scope_ids = scoping
                    .symbol_redeclarations(symbol_id)
                    .iter()
                    .map(|r| ast_nodes.get_node(r.declaration).scope_id());

                let referenced_scope_ids =
                    scoping.get_resolved_references(symbol_id).map(Reference::scope_id);

                // Calculate the scope ids that this symbol is alive in.
                // For each used_scope_id, we walk up the ancestor chain and collect scopes
                // that are descendants of scope_id (i.e., not in ancestor_set and not scope_id itself).
                let slot_liveness_bitset = &mut slot_liveness[assigned_slot as usize];
                for used_scope_id in referenced_scope_ids
                    .chain(redeclared_scope_ids)
                    .chain([scope_id, declared_scope_id])
                {
                    for ancestor_id in scoping.scope_ancestors(used_scope_id) {
                        let ancestor_index = ancestor_id.index();
                        // Stop when we reach scope_id or any of its ancestors
                        if ancestor_index == scope_id_index || ancestor_set.has_bit(ancestor_index)
                        {
                            break;
                        }
                        if slot_liveness_bitset.has_bit(ancestor_index) {
                            debug_assert!(
                                scoping.scope_ancestors(ancestor_id).skip(1).all(|a| {
                                    let idx = a.index();
                                    slot_liveness_bitset.has_bit(idx)
                                        || idx == scope_id_index
                                        || ancestor_set.has_bit(idx)
                                }),
                                "Invariant violated: ancestor chain should be fully marked live"
                            );
                            break;
                        }
                        slot_liveness_bitset.set_bit(ancestor_index);
                    }
                }
            }

            // Repair an orphaned named-fn-expr name: a same-named body declaration
            // (`var foo`, parameter `foo`) overwrites the fn-expr's binding-map entry,
            // so the fn-expr symbol never appears in `bindings` and the main pass leaves
            // its slot at `SLOT_UNASSIGNED`. Copy the shadower's slot so both render with
            // the same mangled name — safe because every body reference resolves to the
            // shadower, not the orphan. Only function expressions can host this orphaning;
            // a function declaration's name lives in the parent scope and is unaffected.
            // The shadower-slot guard catches the case where the shadower is in
            // `keep_name_symbols` (filtered out above and itself unassigned).
            if scoping.scope_flags(scope_id).is_function()
                && let Some(func) = ast_nodes.kind(scoping.get_node_id(scope_id)).as_function()
                && func.is_expression()
                && let Some(id) = &func.id
                && let Some(&shadower) = bindings.get(&id.name)
                && shadower != id.symbol_id()
                && slots[shadower.index()] != SLOT_UNASSIGNED
            {
                slots[id.symbol_id().index()] = slots[shadower.index()];
            }
        }

        let total_number_of_slots = slot_liveness.len();

        let frequencies = self.tally_slot_frequencies(
            scoping,
            exported_symbols.as_ref(),
            keep_name_symbols.as_ref(),
            total_number_of_slots,
            &slots,
            top_level,
        );

        let root_unresolved_references = scoping.root_unresolved_references();
        let root_bindings = scoping.get_bindings(scoping.root_scope_id());

        // Generate reserved names only for slots that have symbols (frequencies.len())
        // instead of all slots. This avoids generating unused names.
        let names_needed = frequencies.len();
        let mut reserved_names = Vec::with_capacity_in(names_needed, temp_allocator);

        let mut count = 0;
        for _ in 0..names_needed {
            let name = loop {
                let name = generate_name(count);
                count += 1;
                // Do not mangle keywords, unresolved references, and names from eval scopes.
                // Variables in direct-eval-containing scopes keep their original names
                // (those scopes are skipped during slot assignment), and we also reserve
                // those names here to prevent mangled names from shadowing them.
                let n = name.as_str();
                if !oxc_syntax::keyword::is_reserved_keyword(n)
                    && !is_special_name(n)
                    && !root_unresolved_references.contains_key(n)
                    && !(root_bindings.contains_key(n)
                        && (!top_level || exported_names.contains(n)))
                    // TODO: only skip the names that are kept in the current scope
                    && !keep_name_names.contains(n)
                    && !eval_reserved_names.contains(n)
                {
                    break name;
                }
            };
            reserved_names.push(name);
        }

        // Group similar symbols for smaller gzipped file
        // <https://github.com/google/closure-compiler/blob/c383a3a1d2fce33b6c778ef76b5a626e07abca41/src/com/google/javascript/jscomp/RenameVars.java#L475-L483>
        // Original Comment:
        // 1) The most frequent vars get the shorter names.
        // 2) If N number of vars are going to be assigned names of the same
        //    length, we assign the N names based on the order at which the vars
        //    first appear in the source. This makes the output somewhat less
        //    random, because symbols declared close together are assigned names
        //    that are quite similar. With this heuristic, the output is more
        //    compressible.
        //    For instance, the output may look like:
        //    var da = "..", ea = "..";
        //    function fa() { .. } function ga() { .. }

        let mut freq_iter = frequencies.iter();
        let mut symbols_renamed_in_this_batch = Vec::with_capacity_in(100, temp_allocator);
        let mut slice_of_same_len_strings = Vec::with_capacity_in(100, temp_allocator);
        // 2. "N number of vars are going to be assigned names of the same length"
        for (_, slice_of_same_len_strings_group) in
            &reserved_names.into_iter().chunk_by(InlineString::len)
        {
            // 1. "The most frequent vars get the shorter names"
            // (freq_iter is sorted by frequency from highest to lowest,
            //  so taking means take the N most frequent symbols remaining)
            slice_of_same_len_strings.clear();
            slice_of_same_len_strings.extend(slice_of_same_len_strings_group);
            symbols_renamed_in_this_batch.clear();
            symbols_renamed_in_this_batch
                .extend(freq_iter.by_ref().take(slice_of_same_len_strings.len()));

            debug_assert_eq!(symbols_renamed_in_this_batch.len(), slice_of_same_len_strings.len());

            // 2. "we assign the N names based on the order at which the vars first appear in the source."
            // sorting by slot enables us to sort by the order at which the vars first appear in the source
            // (this is possible because the slots are discovered currently in a DFS method which is the same order
            //  as variables appear in the source code)
            symbols_renamed_in_this_batch.sort_unstable_by_key(|a| a.slot);

            // here we just zip the iterator of symbols to rename with the iterator of new names for the next for loop
            let symbols_to_rename_with_new_names =
                symbols_renamed_in_this_batch.iter().zip(slice_of_same_len_strings.iter());

            // rename the variables
            for (symbol_to_rename, new_name) in symbols_to_rename_with_new_names {
                for &symbol_id in &symbol_to_rename.symbol_ids {
                    scoping.set_symbol_name(symbol_id, Ident::from(new_name.as_str()));
                }
            }
        }
    }

    fn tally_slot_frequencies<'a>(
        &'a self,
        scoping: &Scoping,
        exported_symbols: Option<&BitSet<'a>>,
        keep_name_symbols: Option<&BitSet<'a>>,
        total_number_of_slots: usize,
        slots: &[Slot],
        top_level: bool,
    ) -> Vec<'a, SlotFrequency<'a>> {
        let root_scope_id = scoping.root_scope_id();
        let temp_allocator = self.temp_allocator.as_ref();
        let mut frequencies = Vec::from_iter_in(
            repeat_with(|| SlotFrequency::new(temp_allocator)).take(total_number_of_slots),
            temp_allocator,
        );

        for (symbol_id, &slot) in slots.iter().enumerate() {
            if slot == SLOT_UNASSIGNED {
                continue;
            }
            let symbol_id = SymbolId::from_usize(symbol_id);
            let symbol_scope_id = scoping.symbol_scope_id(symbol_id);
            if symbol_scope_id == root_scope_id
                && (!top_level
                    || exported_symbols.is_some_and(|exported_symbols| {
                        exported_symbols.has_bit(symbol_id.index())
                    }))
            {
                continue;
            }
            if scoping.scope_flags(symbol_scope_id).contains_direct_eval() {
                continue;
            }
            if is_special_name(scoping.symbol_name(symbol_id)) {
                continue;
            }
            if keep_name_symbols
                .is_some_and(|keep_name_symbols| keep_name_symbols.has_bit(symbol_id.index()))
            {
                continue;
            }
            let index = slot as usize;
            frequencies[index].slot = slot;
            frequencies[index].frequency += scoping.get_resolved_reference_ids(symbol_id).len();
            frequencies[index].symbol_ids.push(symbol_id);
        }

        // Remove slots that have no symbols to rename before sorting.
        frequencies.retain(|x| !x.symbol_ids.is_empty());
        frequencies.sort_unstable_by_key(|x| std::cmp::Reverse(x.frequency));
        frequencies
    }

    fn collect_exported_symbols<'a>(
        program: &Program<'a>,
        allocator: &'a Allocator,
        symbols_len: usize,
    ) -> (HashSet<'a, Str<'a>>, Option<BitSet<'a>>) {
        let mut exported_symbols = BitSet::new_in(symbols_len, allocator);
        let mut exported_names = HashSet::new_in(allocator);
        for statement in &program.body {
            let Statement::ExportNamedDeclaration(v) = statement else { continue };
            let Some(decl) = &v.declaration else { continue };
            if let Declaration::VariableDeclaration(decl) = decl {
                for decl in &decl.declarations {
                    if let Some(id) = decl.id.get_binding_identifier() {
                        exported_names.insert(id.name.as_arena_str());
                        exported_symbols.set_bit(id.symbol_id().index());
                    }
                }
            } else if let Some(id) = decl.id() {
                exported_names.insert(id.name.as_arena_str());
                exported_symbols.set_bit(id.symbol_id().index());
            }
        }
        (exported_names, Some(exported_symbols))
    }

    fn collect_keep_name_symbols<'a>(
        keep_names: MangleOptionsKeepNames,
        temp_allocator: &'t Allocator,
        scoping: &'a Scoping,
        nodes: &AstNodes,
    ) -> (FxHashSet<&'a str>, Option<BitSet<'t>>) {
        if !keep_names.function && !keep_names.class {
            return (FxHashSet::default(), None);
        }
        let ids = collect_name_symbols(keep_names, temp_allocator, scoping, nodes);
        (ids.ones().map(|id| scoping.symbol_name(SymbolId::from_usize(id))).collect(), Some(ids))
    }

    /// Collects and generates mangled names for private members using semantic information
    /// Returns a Vec where each element corresponds to a class in declaration order
    fn collect_private_members_from_semantic(
        semantic: &Semantic<'_>,
    ) -> IndexVec<ClassId, FxHashMap<String, CompactStr>> {
        let classes = semantic.classes();

        let private_member_count: IndexVec<ClassId, usize> = classes
            .elements
            .iter()
            .map(|class_elements| {
                class_elements.iter().filter(|element| element.is_private).count()
            })
            .collect();
        let parent_private_member_count: IndexVec<ClassId, usize> = classes
            .declarations
            .iter_enumerated()
            .map(|(class_id, _)| {
                classes
                    .ancestors(class_id)
                    .skip(1)
                    .map(|id| private_member_count[id])
                    .sum::<usize>()
            })
            .collect();

        classes
            .elements
            .iter_enumerated()
            .map(|(class_id, class_elements)| {
                let parent_private_member_count = parent_private_member_count[class_id];
                assert!(
                    u32::try_from(class_elements.len() + parent_private_member_count).is_ok(),
                    "too many class elements"
                );
                class_elements
                    .iter()
                    .filter_map(|element| {
                        if element.is_private { Some(element.name.to_string()) } else { None }
                    })
                    .enumerate()
                    .map(|(i, name)| {
                        #[expect(
                            clippy::cast_possible_truncation,
                            reason = "checked above with assert"
                        )]
                        let mangled = CompactStr::new(
                            // Avoid reusing the same mangled name in parent classes.
                            // We can improve this by reusing names that are not used in child classes,
                            // but nesting a class inside another class is not common
                            // and that would require liveness analysis.
                            base54((parent_private_member_count + i) as u32).as_str(),
                        );
                        (name, mangled)
                    })
                    .collect::<FxHashMap<_, _>>()
            })
            .collect()
    }
}

fn is_special_name(name: &str) -> bool {
    matches!(name, "arguments")
}

#[derive(Debug)]
struct SlotFrequency<'a> {
    pub slot: Slot,
    pub frequency: usize,
    pub symbol_ids: Vec<'a, SymbolId>,
}

impl<'t> SlotFrequency<'t> {
    fn new(temp_allocator: &'t Allocator) -> Self {
        Self { slot: 0, frequency: 0, symbol_ids: Vec::new_in(temp_allocator) }
    }
}

// Maximum length of string is 15 (`slot_4294967295` for `u32::MAX`).
fn debug_name(n: u32) -> InlineString<15, u8> {
    // Using `format!` here allocates a string unnecessarily.
    // But this function is not for use in production, so let's not worry about it.
    // We shouldn't resort to unsafe code, when it's not critical for performance.
    InlineString::from_str(&format!("slot_{n}"))
}