rolldown 1.2.12

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
use oxc_str::CompactStr;

use crate::{
  stages::{
    generate_stage::{FileInlineNames, order_wrap_state::OrderWrapState},
    link_stage::LinkStageOutput,
  },
  utils::{
    external_import_interop::{
      ChunkAssignments, chunk_external_interop_modes, chunk_has_node_esm_reader,
    },
    renamer::{NestedScopeRenamer, Renamer},
  },
};
use arcstr::ArcStr;
use rolldown_common::{
  Chunk, ChunkIdx, ChunkKind, GetLocalDb, ModuleIdx, OutputFormat, SymbolRef, WrapKind,
};
use rolldown_utils::{concat_string, ecmascript::legitimize_identifier_name};
use rustc_hash::{FxHashMap, FxHashSet};

/// What `experimentalInlineCommonChunks` adds to one file's naming. The modules and synthetic
/// statements of every record the file carries are named in the file's namespace, because their
/// factories are printed into it; the file also declares one bridge per record it reads, one per
/// record each carried factory reads, and the factories' `exports` parameter. See
/// internal-docs/inline-common-chunks/implementation.md ("Deconflicting").
#[derive(Debug)]
pub struct InlineNamingInput {
  /// The file's own modules and every carried record's, in ascending execution order.
  pub modules: Vec<ModuleIdx>,
  /// The file's chunk and every carried record.
  pub chunks: Vec<ChunkIdx>,
  /// Records the file reads directly, with the chunk name the bridge is named after.
  pub file_bridges: Vec<(ChunkIdx, ArcStr)>,
  /// Carried records, each with the records its factory reads.
  pub factories: Vec<(ChunkIdx, Vec<(ChunkIdx, ArcStr)>)>,
}

