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
#![allow(unused_imports)]

use std::borrow::Cow;

use rustc_hash::FxHashSet;
use swc_atoms::JsWord;
use swc_common::collections::AHashMap;
use swc_ecma_ast::*;
use swc_ecma_utils::stack_size::maybe_grow_default;
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith, VisitWith};

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

mod analyzer;
mod collector;
mod eval;
mod ops;

pub trait Renamer: Send + Sync {
    /// 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 preserved_ids_for_module(&mut self, _: &Module) -> FxHashSet<Id> {
        Default::default()
    }

    fn preserved_ids_for_script(&mut self, _: &Script) -> FxHashSet<Id> {
        Default::default()
    }

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

pub fn rename(map: &AHashMap<Id, JsWord>) -> impl '_ + Fold + VisitMut {
    rename_with_config(map, Default::default())
}

pub fn rename_with_config(map: &AHashMap<Id, JsWord>, config: Config) -> impl '_ + Fold + VisitMut {
    as_folder(Operator {
        rename: map,
        config,
        extra: Default::default(),
    })
}

pub fn remap(map: &AHashMap<Id, Id>, config: Config) -> impl '_ + Fold + VisitMut {
    as_folder(Operator {
        rename: map,
        config,
        extra: Default::default(),
    })
}

pub fn renamer<R>(config: Config, renamer: R) -> impl Fold + VisitMut
where
    R: Renamer,
{
    as_folder(RenamePass {
        config,
        renamer,
        preserved: Default::default(),
        unresolved: Default::default(),
    })
}

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

    preserved: FxHashSet<Id>,
    unresolved: FxHashSet<JsWord>,
}

impl<R> RenamePass<R>
where
    R: Renamer,
{
    fn get_unresolved<N>(&self, n: &N, has_eval: bool) -> FxHashSet<JsWord>
    where
        N: VisitWith<IdCollector> + VisitWith<CustomBindingCollector<Id>>,
    {
        let usages = {
            let mut v = IdCollector {
                ids: Default::default(),
            };
            n.visit_with(&mut v);
            v.ids
        };
        let (decls, preserved) = collect_decls(
            n,
            if has_eval {
                Some(self.config.top_level_mark)
            } else {
                None
            },
        );
        usages
            .into_iter()
            .filter(|used_id| !decls.contains(used_id))
            .map(|v| v.0)
            .chain(preserved.into_iter().map(|v| v.0))
            .collect()
    }

    fn get_map<N>(
        &self,
        node: &N,
        skip_one: bool,
        top_level: bool,
        has_eval: bool,
    ) -> AHashMap<Id, JsWord>
    where
        N: VisitWith<IdCollector> + VisitWith<CustomBindingCollector<Id>>,
        N: VisitWith<Analyzer>,
    {
        let mut scope = {
            let mut v = Analyzer {
                has_eval,
                top_level_mark: self.config.top_level_mark,

                ..Default::default()
            };
            if skip_one {
                node.visit_children_with(&mut v);
            } else {
                node.visit_with(&mut v);
            }
            v.scope
        };
        scope.prepare_renaming();

        let mut map = RenameMap::default();

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

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

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

        map.into_iter()
            .map(|((s, ctxt), v)| ((s.into_inner(), ctxt), v))
            .collect()
    }
}

/// 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);

                n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
            }
        }
    };
    ($name:ident, $T:ty, true) => {
        /// 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, true, false, false);

                n.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
            }
        }
    };
}

impl<R> VisitMut for RenamePass<R>
where
    R: Renamer,
{
    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);

    unit!(visit_mut_fn_decl, FnDecl, true);

    unit!(visit_mut_class_decl, ClassDecl, true);

    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.preserved = self.renamer.preserved_ids_for_module(m);

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

        self.unresolved = self.get_unresolved(m, has_eval);

        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);
        }

        m.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
    }

    fn visit_mut_script(&mut self, m: &mut Script) {
        self.preserved = self.renamer.preserved_ids_for_script(m);

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

        self.unresolved = self.get_unresolved(m, has_eval);

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

        if has_eval {
            m.visit_mut_children_with(self);
        }

        m.visit_mut_with(&mut rename_with_config(&map, self.config.clone()));
    }
}

#[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 {}
}