swc_ecma_transforms_base 48.0.0

rust port of babel and closure compiler.
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
use std::{borrow::Cow, collections::hash_map::Entry};

use analyer_and_collector::AnalyzerAndCollector;
use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_common::{Mark, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::stack_size::maybe_grow_default;
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith, VisitWith};

pub use self::eval::contains_eval;
#[cfg(feature = "concurrent-renamer")]
use self::renamer_concurrent::{Send, Sync};
#[cfg(not(feature = "concurrent-renamer"))]
use self::renamer_single::{Send, Sync};
use self::{analyzer::Analyzer, ops::Operator};
use crate::hygiene::Config;

mod analyer_and_collector;
mod analyzer;
mod eval;
mod ops;

pub trait Renamer: Send + Sync {
    /// See the [`RenamedVariable`] documentation, this type determines whether
    /// impls can be used with [`renamer`] or [`renamer_keep_contexts`] .
    type Target: RenamedVariable;

    /// Should reset `n` to 0 for each identifier?
    const RESET_N: bool;

    /// It should be true if you expect lots of collisions
    const MANGLE: bool;

    fn get_cached(&self) -> Option<Cow<'_, FxHashMap<Id, Self::Target>>> {
        None
    }

    fn store_cache(&mut self, _update: &FxHashMap<Id, Self::Target>) {}

    /// Should increment `n`.
    fn new_name_for(&self, orig: &Id, n: &mut usize) -> Atom;

    fn unresolved_symbols(&self) -> Vec<Atom> {
        Default::default()
    }

    /// Return true if the identifier should be preserved.
    #[inline]
    fn preserve_name(&self, _orig: &Id) -> bool {
        false
    }
}

pub type RenameMap = FxHashMap<Id, Atom>;

pub fn rename<V: RenamedVariable>(map: &FxHashMap<Id, V>) -> impl '_ + Pass + VisitMut {
    rename_with_config(map, Default::default())
}

pub fn rename_with_config<V: RenamedVariable>(
    map: &FxHashMap<Id, V>,
    config: Config,
) -> impl '_ + Pass + VisitMut {
    visit_mut_pass(Operator {
        rename: map,
        config,
        extra: Default::default(),
    })
}

pub fn renamer<R>(config: Config, renamer: R) -> impl Pass + VisitMut
where
    R: Renamer<Target = Atom>,
{
    visit_mut_pass(RenamePass {
        config,
        renamer,
        preserved: Default::default(),
        unresolved: Default::default(),
        previous_cache: Default::default(),
        total_map: None,
        eval_reserved_targets: Default::default(),
        marker: std::marker::PhantomData::<Atom>,
    })
}

/// Create correct (unique) syntax contexts. Use this if you need the syntax
/// contexts produces by this pass (unlike the default `hygiene` pass which
/// removes them anyway.)
pub fn renamer_keep_contexts<R>(config: Config, renamer: R) -> impl Pass + VisitMut
where
    R: Renamer<Target = Id>,
{
    visit_mut_pass(RenamePass {
        config,
        renamer,
        preserved: Default::default(),
        unresolved: Default::default(),
        previous_cache: Default::default(),
        total_map: None,
        eval_reserved_targets: Default::default(),
        marker: std::marker::PhantomData::<Id>,
    })
}

mod private {
    use swc_atoms::Atom;
    use swc_ecma_ast::Id;

    pub trait Sealed {}

    impl Sealed for Atom {}
    impl Sealed for Id {}
}

/// A trait that is used to represent a renamed variable. For
/// `renamer_keep_contexts`, the syntax contexts of the replacements should be
/// correct (unique), while for `hygiene` (which calls `renamer`), the resulting
/// syntax contexts are irrelevant. This type is used to handle both cases
/// without code duplication by using `HashMap<Id, impl RenamedVariable>`
/// everywhere:
/// - For `renamer`, `HashMap<Id, Atom>` is used (and `SyntaxContext::empty()`
///   isn't store unnecessarily). All replaced idents have the same
///   SyntaxContext #0.
/// - For `renamer_keep_contexts`, `HashMap<Id, Id>` is used. All replaced
///   idents have a unique SyntaxContext.
pub trait RenamedVariable:
    private::Sealed + Clone + Sized + std::marker::Send + std::marker::Sync + 'static
{
    /// Potentially create a new private variable, depending on whether the
    /// consumer cares about the syntax context after the renaming.
    fn new_private(sym: Atom) -> Self;
    fn to_id(&self) -> Id;
    fn atom(&self) -> &Atom;
    fn ctxt(&self) -> SyntaxContext;
}
impl RenamedVariable for Atom {
    fn new_private(sym: Atom) -> Self {
        sym
    }

    fn to_id(&self) -> Id {
        (self.clone(), Default::default())
    }

    fn atom(&self) -> &Atom {
        self
    }

    fn ctxt(&self) -> SyntaxContext {
        Default::default()
    }
}
impl RenamedVariable for Id {
    fn new_private(sym: Atom) -> Self {
        (sym, SyntaxContext::empty().apply_mark(Mark::new()))
    }