/// `inline` is `Some` for a file that reads inline common chunk records, see [`InlineNamingInput`].
#[tracing::instrument(level = "trace", skip_all)]
#[expect(clippy::too_many_arguments)]
#[expect(clippy::too_many_lines)]
pub fn deconflict_chunk_symbols(
  chunk_idx: ChunkIdx,
  chunk: &mut Chunk,
  link_output: &LinkStageOutput,
  order_wrap_state: &OrderWrapState,
  order_live_symbols: &FxHashSet<SymbolRef>,
  format: OutputFormat,
  index_chunk_id_to_name: &FxHashMap<ChunkIdx, ArcStr>,
  chunk_assignments: ChunkAssignments<'_>,
  inline: Option<&InlineNamingInput>,
) -> Option<FileInlineNames> {
  // The modules and chunks whose root-scope declarations land in this file.
  let own_chunk = [chunk_idx];
  let (modules, chunks): (&[ModuleIdx], &[ChunkIdx]) = match inline {
    Some(inline) => (&inline.modules, &inline.chunks),
    None => (&chunk.modules, &own_chunk),
  };
  let mut renamer = Renamer::new(chunk.entry_module_idx(), &link_output.symbol_db, format);
  // Reserve global scope symbols (unresolved references) to prevent generating conflicting names.
  // These are identifiers referenced but not defined in the module's scope (e.g., `console`, `window`).
  modules
    .iter()
    .copied()
    .filter_map(|idx| {
      Some(
        link_output.symbol_db[idx]
          .as_ref()?
          .ast_scopes
          .scoping()
          .root_unresolved_references()
          .keys(),
      )
    })
    .flatten()
    .for_each(|name| {
      renamer.reserve(CompactStr::new(name));
    });

  if matches!(format, OutputFormat::Iife | OutputFormat::Umd | OutputFormat::Cjs) {
    // deconflict iife introduce symbols by external
    // Also AMD, but we don't support them yet.
    chunk
      .direct_imports_from_external_modules
      .iter()
      .map(|(idx, _)| *idx)
      .chain(chunk.entry_level_external_module_idx.iter().copied())
      .filter_map(|idx| link_output.module_table[idx].as_external())
      .for_each(|external_module| {
        renamer.add_symbol_in_root_scope(external_module.namespace_ref, true);
      });

    chunk
      .import_symbol_from_external_modules
      .iter()
      .filter_map(|idx| link_output.module_table[*idx].as_external())
      .for_each(|external_module| {
        renamer.add_symbol_in_root_scope(external_module.namespace_ref, true);
      });
  }

  match chunk.kind {
    ChunkKind::EntryPoint { module, .. } => {
      let meta = &link_output.metas[module];
      meta.referenced_symbols_by_entry_point_chunk.iter().for_each(
        |(symbol_ref, came_from_cjs)| {
          if !came_from_cjs {
            renamer.add_symbol_in_root_scope(*symbol_ref, true);
          }
        },
      );
    }
    ChunkKind::Common => {}
  }
  if matches!(format, OutputFormat::Esm) {
    chunk.direct_imports_from_external_modules.iter().for_each(|(module, _)| {
      let db = link_output.symbol_db.local_db(*module);
      db.classic_data.iter_enumerated().for_each(|(symbol, _)| {
        let symbol_ref = (*module, symbol).into();
        if link_output.used_external_symbols.contains(&symbol_ref) {
          renamer.add_symbol_in_root_scope(symbol_ref, true);
        }
      });
    });
  }

  let chunk_scope_captured_names = collect_chunk_scope_captured_names(
    chunks,
    modules,
    chunk,
    link_output,
    order_wrap_state,
    order_live_symbols,
    format,
    &renamer,
  );

  // The renamer relies on `modules` being in ascending exec_order so that
  // `.rev()` yields entry-first / descending exec_order — the same priority as
  // `deconflict_order_key`. Enforce that invariant in debug builds (was only a
  // prose + pinned-SHA comment before).
  debug_assert!(
    modules
      .iter()
      .filter_map(|idx| link_output.module_table[*idx].as_normal().map(|m| m.exec_order))
      .is_sorted(),
    "modules must be in ascending exec_order for deconfliction"
  );

  modules
    .iter()
    .copied()
    // Starts with entry module
    .rev()
    .filter_map(|id| link_output.module_table[id].as_normal())
    .for_each(|module| {
      if let Some(hmr_hot_ref) = module.hmr_hot_ref {
        renamer.add_symbol_in_root_scope(hmr_hot_ref, true);
      }
      // Skip deconflicting top-level symbols for CJS modules since they are wrapped in a function scope
      // and their symbols don't pollute the chunk's root scope.
      let meta = &link_output.metas[module.idx];
      let is_cjs_wrapped_module = matches!(meta.wrap_kind(), WrapKind::Cjs);

      link_output.stmt_infos[module.idx]
        .iter_enumerated()
        // A runtime statement tree-shaking excluded but order wrapping force-includes is rendered
        // and symbol-assigned, so it must reach the renamer too. Mirror the overlay-aware inclusion
        // test the other two consumers already use (`compute_cross_chunk_links` and the module
        // finalizer's `remove_unused_top_level_stmt`); without it a user top-level binding named
        // `__esmMin`/`__esm` co-hosted with the runtime collides with the forced helper declaration.
        .filter(|(idx, stmt_info)| {
          (meta.stmt_info_included.has_bit(*idx)
            || order_wrap_state.forces_runtime_stmt(&link_output.runtime, module.idx, stmt_info))
            && !stmt_info.import_records.iter().any(|rec_idx| {
              order_wrap_state.has_order_cjs_carrier(
                crate::stages::generate_stage::order_wrap_state::OrderCjsCarrierKey {
                  importer: module.idx,
                  record: *rec_idx,
                },
              )
            })
        })
        .for_each(|(_, stmt_info)| {
          for declared_symbol in stmt_info.declared_symbols.iter().filter(|item| item.is_normal()) {
            let symbol_ref = declared_symbol.inner();
            let canonical_ref = link_output.symbol_db.canonical_ref_for(symbol_ref);
            // Import statement declared some symbols that come from other module, those symbol should be skipped
            if canonical_ref.owner != module.idx {
              continue;
            }
            // For CJS wrapped modules, only facade symbols need deconflicting.
            // Facade symbols are synthetic symbols created during linking (e.g., `require_foo` wrapper,
            // namespace objects) that don't exist in the original AST. These are rendered at the chunk's
            // root scope and must be deconflicted. Non-facade (real AST) symbols in CJS modules are
            // wrapped inside the `__commonJS` closure and don't pollute the chunk's root scope.
            let needs_deconflict = if is_cjs_wrapped_module {
              // Note:
              // 1. Some facade symbols may originate from external modules (e.g., namespace objects for external imports).
              // 2. Since we merge external module symbols, external symbol declared in a cjs module also needs to be deconflicted
              let is_facade_or_external = link_output.symbol_db.is_facade_symbol(canonical_ref)
                || stmt_info.import_records.iter().any(|import_rec_idx| {
                  module.import_records[*import_rec_idx]
                    .resolved_module
                    .is_some_and(|module_idx| link_output.module_table[module_idx].is_external())
                });
              // Deconflict bindings that would shadow a name captured by the enclosing
              // `__commonJS` closure (issues #9055, #9375).
              let shadows_chunk_scope_name =
                chunk_scope_captured_names.contains(canonical_ref.name(&link_output.symbol_db));
              is_facade_or_external || shadows_chunk_scope_name
            } else {
              true
            };
            renamer.add_symbol_in_root_scope(symbol_ref, needs_deconflict);
          }
        });
    });

  for synthetic in
    chunks.iter().flat_map(|idx| order_wrap_state.synthetic_statements_for_chunk(*idx))
  {
    for declared_symbol in synthetic.declared_symbols.iter().filter(|item| item.is_normal()) {
      renamer.add_symbol_in_root_scope(declared_symbol.inner(), true);
    }
  }

  // Though, those symbols in `imports_from_other_chunks` doesn't belong to this chunk, but in the final output, they still behave
  // like declared in this chunk. This is because we need to generate import statements in this chunk to import symbols from other
  // statements. Those `import {...} from './other-chunk.js'` will declared these outside symbols in this chunk, so symbols that
  // point to them can be resolved in runtime.
  // So we add them in the deconflict process to generate conflict-less names in this chunk.
  chunk.imports_from_other_chunks.iter().flat_map(|(_, items)| items.iter()).for_each(|item| {
    renamer.add_symbol_in_root_scope(item.import_ref, true);
  });

  chunk.require_binding_names_for_other_chunks = chunk
    .imports_from_other_chunks
    .iter()
    .map(|(id, _)| {
      (
        *id,
        renamer
          .create_conflictless_name(&legitimize_identifier_name(&format!(
            "require_{}",
            index_chunk_id_to_name[id]
          )))
          .to_string(),
      )
    })
    .collect();

  // Detect mixed-mode external imports: both ESM (node-mode) and non-ESM importers
  // needing interop on the same external. Create a separate binding name for node-mode.
  if matches!(format, OutputFormat::Iife | OutputFormat::Umd | OutputFormat::Cjs) {
    let mut node_mode_names = FxHashMap::default();
    // Externals the chunk only *references* (their importing module lives in another chunk or was
    // tree-shaken away) carry no `named_imports`, but the inclusion pass still recorded how they
    // are observed — so they can be mixed-mode too. See `chunk_recorded_external_interop`.
    //
    // Only the cjs renderer emits bindings for that indirect list; `render_chunk_external_imports`
    // walks the direct list alone, so a name planned from an indirect external under iife/umd would
    // have no `let` to bind it. Keep the two in step rather than plan a name nothing declares.
    let indirect_externals = matches!(format, OutputFormat::Cjs)
      .then(|| chunk.import_symbol_from_external_modules.iter())
      .into_iter()
      .flatten();
    let externals = chunk
      .direct_imports_from_external_modules
      .iter()
      .map(|(ext_idx, named_imports)| (*ext_idx, Some(named_imports.as_slice())))
      .chain(indirect_externals.map(|ext_idx| (*ext_idx, None)));
    for (ext_idx, named_imports) in externals {
      let ext =
        link_output.module_table[ext_idx].as_external().expect("Should be external module here");
      let Some(modes) = chunk_external_interop_modes(
        link_output,
        chunk_assignments,
        chunk_idx,
        ext.namespace_ref,
        named_imports,
      ) else {
        continue;
      };
      // Both modes are needed *and* some module here will actually read the node one. Without the
      // second test the binding is dead on arrival and only its `__toESM(mod, 1)` call survives DCE.
      if modes.node_esm
        && modes.non_node_esm
        && chunk_has_node_esm_reader(
          link_output,
          chunk_assignments,
          chunk_idx,
          ext.namespace_ref,
          named_imports,
        )
      {
        let canonical_ref = link_output.symbol_db.canonical_ref_for(ext.namespace_ref);
        let original_name = canonical_ref.name(&link_output.symbol_db);
        let node_name = renamer.create_conflictless_name(original_name);
        node_mode_names.insert(canonical_ref, node_name);
      }
    }
    chunk.node_mode_external_ns_names = node_mode_names;
  }

  let inline_names = inline.map(|inline| name_inline_bindings(&mut renamer, inline, link_output));

  rename_shadowing_symbols_in_nested_scopes(chunk_idx, modules, link_output, format, &mut renamer);

  chunk.canonical_names = renamer.into_canonical_names();
  inline_names
}

