rolldown 1.0.0

Fast JavaScript bundler in Rust, designed for the future of Vite
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
use itertools::Itertools;
use oxc::allocator::FromIn;
use oxc::ast::AstType;
use oxc::ast::ast::{AssignmentTarget, JSXMemberExpression, Str};
use oxc::{
  allocator::{self, Dummy as _, IntoIn, TakeIn},
  ast::{
    NONE,
    ast::{self, BindingPattern, Expression, SimpleAssignmentTarget, Statement},
    match_member_expression,
  },
  ast_visit::{VisitMut, walk_mut},
  semantic::ScopeFlags,
  span::{SPAN, Span},
};
use oxc_str::CompactStr;
use rolldown_common::{ConcatenateWrappedModuleKind, SymbolRef, ThisExprReplaceKind, WrapKind};
use rolldown_ecmascript::ToSourceString;
use rolldown_ecmascript_utils::{ExpressionExt, JsxExt, JsxMemberExpressionObjectExt};

use crate::hmr::utils::HmrAstBuilder;
use crate::module_finalizers::{KeepNameId, TraverseState};

use super::ScopeHoistingFinalizer;

impl<'ast> VisitMut<'ast> for ScopeHoistingFinalizer<'_, 'ast> {
  fn enter_scope(
    &mut self,
    flags: oxc::semantic::ScopeFlags,
    _scope_id: &std::cell::Cell<Option<oxc::semantic::ScopeId>>,
  ) {
    self.scope_stack.push(flags);
    self.state.set(
      TraverseState::TopLevel,
      self.scope_stack.iter().rev().all(|flag| flag.is_block() || flag.is_top()),
    );
    self
      .state
      .set(TraverseState::IsRootLevel, self.scope_stack.iter().rev().all(|flag| flag.is_top()));
  }

  fn leave_scope(&mut self) {
    self.scope_stack.pop();
    self.state.set(
      TraverseState::TopLevel,
      self.scope_stack.iter().rev().all(|flag| flag.is_block() || flag.is_top()),
    );
    self
      .state
      .set(TraverseState::IsRootLevel, self.scope_stack.iter().rev().all(|flag| flag.is_top()));
  }

  fn visit_if_statement(&mut self, it: &mut ast::IfStatement<'ast>) {
    let kind = AstType::IfStatement;
    self.enter_node(kind);
    self.visit_span(&mut it.span);
    let pre = self.state;
    self.state.insert(TraverseState::SmartInlineConst);
    self.visit_expression(&mut it.test);
    self.state = pre;
    self.visit_statement(&mut it.consequent);
    if let Some(alternate) = &mut it.alternate {
      self.visit_statement(alternate);
    }
    self.leave_node(kind);
  }

  fn visit_conditional_expression(&mut self, it: &mut ast::ConditionalExpression<'ast>) {
    let kind = AstType::ConditionalExpression;
    self.enter_node(kind);
    self.visit_span(&mut it.span);
    let pre = self.state;
    self.state.insert(TraverseState::SmartInlineConst);
    self.visit_expression(&mut it.test);
    self.state = pre;
    self.visit_expression(&mut it.consequent);
    self.visit_expression(&mut it.alternate);
    self.leave_node(kind);
  }

  fn visit_logical_expression(&mut self, it: &mut ast::LogicalExpression<'ast>) {
    let pre = self.state;
    self.state.insert(TraverseState::SmartInlineConst);
    walk_mut::walk_logical_expression(self, it);
    self.state = pre;
  }