    fn to_id(&self) -> Id {
        self.clone()
    }

    fn atom(&self) -> &Atom {
        &self.0
    }

    fn ctxt(&self) -> SyntaxContext {
        self.1
    }
}

#[derive(Debug, Default)]
struct RenamePass<R, V>
where
    R: Renamer<Target = V>,
    V: RenamedVariable,
{
    config: Config,
    renamer: R,

    preserved: FxHashSet<Id>,
    unresolved: FxHashSet<Atom>,

    previous_cache: FxHashMap<Id, V>,

    /// Used to store cache.
    ///
    /// [Some] if the [`Renamer::get_cached`] returns [Some].
    total_map: Option<FxHashMap<Id, V>>,

    /// Mangled names assigned by the top-level map when `eval` is present.
    ///
    /// With `eval`, the top-level scope and each eval-free nested function are
    /// renamed in separate `get_map` calls, each with its own fresh
    /// `ReverseMap`. Without sharing the already-assigned names, a nested
    /// function could pick a Base54 name already used at the top level,
    /// producing a collision (#11294). These are fed as reserved symbols to
    /// the per-unit maps.
    eval_reserved_targets: FxHashSet<Atom>,

    marker: std::marker::PhantomData<V>,
}

impl<R, V> RenamePass<R, V>
where
    R: Renamer<Target = V>,
    V: RenamedVariable,
{
    fn get_map<N>(
        &mut self,
        node: &N,
        skip_one: bool,
        top_level: bool,
        has_eval: bool,
    ) -> FxHashMap<Id, V>
    where
        N: VisitWith<AnalyzerAndCollector>,
    {
        let (mut scope, unresolved) = analyer_and_collector::analyzer_and_collect_unresolved(
            node,
            has_eval,
            self.config.top_level_mark,
            skip_one,
            R::MANGLE,
        );

        scope.prepare_renaming();

        let mut unresolved = if !top_level {
            let mut set = self.unresolved.clone();
            set.extend(unresolved);
            Cow::Owned(set)
        } else {
            self.unresolved = unresolved;
            Cow::Borrowed(&self.unresolved)
        };

        if !self.preserved.is_empty() {
            unresolved
                .to_mut()
                .extend(self.preserved.iter().map(|v| v.0.clone()));
        }

        {
            let extra_unresolved = self.renamer.unresolved_symbols();

            if !extra_unresolved.is_empty() {
                unresolved.to_mut().extend(extra_unresolved);
            }
        }

        // When `eval` is present, per-unit maps must avoid the names already
        // assigned by the top-level map, since each map is built with an
        // independent `ReverseMap`. See #11294.
        if !top_level && !self.eval_reserved_targets.is_empty() {
            unresolved
                .to_mut()
                .extend(self.eval_reserved_targets.iter().cloned());
        }

        let mut map = FxHashMap::<Id, V>::default();

        if R::MANGLE {
            let cost = scope.rename_cost();
            map.reserve(cost);
            scope.rename_in_mangle_mode(
                &self.renamer,
                &mut map,
                &self.previous_cache,
                &Default::default(),
                &self.preserved,
                &unresolved,
                cost > 1024,
            );
        } else {
            scope.rename_in_normal_mode(
                &self.renamer,
                &mut map,
                &self.previous_cache,
                &mut Default::default(),
                &self.preserved,
                &unresolved,
            );
        }

        // Remember the names assigned at the top level so that per-unit maps
        // computed for eval-free nested functions can avoid them. Only needed
        // on the split-map path that `eval` forces. See #11294.
        if R::MANGLE && top_level && has_eval {
            self.eval_reserved_targets = map.values().map(|v| v.atom().clone()).collect();
        }

        if let Some(total_map) = &mut self.total_map {
            total_map.reserve(map.len());

            for (k, v) in &map {
                match total_map.entry(k.clone()) {
                    Entry::Occupied(old) => {
                        let old = old.get().to_id();
                        let new = v.to_id();
                        unreachable!(
                            "{} is already renamed to {}, but it's renamed as {}",
                            k.0, old.0, new.0
                        );
                    }
                    Entry::Vacant(e) => {
                        e.insert(v.clone());
                    }
                }
            }
        }

        // Drop identity mappings before apply. Operator already no-ops when
        // `sym == ident.sym`, so they only inflate the apply walk.
        //
        // Identities must still be inserted into `map` *during* analysis so
        // later scopes can skip via `to.get(id)`. Without that (e.g. hygiene
        // alone, no resolver), the same Id is reprocessed in every scope and
        // the reverse map blows up.
        //
        // Keep identities when `keep_class_names` is set: Operator uses that
        // flag to rewrite `class Foo` into `let Foo = class Foo`, and on the
        // old path those identity entries were what kept the map non-empty so
        // Operator ran. Minifier `keep_classnames` preserves class Ids instead
        // (they never enter the map), so this does not reintroduce apply work
        // for those fixtures.
        if !self.config.keep_class_names {
            map.retain(|id, v| v.atom() != &id.0);
        }

        map
    }

    fn load_cache(&mut self) {
        if let Some(cache) = self.renamer.get_cached() {
            self.previous_cache = cache.into_owned();
            self.total_map = Some(Default::default());
        }
    }
}