/// A bridge is read wherever a record symbol was referenced, including inside nested scopes, so
/// its name must be free in every nested scope of the file's modules, like an import binding.
/// The factories' `exports` parameter avoids everything the file declares and reads.
fn name_inline_bindings(
  renamer: &mut Renamer<'_>,
  inline: &InlineNamingInput,
  link_output: &LinkStageOutput,
) -> FileInlineNames {
  // A CommonJS-wrapped module's root scope is emitted inside its `__commonJS` closure, where a
  // local named like a bridge would shadow it.
  let cjs_wrapped = inline
    .modules
    .iter()
    .copied()
    .filter(|module_idx| matches!(link_output.metas[*module_idx].wrap_kind(), WrapKind::Cjs))
    .collect::<Vec<_>>();
  let bridges = inline
    .file_bridges
    .iter()
    .map(|(record, name)| (*record, bridge_name(renamer, name, &inline.modules, &cjs_wrapped)))
    .collect();
  let factory_bridges = inline
    .factories
    .iter()
    .map(|(record, reads)| {
      let names = reads
        .iter()
        .map(|(other, name)| (*other, bridge_name(renamer, name, &inline.modules, &cjs_wrapped)))
        .collect();
      (*record, names)
    })
    .collect();
  let exports_param = if inline.factories.is_empty() {
    CompactStr::new_const("exports")
  } else {
    renamer.create_conflictless_name("exports")
  };
  FileInlineNames { exports_param, bridges, factory_bridges }
}