  fn visit_program(&mut self, program: &mut ast::Program<'ast>) {
    // Drop the hashbang since we already store them in ast_scan phase and
    // we don't want oxc to generate hashbang statement and directives in module level since we already handle
    // them in chunk level
    program.hashbang.take();
    program.directives.clear();
    // init namespace_alias_symbol_id

    let last_import_stmt_idx = self.remove_unused_top_level_stmt(program);

    if self.ctx.options.is_dev_mode_enabled() {
      let hmr_header = if self.ctx.runtime.id() == self.ctx.module.idx {
        vec![]
      } else {
        // FIXME(hyf0): Module register relies on runtime module, this causes a runtime error for registering runtime module.
        // Let's skip it for now.
        self.generate_hmr_header()
      };
      program.body.splice(last_import_stmt_idx..last_import_stmt_idx, hmr_header);
    }

    // check if we need to add wrapper
    let included_wrap_kind = self
      .ctx
      .linking_info
      .wrapper_stmt_info
      .is_some_and(|idx| self.ctx.linking_info.stmt_info_included.has_bit(idx))
      .then_some(self.ctx.linking_info.wrap_kind());

    self.needs_hosted_top_level_binding = matches!(included_wrap_kind, Some(WrapKind::Esm));

    // the order should be
    // 1. module namespace object declaration
    // 2. shimmed_exports
    // 3. hoisted_names
    // 4. wrapped module declaration
    let declaration_of_module_namespace_object =
      self.generate_declaration_of_module_namespace_object();

    let mut shimmed_exports =
      self.ctx.linking_info.shimmed_missing_exports.iter().collect::<Vec<_>>();
    shimmed_exports.sort_unstable_by_key(|(name, _)| name.as_str());
    shimmed_exports.into_iter().for_each(|(_name, symbol_ref)| {
      debug_assert!(!self.ctx.stmt_infos.declared_stmts_by_symbol(symbol_ref).is_empty());
      let is_included: bool = self
        .ctx
        .stmt_infos
        .declared_stmts_by_symbol(symbol_ref)
        .iter()
        .any(|id| self.ctx.linking_info.stmt_info_included.has_bit(*id));
      if is_included {
        let canonical_name = self.canonical_name_for(*symbol_ref);
        program.body.push(self.snippet.var_decl_stmt(canonical_name, self.snippet.void_zero()));
      }
    });

    self.enter_scope(
      {
        let mut flags = ScopeFlags::Top;
        if program.source_type.is_strict() || program.has_use_strict_directive() {
          flags |= ScopeFlags::StrictMode;
        }
        flags
      },
      &program.scope_id,
    );
    walk_mut::walk_program(self, program);
    self.leave_scope();

    // Insert keep_name statements for top-level declarations
    self.insert_keep_name_statements(&mut program.body);
    self.keep_name_statement_to_insert.clear();

    match included_wrap_kind {
      Some(WrapKind::Cjs) => {
        let wrap_ref_name = self.canonical_name_for(self.ctx.linking_info.wrapper_ref.unwrap());
        let commonjs_ref = if self.ctx.options.profiler_names {
          self.canonical_ref_for_runtime("__commonJS")
        } else {
          self.canonical_ref_for_runtime("__commonJSMin")
        };

        let (commonjs_ref_expr, _) = self.finalized_expr_for_symbol_ref(commonjs_ref, false, false);

        let mut stmts_inside_closure = allocator::Vec::new_in(self.alloc);
        stmts_inside_closure.append(&mut program.body);

        program.body.push(self.snippet.commonjs_wrapper_stmt(
          wrap_ref_name,
          commonjs_ref_expr,
          stmts_inside_closure,
          self.ctx.module.ast_usage,
          self.ctx.options.profiler_names,
          &self.ctx.module.stable_id,
          self.ctx.linking_info.is_tla_or_contains_tla_dependency,
        ));
      }
      Some(WrapKind::Esm) => {
        let is_concatenated_wrapped_module = !matches!(
          self.ctx.linking_info.concatenated_wrapped_module_kind,
          ConcatenateWrappedModuleKind::None
        );
        let old_body = program.body.take_in(self.alloc);

        let mut fn_stmts = allocator::Vec::new_in(self.alloc);
        let mut stmts_inside_closure = allocator::Vec::new_in(self.alloc);

        // Hoist all top-level "var" and "function" declarations out of the closure
        old_body.into_iter().for_each(|mut stmt| match &mut stmt {
            ast::Statement::FunctionDeclaration(_) => {
              fn_stmts.push(stmt);
            }
            ast::match_module_declaration!(Statement) => {
              if stmt.is_typescript_syntax() {
                unreachable!(
                  "At this point, typescript module declarations should have been removed or transformed"
                )
              }
              program.body.push(stmt);
            }
            _ => {
              stmts_inside_closure.push(stmt);
            }
          });

        if is_concatenated_wrapped_module {
          self.rendered_concatenated_wrapped_module_parts.hoisted_functions_or_module_ns_decl =
            declaration_of_module_namespace_object
              .iter()
              .chain(fn_stmts.iter())
              .map(rolldown_ecmascript::ToSourceString::to_source_string)
              .collect_vec();
          self.rendered_concatenated_wrapped_module_parts.hoisted_vars = self
            .top_level_var_bindings
            .iter()
            .map(|var_name| CompactStr::new(var_name))
            .collect_vec();
        } else {
          program.body.extend(declaration_of_module_namespace_object);
          program.body.extend(fn_stmts);
        }

        if !is_concatenated_wrapped_module && !self.top_level_var_bindings.is_empty() {
          let builder = self.builder();
          let decorations = self.top_level_var_bindings.iter().map(|var_name| {
            builder.variable_declarator(
              SPAN,
              ast::VariableDeclarationKind::Var,
              builder.binding_pattern_binding_identifier(SPAN, *var_name),
              NONE,
              None,
              false,
            )
          });
          program.body.push(Statement::VariableDeclaration(builder.alloc_variable_declaration(
            SPAN,
            ast::VariableDeclarationKind::Var,
            builder.vec_from_iter(decorations),
            false,
          )));
        }

        // The wrapping would happen during the chunk codegen phase
        if matches!(
          self.ctx.linking_info.concatenated_wrapped_module_kind,
          ConcatenateWrappedModuleKind::Inner
        ) {
          program.body.extend(stmts_inside_closure);
          return;
        }

        let esm_ref = if self.ctx.options.profiler_names {
          self.canonical_ref_for_runtime("__esm")
        } else {
          self.canonical_ref_for_runtime("__esmMin")
        };
        let (esm_ref_expr, _) = self.finalized_expr_for_symbol_ref(esm_ref, false, false);
        let wrap_ref_name = self.canonical_name_for(self.ctx.linking_info.wrapper_ref.unwrap());

        if matches!(
          self.ctx.linking_info.concatenated_wrapped_module_kind,
          ConcatenateWrappedModuleKind::Root
        ) {
          self.rendered_concatenated_wrapped_module_parts.rendered_esm_runtime_expr =
            Some(self.builder().expression_statement(SPAN, esm_ref_expr).to_source_string());
          self.rendered_concatenated_wrapped_module_parts.wrap_ref_name =
            Some(CompactStr::new(wrap_ref_name));
          program.body.extend(stmts_inside_closure);
          return;
        }

        program.body.push(self.snippet.esm_wrapper_stmt(
          wrap_ref_name,
          esm_ref_expr,
          stmts_inside_closure,
          self.ctx.options.profiler_names,
          self.ctx.options.optimization.is_pife_for_module_wrappers_enabled(),
          &self.ctx.module.stable_id,
          self.ctx.linking_info.is_tla_or_contains_tla_dependency,
        ));
      }
      Some(WrapKind::None) => {}
      None => {
        program.body.splice(0..0, declaration_of_module_namespace_object);
      }
    }

    if self.json_module_inlined_prop.is_some() {
      program.body.drain_filter(|item| matches!(item, ast::Statement::EmptyStatement(_)));
    }
  }