/// Mark a node as a unit of minification.
///
/// This is
macro_rules! unit {
    ($name:ident, $T:ty) => {
        /// Only called if `eval` exists
        fn $name(&mut self, n: &mut $T) {
            if !self.config.ignore_eval && contains_eval(n, true) {
                n.visit_mut_children_with(self);
            } else {
                let map = self.get_map(n, false, false, false);

                if !map.is_empty() {
                    n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
                }
            }
        }
    };
}

impl<R, V> VisitMut for RenamePass<R, V>
where
    R: Renamer<Target = V>,
    V: RenamedVariable,
{
    noop_visit_mut_type!();

    unit!(visit_mut_arrow_expr, ArrowExpr);

    unit!(visit_mut_setter_prop, SetterProp);

    unit!(visit_mut_getter_prop, GetterProp);

    unit!(visit_mut_constructor, Constructor);

    unit!(visit_mut_fn_expr, FnExpr);

    unit!(visit_mut_method_prop, MethodProp);

    unit!(visit_mut_class_method, ClassMethod);

    unit!(visit_mut_private_method, PrivateMethod);

    fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) {
        if !self.config.ignore_eval && contains_eval(n, true) {
            n.visit_mut_children_with(self);
        } else {
            let id = n.ident.to_id();
            let inserted = self.preserved.insert(id.clone());
            let map = self.get_map(n, true, false, false);

            if inserted {
                self.preserved.remove(&id);
            }

            if !map.is_empty() {
                n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
            }
        }
    }

    fn visit_mut_class_decl(&mut self, n: &mut ClassDecl) {
        if !self.config.ignore_eval && contains_eval(n, true) {
            n.visit_mut_children_with(self);
        } else {
            let id = n.ident.to_id();
            let inserted = self.preserved.insert(id.clone());
            let map = self.get_map(n, true, false, false);

            if inserted {
                self.preserved.remove(&id);
            }

            if !map.is_empty() {
                n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
            }
        }
    }

    fn visit_mut_default_decl(&mut self, n: &mut DefaultDecl) {
        match n {
            DefaultDecl::Class(n) => {
                n.visit_mut_children_with(self);
            }
            DefaultDecl::Fn(n) => {
                n.visit_mut_children_with(self);
            }
            DefaultDecl::TsInterfaceDecl(n) => {
                n.visit_mut_children_with(self);
            }
            #[cfg(swc_ast_unknown)]
            _ => (),
        }
    }

    fn visit_mut_expr(&mut self, n: &mut Expr) {
        maybe_grow_default(|| n.visit_mut_children_with(self));
    }

    fn visit_mut_module(&mut self, m: &mut Module) {
        self.load_cache();

        let has_eval = !self.config.ignore_eval && contains_eval(m, true);

        let map = self.get_map(m, false, true, has_eval);

        // If we have eval, we cannot rename a whole program at once.
        //
        // Still, we can, and should rename some identifiers, if the containing scope
        // (function-like nodes) does not have eval. This `eval` check includes
        // `eval` in children.
        //
        // We calculate the top level map first, rename children, and then rename the
        // top level.
        //
        //
        // Order:
        //
        // 1. Top level map calculation
        // 2. Per-unit map calculation
        // 3. Per-unit renaming
        // 4. Top level renaming
        //
        // This is because the top level map may contain a mapping which conflicts
        // with a map from one of the children.
        //
        // See https://github.com/swc-project/swc/pull/7615
        if has_eval {
            m.visit_mut_children_with(self);
        }

        if !map.is_empty() {
            m.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
        }

        if let Some(total_map) = &self.total_map {
            self.renamer.store_cache(total_map);
        }
    }

    fn visit_mut_script(&mut self, m: &mut Script) {
        self.load_cache();

        let has_eval = !self.config.ignore_eval && contains_eval(m, true);

        let map = self.get_map(m, false, true, has_eval);

        if has_eval {
            m.visit_mut_children_with(self);
        }

        if !map.is_empty() {
            m.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
        }

        if let Some(total_map) = &self.total_map {
            self.renamer.store_cache(total_map);
        }
    }
}

#[cfg(feature = "concurrent-renamer")]
mod renamer_concurrent {
    pub use std::marker::{Send, Sync};
}

#[cfg(not(feature = "concurrent-renamer"))]
mod renamer_single {
    /// Dummy trait because swc_common is in single thread mode.
    pub trait Send {}
    /// Dummy trait because swc_common is in single thread mode.
    pub trait Sync {}

    impl<T> Send for T where T: ?Sized {}
    impl<T> Sync for T where T: ?Sized {}
}