fn bridge_name(
  renamer: &mut Renamer<'_>,
  chunk_name: &str,
  modules: &[ModuleIdx],
  cjs_wrapped: &[ModuleIdx],
) -> CompactStr {
  let hint_source = concat_string!("share_", chunk_name);
  let hint = legitimize_identifier_name(&hint_source);
  renamer.create_conflictless_name_for_modules(&hint, modules, cjs_wrapped)
}

/// Collect the canonical names of things that are emitted at the chunk's root scope and thus
/// captured by every CJS-wrapped module's `__commonJS((exports, module) => { ... })` closure.
/// A real-AST root-scope binding inside the closure whose name matches one of these would
/// shadow the captured value at runtime (issues #9055, #9375, #9630). We track only
/// rolldown-emitted names — iife/umd factory params and `require_xxx` wrapper facades — and
/// intentionally exclude the names of import bindings that get rewritten away at codegen time.
/// We use the symbols' *original* names here: wrapper symbols haven't been renamed yet at this
/// point, and if any of them ends up renamed in the deconfliction loop, the conflict that
/// triggered the rename would have been the user-source local — which is exactly the case we
/// want to catch.
#[expect(clippy::too_many_arguments)]
fn collect_chunk_scope_captured_names(
  chunks: &[ChunkIdx],
  modules: &[ModuleIdx],
  chunk: &Chunk,
  link_output: &LinkStageOutput,
  order_wrap_state: &OrderWrapState,
  order_live_symbols: &FxHashSet<SymbolRef>,
  format: OutputFormat,
  renamer: &Renamer<'_>,
) -> FxHashSet<CompactStr> {
  let mut captured: FxHashSet<CompactStr> = FxHashSet::default();
  for synthetic in
    chunks.iter().flat_map(|idx| order_wrap_state.synthetic_statements_for_chunk(*idx))
  {
    for declared in &synthetic.declared_symbols {
      captured.insert(CompactStr::new(declared.inner().name(&link_output.symbol_db)));
    }
  }
  if matches!(format, OutputFormat::Iife | OutputFormat::Umd) {
    // Mirror the set rendered as factory params by `render_chunk_external_imports` +
    // `render_factory_parameters`.
    for (external_idx, _) in &chunk.direct_imports_from_external_modules {
      let Some(external) = link_output.module_table[*external_idx].as_external() else {
        continue;
      };
      if let Some(name) = renamer.get_canonical_name(external.namespace_ref) {
        captured.insert(name.clone());
      }
    }
  }
  // CJS wrapper facades (e.g. `require_foo`) are rendered at chunk scope and captured by every
  // CJS-wrapped module's closure in this chunk.
  for module_idx in modules.iter().copied() {
    if let Some(wrapper_ref) = link_output.metas[module_idx].wrapper_ref {
      let canonical_ref = link_output.symbol_db.canonical_ref_for(wrapper_ref);
      captured.insert(CompactStr::new(canonical_ref.name(&link_output.symbol_db)));
    }
  }
  if matches!(format, OutputFormat::Esm) {
    // A CJS wrapper whose module lives in *another* chunk is hoisted here as a real root-scope
    // import binding (`import { ... as require_foo } from "./other.js"`) and is likewise captured
    // by every CJS-wrapped closure in this chunk. The in-chunk loop above can't see it because its
    // owner module isn't in `chunk.modules`, so we recover it from the cross-chunk import list.
    // Without this, an author-local of the same name inside a CJS closure shadows the imported
    // wrapper, emitting the self-referential `var require_foo = require_foo()` (issue #9630).
    for item in chunk.imports_from_other_chunks.values().flatten() {
      let canonical_ref = link_output.symbol_db.canonical_ref_for(item.import_ref);
      let is_cjs_wrapper =
        link_output.metas[canonical_ref.owner].wrapper_ref.is_some_and(|wrapper_ref| {
          link_output.symbol_db.canonical_ref_for(wrapper_ref) == canonical_ref
        });
      if is_cjs_wrapper || order_live_symbols.contains(&canonical_ref) {
        captured.insert(CompactStr::new(canonical_ref.name(&link_output.symbol_db)));
      }
    }
  }
  captured
}