  fn visit_binding_identifier(&mut self, ident: &mut ast::BindingIdentifier<'ast>) {
    if let Some(symbol_id) = ident.symbol_id.get() {
      let symbol_ref: SymbolRef = (self.ctx.idx, symbol_id).into();

      let canonical_ref = self.ctx.symbol_db.canonical_ref_for(symbol_ref);
      let symbol = self.ctx.symbol_db.get(canonical_ref);
      assert!(symbol.namespace_alias.is_none());
      let canonical_name = self.canonical_name_for(symbol_ref);
      if ident.name != canonical_name {
        ident.name = self.snippet.atom(canonical_name).into();
      }
      ident.symbol_id.get_mut().take();
    } else {
      // Some `BindingIdentifier`s constructed by bundler don't have `SymbolId` and we just ignore them.
    }
  }

  fn visit_statement(&mut self, it: &mut ast::Statement<'ast>) {
    _ = self.try_inline_json_module_prop(it);

    if !self.ctx.options.drop_labels.is_empty() {
      if let ast::Statement::LabeledStatement(stmt) = it {
        if self.ctx.options.drop_labels.contains(stmt.label.name.as_str()) {
          *it = self.snippet.builder.statement_empty(stmt.span);
        }
      }
    }
    walk_mut::walk_statement(self, it);

    // transform top level `var a = 1, b = 1;` to `a = 1, b = 1`
    // for `__esm(() => {})` wrapping VariableDeclaration hoist
    if self.state.contains(TraverseState::TopLevel)
      && self.needs_hosted_top_level_binding
      && let ast::Statement::VariableDeclaration(decl) = it
    {
      if let Some((expr, bindings)) =
        self.var_declaration_to_expr_seq_and_bindings(decl, self.state)
      {
        self.top_level_var_bindings.extend(bindings);
        *it = ast::Statement::ExpressionStatement(
          self.builder().alloc_expression_statement(SPAN, expr),
        );
      }
    }
  }

