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
use std::collections::VecDeque;
use rustc_hash::FxHashMap;
use swc_atoms::{Atom, Wtf8Atom};
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use crate::option::CompressOptions;
/// Records all import specifiers for a single source module.
#[derive(Default)]
struct ImportRecord {
/// Default imports: stores local Id in order
/// e.g., `import A, { default as B, "default" as C } from 'm.js'`
/// stores A's Id, B's Id, C's Id
defaults: VecDeque<Ident>,
/// Namespace imports: stores local Id in order
/// e.g., `import * as X from 'm.js'` stores X's Id
namespaces: VecDeque<Ident>,
/// Named imports: stores (import_name, local_id) in order
/// e.g., `import { foo } from 'm.js'` stores ("foo", foo's Id)
/// e.g., `import { foo as bar } from 'm.js'` stores ("foo", bar's Id)
/// Note: import_name "default" cases are classified into defaults
named: VecDeque<(Atom, Ident)>,
}
impl ImportRecord {
fn is_empty(&self) -> bool {
self.defaults.is_empty() && self.namespaces.is_empty() && self.named.is_empty()
}
}
pub fn postcompress_optimizer(program: &mut Program, options: &CompressOptions) {
if !options.merge_imports {
return;
}
let Some(module) = program.as_mut_module() else {
return;
};
// First pass: collect all imports and exports
let mut import_map = FxHashMap::<Wtf8Atom, ImportRecord>::default();
// Re-exports: only named re-exports can be merged
let mut reexport_map =
FxHashMap::<Wtf8Atom, VecDeque<(ModuleExportName, Option<ModuleExportName>)>>::default();
// Local exports without source: `export { foo, bar }`
let mut local_export_list = Vec::default();
for item in &module.body {
match item {
ModuleItem::ModuleDecl(ModuleDecl::Import(import_decl)) => {
// Skip conditions
if import_decl.type_only {
continue;
}
if import_decl.with.is_some() {
continue;
}
if import_decl.phase != ImportPhase::Evaluation {
continue;
}
let src = import_decl.src.value.clone();
let record = import_map.entry(src).or_default();
for spec in &import_decl.specifiers {
match spec {
ImportSpecifier::Default(d) => {
record.defaults.push_back(d.local.clone());
}
ImportSpecifier::Namespace(ns) => {
record.namespaces.push_back(ns.local.clone());
}
ImportSpecifier::Named(n) => {
debug_assert!(
!n.is_type_only,
"type-only imports/exports should be stripped earlier"
);
if n.is_type_only {
continue;
}
let remote: Atom = n
.imported
.as_ref()
.map(|i| match i {
ModuleExportName::Ident(id) => id.sym.clone(),
ModuleExportName::Str(s) => {
Atom::new(s.value.to_string_lossy())
}
#[cfg(swc_ast_unknown)]
_ => panic!("unable to access unknown nodes"),
})
.unwrap_or_else(|| n.local.sym.clone());
let local_id = n.local.clone();
// If remote is "default", classify as default import
if &*remote == "default" {
record.defaults.push_back(local_id);
} else {
record.named.push_back((remote, local_id));
}
}
#[cfg(swc_ast_unknown)]
_ => panic!("unable to access unknown nodes"),
}
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(export_named)) => {
if export_named.type_only {
continue;
}
if export_named.with.is_some() {
continue;
}
if let Some(ref src) = export_named.src {
// Re-export: `export { foo } from 'm.js'`
// Only collect named specifiers; namespace/default can't be merged
let has_non_named = export_named.specifiers.iter().any(|s| {
matches!(
s,
ExportSpecifier::Namespace(_) | ExportSpecifier::Default(_)
)
});
if has_non_named {
// Keep as-is, don't collect
continue;
}
let reexports = reexport_map.entry(src.value.clone()).or_default();
for spec in &export_named.specifiers {
if let ExportSpecifier::Named(n) = spec {
debug_assert!(
!n.is_type_only,
"type-only imports/exports should be stripped earlier"
);
if n.is_type_only {
continue;
}
let orig = n.orig.clone();
let exported = n.exported.clone();
reexports.push_back((orig, exported));
}
}
} else {
// Local export: `export { foo, bar }`
for spec in &export_named.specifiers {
if let ExportSpecifier::Named(..) = spec {
local_export_list.push(spec.clone());
}
}
}
}
_ => {}
}
}
if import_map.is_empty() && reexport_map.is_empty() && local_export_list.is_empty() {
return;
}
let mut run_once = false;
module.body.retain_mut(|item| {
match item {
ModuleItem::ModuleDecl(ModuleDecl::Import(import_decl)) => {
// Don't process these, keep as-is
if import_decl.type_only {
return true;
}
if import_decl.with.is_some() {
return true;
}
if import_decl.phase != ImportPhase::Evaluation {
return true;
}
let src = &import_decl.src.value;
let Some(record) = import_map.get_mut(src) else {
return false; // No record, remove
};
let has_namespace = import_decl
.specifiers
.iter()
.any(|s| matches!(s, ImportSpecifier::Namespace(_)));
let mut new_specs: Vec<ImportSpecifier> = Vec::new();
if has_namespace || (record.named.is_empty() && !record.namespaces.is_empty()) {
// Has namespace: take one default + one namespace
if let Some(local) = record.defaults.pop_front() {
new_specs.push(ImportSpecifier::Default(ImportDefaultSpecifier {
span: DUMMY_SP,
local,
}));
}
if let Some(local) = record.namespaces.pop_front() {
new_specs.push(ImportSpecifier::Namespace(ImportStarAsSpecifier {
span: DUMMY_SP,
local,
}));
}
} else {
// No namespace: take one default + remaining defaults as named + all named
if let Some(local) = record.defaults.pop_front() {
new_specs.push(ImportSpecifier::Default(ImportDefaultSpecifier {
span: DUMMY_SP,
local,
}));
}
// Keep ns_count defaults for later namespace imports
let ns_count = record.namespaces.len();
let drain_count = record.defaults.len().saturating_sub(ns_count);
// Remaining defaults become { default as X }
for local in record.defaults.drain(..drain_count) {
new_specs.push(ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local,
imported: Some(ModuleExportName::Ident(Ident::new_no_ctxt(
"default".into(),
DUMMY_SP,
))),
is_type_only: false,
}));
}
// All named imports
for (remote, local) in record.named.drain(..) {
let imported = if remote == local.sym {
None
} else {
Some(ModuleExportName::Ident(Ident::new_no_ctxt(
remote, DUMMY_SP,
)))
};
new_specs.push(ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP,
local,
imported,
is_type_only: false,
}));
}
}
if record.is_empty() {
import_map.remove(src);
}
import_decl.specifiers = new_specs;
true
}
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(export_named)) => {
if export_named.type_only {
return true;
}
if export_named.with.is_some() {
return true;
}
if let Some(ref src) = export_named.src {
// Re-export: `export { foo } from 'm.js'`
// Statements with namespace/default specifiers are kept as-is
let has_non_named = export_named.specifiers.iter().any(|s| {
matches!(
s,
ExportSpecifier::Namespace(_) | ExportSpecifier::Default(_)
)
});
if has_non_named {
return true;
}
let Some(reexports) = reexport_map.get_mut(&src.value) else {
return false;
};
let mut new_specs: Vec<ExportSpecifier> = Vec::new();
// Take named exports
for (orig, exported) in reexports.drain(..) {
new_specs.push(ExportSpecifier::Named(ExportNamedSpecifier {
span: DUMMY_SP,
orig,
exported,
is_type_only: false,
}));
}
if reexports.is_empty() {
reexport_map.remove(&src.value);
}
export_named.specifiers = new_specs;
true
} else {
if run_once {
return false;
}
export_named.specifiers = local_export_list.take();
run_once = true;
true
}
}
_ => true,
}
});
}