/// Rename nested scope symbols that would shadow top-level symbols.
///
/// Since we avoid conflicting names during root scope renaming, most nested scope
/// symbols can keep their original names. However, we still need to handle cases
/// where a nested binding would capture a reference to a top-level symbol.
fn rename_shadowing_symbols_in_nested_scopes<'a>(
  chunk_idx: ChunkIdx,
  modules: &[ModuleIdx],
  link_output: &'a LinkStageOutput,
  output_format: OutputFormat,
  renamer: &mut Renamer<'a>,
) {
  // Same as above, starts with entry module to give entry module symbols naming priority.
  for module_idx in modules.iter().copied().rev() {
    let Some(module) = link_output.module_table[module_idx].as_normal() else {
      continue;
    };
    let Some(db) = &link_output.symbol_db[module_idx] else {
      continue;
    };

    let mut ctx = NestedScopeRenamer {
      module_idx,
      module,
      db,
      scoping: db.ast_scopes.scoping(),
      link_output,
      renamer,
    };

    ctx.rename_bindings_shadowing_star_imports();
    ctx.rename_bindings_shadowing_named_imports();
    ctx.rename_bindings_shadowing_wrapper_params(matches!(
      output_format,
      OutputFormat::Iife | OutputFormat::Umd | OutputFormat::Cjs
    ));

    ctx.rename_bindings_shadowing_cjs_ambient_names(output_format);
    ctx.rename_cjs_locals_shadowing_referenced_chunk_bindings(output_format, chunk_idx);
  }
}