  fn visit_statements(&mut self, it: &mut allocator::Vec<'ast, ast::Statement<'ast>>) {
    let previous_stmt_index = self.cur_stmt_index;
    let previous_keep_name_statement = std::mem::take(&mut self.keep_name_statement_to_insert);
    for (i, stmt) in it.iter_mut().enumerate() {
      self.cur_stmt_index = i;
      self.visit_statement(stmt);
    }

    self.insert_keep_name_statements(it);
    self.cur_stmt_index = previous_stmt_index;
    self.keep_name_statement_to_insert = previous_keep_name_statement;
  }

  fn visit_identifier_reference(&mut self, ident: &mut ast::IdentifierReference) {
    // This ensure all `IdentifierReference`s are processed
    debug_assert!(
      self.is_global_identifier_reference(ident) || ident.reference_id.get().is_none(),
      "{} doesn't get processed in {}",
      ident.name,
      self.ctx.module.repr_name
    );
  }

  fn visit_expression(&mut self, expr: &mut ast::Expression<'ast>) {
    // Handle keep_names for named class/function expressions in any expression context
    // (return statements, function args, array elements, etc.)
    if self.ctx.options.keep_names && self.ctx.runtime.id() != self.ctx.idx {
      match expr {
        ast::Expression::ClassExpression(class_expression) => {
          if let Some(id) = class_expression.id.as_ref() {
            if let Some(element) = self.keep_name_helper_for_class(
              id.symbol_id.get().map(KeepNameId::SymbolId),
              &class_expression.body,
            ) {
              class_expression.body.body.insert(0, element);
            }
          }
        }
        ast::Expression::FunctionExpression(fn_expression) => {
          if let Some(id) = fn_expression.id.as_mut() {
            if let Some(symbol_id) = id.symbol_id.get() {
              let keep_name_id = KeepNameId::SymbolId(symbol_id);
              if let Some((_insert_position, original_name, _)) =
                self.process_fn(Some(keep_name_id), Some(keep_name_id))
              {
                // Manually rename the binding identifier before clearing symbol_id
                let symbol_ref: SymbolRef = (self.ctx.idx, symbol_id).into();
                let canonical_name = self.canonical_name_for(symbol_ref);
                if id.name != canonical_name {
                  id.name = self.snippet.atom(canonical_name).into();
                }
                // Clear symbol_id to prevent double processing:
                // - visit_expression won't re-wrap when walker visits inner fn
                // - visit_binding_identifier won't re-rename
                id.symbol_id.get_mut().take();

                let fn_expr = expr.take_in(self.alloc);
                let name_ref = self.canonical_ref_for_runtime("__name");
                let (finalized_callee, _) =
                  self.finalized_expr_for_symbol_ref(name_ref, false, false);
                *expr =
                  self.snippet.keep_name_call_expr(&original_name, fn_expr, finalized_callee, true);
              }
            }
          }
        }
        _ => {}
      }
    }

    match expr {
      ast::Expression::CallExpression(call_expr) => {
        self.rewrite_hot_accept_call_deps(call_expr);
        if let Some(new_expr) = self.try_rewrite_global_require_call(call_expr) {
          *expr = new_expr;
        } else if let Some(ident_ref) = call_expr.callee.as_identifier_mut() {
          let is_empty_function = ident_ref
            .reference_id
            .get()
            .and_then(|ref_id| self.scope.scoping().get_reference(ref_id).symbol_id())
            .map(|id| {
              let symbol_ref = self.ctx.symbol_db.canonical_ref_for((self.ctx.idx, id).into());
              symbol_ref.is_side_effect_free_function(self.ctx.symbol_db, self.ctx.modules)
                && symbol_ref.is_not_reassigned(self.ctx.symbol_db) == Some(true)
            })
            .unwrap_or(false);
          if is_empty_function {
            call_expr.pure = true;
          } else if let Some(new_expr) = self.try_rewrite_identifier_reference_expr(ident_ref, true)
          {
            call_expr.callee = new_expr;
          }
        }
      }
      // inline dynamic import
      ast::Expression::ImportExpression(import_expr) => {
        if let Some(new_expr) = self.try_rewrite_inline_dynamic_import_expr(import_expr) {
          *expr = new_expr;
        }
        if self.try_rewrite_import_expression(expr) {
          // If the import expression is rewritten, we don't need to walk it again.
          // Otherwise, it might cause infinite recursion in some cases.
          return;
        }
      }
      ast::Expression::NewExpression(new_expr) => {
        self.handle_new_url_with_string_literal_and_import_meta_url(new_expr);
      }
      ast::Expression::Identifier(ident_ref) => {
        if let Some(new_expr) = self.try_rewrite_identifier_reference_expr(ident_ref, false) {
          *expr = new_expr;
        }
      }
      ast::Expression::ThisExpression(this_expr) => {
        if let Some(kind) = self.ctx.module.ecma_view.this_expr_replace_map.get(&this_expr.span) {
          match kind {
            ThisExprReplaceKind::Exports => {
              *expr = self.snippet.builder.expression_identifier(SPAN, "exports");
            }
            ThisExprReplaceKind::Context if self.ctx.options.context.is_empty() => {
              *expr = self.snippet.void_zero();
            }
            ThisExprReplaceKind::Context => {
              *expr = self.snippet.builder.expression_identifier(
                SPAN,
                Str::from_in(self.ctx.options.context.as_str(), self.alloc),
              );
            }
          }
        }
      }
      ast::Expression::MetaProperty(meta) => {
        if !self.ctx.options.format.keep_esm_import_export_syntax()
          && meta.meta.name == "import"
          && meta.property.name == "meta"
        {
          *expr = self.snippet.builder.expression_object(SPAN, self.snippet.builder.vec());
        }
      }
      ast::Expression::ChainExpression(_) => {
        // Try inline as enum access first (`E?.x` → literal). Enum bindings are
        // always defined (the IIFE produces `{}`, never null/undefined), so `?.`
        // is equivalent to `.` here.
        if self.ctx.has_enum_inlining
          && let Some(new_expr) = self.try_inline_enum_access(expr)
        {
          *expr = new_expr;
          self.rewrite_import_meta_hot(expr);
          walk_mut::walk_expression(self, expr);
          return;
        }

        let ast::Expression::ChainExpression(chain_expr) = expr else { unreachable!() };
        let chain_span = chain_expr.span;
        if let Some(new_expr) = chain_expr
          .expression
          .as_member_expression_mut()
          .and_then(|expr| self.try_rewrite_member_expr(expr))
        {
          // If the rewritten expression contains optional member accesses (?.),
          // it must remain wrapped in a ChainExpression for valid JavaScript output.
          if has_optional_member_access(&new_expr) {
            match new_expr {
              ast::Expression::StaticMemberExpression(member) => {
                *expr = self
                  .snippet
                  .builder
                  .expression_chain(chain_span, ast::ChainElement::StaticMemberExpression(member));
              }
              ast::Expression::ComputedMemberExpression(member) => {
                *expr = self.snippet.builder.expression_chain(
                  chain_span,
                  ast::ChainElement::ComputedMemberExpression(member),
                );
              }
              _ => {
                *expr = new_expr;
              }
            }
          } else {
            *expr = new_expr;
          }
        }
      }
      _ => {
        // Try to inline enum member accesses (e.g., `Direction.Up` → `0`, `ns.c.x` → `"c"`)
        if self.ctx.has_enum_inlining {
          if let Some(new_expr) = self.try_inline_enum_access(expr) {
            *expr = new_expr;
            self.rewrite_import_meta_hot(expr);
            walk_mut::walk_expression(self, expr);
            return;
          }
        }
        if let Some(new_expr) =
          expr.as_member_expression().and_then(|expr| self.try_rewrite_member_expr(expr))
        {
          *expr = new_expr;
          // After namespace rewriting (e.g., `ns.c` → `c`), the result may be
          // an enum member access that can be inlined.
          if self.ctx.has_enum_inlining {
            if let Some(inlined) = self.try_inline_enum_access(expr) {
              *expr = inlined;
            }
          }
        }
      }
    }
    self.rewrite_import_meta_hot(expr);

    walk_mut::walk_expression(self, expr);
  }

  fn visit_jsx_element_name(&mut self, it: &mut ast::JSXElementName<'ast>) {
    match it {
      ast::JSXElementName::Identifier(ident) => {
        walk_mut::walk_jsx_identifier(self, ident);
      }
      ast::JSXElementName::IdentifierReference(identifier_reference) => {
        if let Some(new_expr) =
          self.try_rewrite_identifier_reference_expr(identifier_reference, false)
        {
          match new_expr {
            Expression::Identifier(ident_ref) => {
              *it = ast::JSXElementName::IdentifierReference(ident_ref);
            }
            Expression::StaticMemberExpression(member_expr) => {
              *it = ast::JSXElementName::MemberExpression(oxc::allocator::Box::new_in(
                JSXMemberExpression::from_ast(member_expr.unbox(), self.alloc).unwrap(),
                self.alloc,
              ));
            }
            Expression::ThisExpression(this_expr) => {
              *it = ast::JSXElementName::ThisExpression(this_expr);
            }
            _ => {
              unreachable!(
                "Should always rewrite to Identifier, StaticMemberExpression, or ThisExpression for JsxElementName::IdentifierReference"
              )
            }
          }
        }
      }
      ast::JSXElementName::NamespacedName(jsx_namespace_name) => {
        walk_mut::walk_jsx_namespaced_name(self, jsx_namespace_name);
      }
      ast::JSXElementName::MemberExpression(jsx_member_expression) => {
        if let Some(ident) = jsx_member_expression.get_identifier() {
          if let Some(new_expr) = self.try_rewrite_identifier_reference_expr(ident, false) {
            match new_expr {
              Expression::Identifier(ident_ref) => {
                jsx_member_expression.object.rewrite_ident_reference(
                  ast::JSXMemberExpressionObject::IdentifierReference(ident_ref),
                );
              }
              Expression::StaticMemberExpression(member_expr) => {
                jsx_member_expression.object.rewrite_ident_reference(
                  ast::JSXMemberExpressionObject::MemberExpression(oxc::allocator::Box::new_in(
                    // TODO: Currently only support `StaticMemberExpression`, `ThisExpression` and `IdentifierReference`.
                    // In most of scenarios, it should be enough. The ultimate solution is create
                    // an extra binding for the cjs property access then *Uppercase* the binding.
                    JSXMemberExpression::from_ast(member_expr.unbox(), self.alloc).unwrap(),
                    self.alloc,
                  )),
                );
              }
              Expression::ThisExpression(this_expr) => {
                *it = ast::JSXElementName::ThisExpression(this_expr);
              }
              _ => {
                unreachable!(
                  "Should always rewrite to Identifier for JsxMemberExpression::get_identifier()"
                )
              }
            }
          }
        }
      }
      ast::JSXElementName::ThisExpression(this_expression) => {
        walk_mut::walk_this_expression(self, this_expression);
      }
    }
  }

  // foo.js `export const bar = { a: 0 }`
  // main.js `import * as foo_exports from './foo.js';\n foo_exports.bar.a = 1;`
  // The `foo_exports.bar.a` ast is `StaticMemberExpression(StaticMemberExpression)`, The outer StaticMemberExpression span is `foo_exports.bar.a`, the `visit_expression(Expression::MemberExpression)` is called with `foo_exports.bar`, the span is inner StaticMemberExpression.
  fn visit_member_expression(&mut self, expr: &mut ast::MemberExpression<'ast>) {
    if let Some(new_expr) = self.try_rewrite_member_expr(expr) {
      match new_expr {
        match_member_expression!(Expression) => {
          *expr = new_expr.into_member_expression();
        }
        _ => {
          unreachable!("Always rewrite to MemberExpression for nested MemberExpression")
        }
      }
    } else {
      walk_mut::walk_member_expression(self, expr);
    }
  }

  fn visit_object_property(&mut self, prop: &mut ast::ObjectProperty<'ast>) {
    // Ensure `{ a }` would be rewritten to `{ a: a$1 }` instead of `{ a$1 }`
    if prop.shorthand {
      if let ast::Expression::Identifier(id_ref) = &mut prop.value {
        match self.generate_finalized_expr_for_reference(id_ref, false) {
          Some(expr) => {
            prop.value = expr;
            prop.shorthand = false;
          }
          None => {
            id_ref.reference_id.get_mut().take();
          }
        }
      }
    }

    walk_mut::walk_object_property(self, prop);
  }

  fn visit_object_pattern(&mut self, pat: &mut ast::ObjectPattern<'ast>) {
    self.rewrite_object_pat_shorthand(pat);

    walk_mut::walk_object_pattern(self, pat);
  }

  fn visit_assignment_target_property(
    &mut self,
    property: &mut ast::AssignmentTargetProperty<'ast>,
  ) {
    if let ast::AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(prop) = property {
      if let Some(target) =
        self.generate_finalized_simple_assignment_target_for_reference(&prop.binding)
      {
        *property = ast::AssignmentTargetProperty::AssignmentTargetPropertyProperty(
          ast::AssignmentTargetPropertyProperty {
            name: ast::PropertyKey::StaticIdentifier(
              self.snippet.id_name(&prop.binding.name, prop.span).into_in(self.alloc),
            ),
            binding: if let Some(init) = prop.init.take() {
              ast::AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(
                ast::AssignmentTargetWithDefault {
                  binding: ast::AssignmentTarget::from(target),
                  init,
                  span: Span::default(),
                  ..ast::AssignmentTargetWithDefault::dummy(self.alloc)
                }
                .into_in(self.alloc),
              )
            } else {
              ast::AssignmentTargetMaybeDefault::from(target)
            },
            span: Span::default(),
            computed: false,
            ..ast::AssignmentTargetPropertyProperty::dummy(self.alloc)
          }
          .into_in(self.alloc),
        );
      } else {
        prop.binding.reference_id.get_mut().take();
      }
    }

    walk_mut::walk_assignment_target_property(self, property);
  }

  fn visit_simple_assignment_target(&mut self, target: &mut SimpleAssignmentTarget<'ast>) {
    self.rewrite_simple_assignment_target(target);

    walk_mut::walk_simple_assignment_target(self, target);
  }

  fn visit_assignment_expression(&mut self, it: &mut ast::AssignmentExpression<'ast>) {
    if let AssignmentTarget::AssignmentTargetIdentifier(id) = &mut it.left {
      self.process_keep_name_for_expression(
        id.reference_id.get().map(KeepNameId::ReferenceId),
        &mut it.right,
      );
    }
    walk_mut::walk_assignment_expression(self, it);
  }

  fn visit_for_statement_init(&mut self, it: &mut ast::ForStatementInit<'ast>) {
    walk_mut::walk_for_statement_init(self, it);
    if self.state.contains(TraverseState::TopLevel)
      && self.needs_hosted_top_level_binding
      && let ast::ForStatementInit::VariableDeclaration(decl) = it
    {
      if let Some((expr, bindings)) =
        self.var_declaration_to_expr_seq_and_bindings(decl, self.state)
      {
        self.top_level_var_bindings.extend(bindings);
        *it = ast::ForStatementInit::from(expr);
      }
    }
  }

  fn visit_declaration(&mut self, it: &mut ast::Declaration<'ast>) {
    // keep_name transformation
    match it {
      ast::Declaration::VariableDeclaration(decl) => {
        for decl in &mut decl.declarations {
          let (BindingPattern::BindingIdentifier(id), Some(init)) = (&decl.id, decl.init.as_mut())
          else {
            continue;
          };
          self.process_keep_name_for_expression(id.symbol_id.get().map(KeepNameId::SymbolId), init);
        }
      }
      ast::Declaration::FunctionDeclaration(decl) => {
        let keep_name_id =
          decl.id.as_ref().and_then(|id| id.symbol_id.get().map(KeepNameId::SymbolId));
        if let Some((insert_position, original_name, new_name)) =
          self.process_fn(keep_name_id, keep_name_id)
        {
          self.keep_name_statement_to_insert.push((insert_position, original_name, new_name));
        }
      }
      ast::Declaration::ClassDeclaration(decl) => {
        // need to insert `keep_names` helper, because `get_transformed_class_decl`
        // will remove id in `class.id`
        if let Some(element) = self.keep_name_helper_for_class(
          decl.id.as_ref().and_then(|id| id.symbol_id.get().map(KeepNameId::SymbolId)),
          &decl.body,
        ) {
          decl.body.body.insert(0, element);
        }
        if let Some(new_decl) = self.get_transformed_class_decl(decl) {
          *it = new_decl;
          // Clear symbol_id on class expression's id to prevent visit_expression
          // from inserting a duplicate __name static block during walk
          if let ast::Declaration::VariableDeclaration(var_decl) = it {
            if let Some(declarator) = var_decl.declarations.first_mut() {
              if let Some(ast::Expression::ClassExpression(class_expr)) = &mut declarator.init {
                if let Some(id) = &mut class_expr.id {
                  id.symbol_id.get_mut().take();
                }
              }
            }
          }
        }
      }
      ast::Declaration::TSTypeAliasDeclaration(_)
      | ast::Declaration::TSInterfaceDeclaration(_)
      | ast::Declaration::TSEnumDeclaration(_)
      | ast::Declaration::TSModuleDeclaration(_)
      | ast::Declaration::TSImportEqualsDeclaration(_)
      | ast::Declaration::TSGlobalDeclaration(_) => unreachable!(),
    }

    walk_mut::walk_declaration(self, it);
  }
}

/// Check if an expression tree contains any optional member accesses (`?.`).
fn has_optional_member_access(expr: &Expression) -> bool {
  let mut cur = expr;
  loop {
    match cur {
      Expression::StaticMemberExpression(e) => {
        if e.optional {
          return true;
        }
        cur = &e.object;
      }
      Expression::ComputedMemberExpression(e) => {
        if e.optional {
          return true;
        }
        cur = &e.object;
      }
      _ => return false,
    }
  }
}