swc_ecma_compat_bugfixes/
safari_id_destructuring_collision_in_function_expression.rs

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
use std::collections::HashMap;

use rustc_hash::FxHashSet;
use swc_atoms::Atom;
use swc_common::SyntaxContext;
use swc_ecma_ast::*;
use swc_ecma_transforms_base::hygiene::rename;
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;

pub fn safari_id_destructuring_collision_in_function_expression() -> impl Pass {
    visit_mut_pass(SafariIdDestructuringCollisionInFunctionExpression::default())
}

#[derive(Default, Clone)]
struct SafariIdDestructuringCollisionInFunctionExpression {
    fn_expr_name: Atom,
    destructured_id_span: Option<SyntaxContext>,
    other_ident_symbols: FxHashSet<Atom>,
    in_body: bool,
}

impl SafariIdDestructuringCollisionInFunctionExpression {
    fn visit_mut_pat_id(&mut self, id: &Ident) {
        if !self.in_body && self.fn_expr_name == id.sym {
            self.destructured_id_span = Some(id.ctxt);
        } else {
            self.other_ident_symbols.insert(id.sym.clone());
        }
    }
}

#[swc_trace]
impl VisitMut for SafariIdDestructuringCollisionInFunctionExpression {
    noop_visit_mut_type!(fail);

    fn visit_mut_assign_pat_prop(&mut self, n: &mut AssignPatProp) {
        self.visit_mut_pat_id(&Ident::from(&n.key));

        n.value.visit_mut_with(self);
    }

    fn visit_mut_binding_ident(&mut self, binding_ident: &mut BindingIdent) {
        self.visit_mut_pat_id(&Ident::from(&*binding_ident))
    }

    fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) {
        let old_in_body = self.in_body;
        if let Some(ident) = &n.ident {
            let old_span = self.destructured_id_span.take();
            let old_fn_expr_name = self.fn_expr_name.clone();

            self.fn_expr_name = ident.sym.clone();
            self.in_body = false;
            n.function.params.visit_mut_children_with(self);
            self.in_body = true;
            n.function.body.visit_mut_children_with(self);

            if let Some(id_ctxt) = self.destructured_id_span.take() {
                let mut rename_map = HashMap::default();
                let new_id: Atom = {
                    let mut id_value: Atom = format!("_{}", self.fn_expr_name).into();
                    let mut count = 0;
                    while self.other_ident_symbols.contains(&id_value) {
                        count += 1;
                        id_value = format!("_{}{}", self.fn_expr_name, count).into();
                    }
                    id_value
                };
                let id = (self.fn_expr_name.clone(), id_ctxt);
                rename_map.insert(id, new_id);
                n.function.visit_mut_children_with(&mut rename(&rename_map));
            }

            self.fn_expr_name = old_fn_expr_name;
            self.destructured_id_span = old_span;
        } else {
            // fn_expr_name assgin empty to express that it is a non-ident-function
            // Otherwise, it will be treated as a function with an ident name due to the
            // previous function
            self.fn_expr_name = "".into();
            self.in_body = false;
            n.function.params.visit_mut_children_with(self);
            self.in_body = true;
            n.function.body.visit_mut_children_with(self);
        }
        self.in_body = old_in_body;
    }

    fn visit_mut_ident(&mut self, ident: &mut Ident) {
        if self.in_body && self.fn_expr_name != ident.sym {
            self.other_ident_symbols.insert(ident.sym.clone());
        }
    }

    fn visit_mut_member_prop(&mut self, p: &mut MemberProp) {
        if let MemberProp::Computed(..) = p {
            p.visit_mut_children_with(self)
        }
    }

    fn visit_mut_prop_name(&mut self, p: &mut PropName) {
        if let PropName::Computed(..) = p {
            p.visit_mut_children_with(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use swc_common::Mark;
    use swc_ecma_parser::Syntax;
    use swc_ecma_transforms_base::resolver;
    use swc_ecma_transforms_testing::{test, HygieneTester};
    use swc_ecma_visit::fold_pass;

    use super::*;

    fn tr() -> impl Pass {
        (
            resolver(Mark::new(), Mark::new(), false),
            safari_id_destructuring_collision_in_function_expression(),
        )
    }

    test!(
        Syntax::default(),
        |_| tr(),
        basic,
        "(function a ([a]) { a });
         (function a({ ...a }) { a });
         (function a({ a }) { a });"
    );

    test!(
        Syntax::default(),
        |_| tr(),
        avoid_collision_1,
        "(function a([a, _a]) { a + _a })"
    );

    test!(
        Syntax::default(),
        |_| tr(),
        issue_10242_1,
        r#"
[
  {
    37287: function (e, t, n) {
      !function (t, n) {
      }(0, (function () {
        return function (e) {}([
          function (e, t, n) {
          o.fromDer = function (e, t) {
            var a = function e(t, n, r, a) {
              var d, f, v = function (e, t) {}(t, n);
            }(e, e.length(), 0, t);
          }
          }
        ])
      }))
    },
    31922: function (e, t, n) {
      var L = (0, w.Z)(function () {
        var e = (0, i.Z)((0, o.Z)().mark((function e(t) {
          return (0, o.Z)().wrap((function (e) {

          }), e)
        })));

      }(), 1e3);
      var $ = function (e) {
        var _e = ye[0],
          $e = function () {
            var e = (0, i.Z)((0, o.Z)().mark((function e() {
              return (0, o.Z)().wrap((function (e) {

              }), e)
            })));

          }();
      },
        ee = $,

        _e = n(36750);

      var zt = function () {
        var e = (0, i.Z)((0, o.Z)().mark((
          function e(t) {
            return (0, o.Z)().wrap((function (e) {
            console.log(e);
            console.log(_e);
          }), e)
        })));
       
      }();

    }
  }
];
"#
    );

    test!(
        Syntax::default(),
        |_| tr(),
        use_duplicated_id,
        "(function a([a]) { console.log(_a); })"
    );

    test!(
        Syntax::default(),
        |_| tr(),
        avoid_collision_2,
        "(function _a([_a]) { console.log(_a); })"
    );

    test!(
        Syntax::default(),
        |_| tr(),
        assign_outside_var,
        "let _a;
        (function a([a]) {
            _a = 3;
        })"
    );

    test!(
        Syntax::default(),
        |_| tr(),
        assignment_expr_in_default_value,
        "(function a([a = a = 3]) {})"
    );

    test!(
        Syntax::default(),
        |_| (tr(), fold_pass(HygieneTester)),
        issue_4488_1,
        "
        export default function _type_of() {
            if (Date.now() > 0) {
                _type_of = function _type_of() {
                    console.log(0);
                };
            } else {
                _type_of = function _type_of() {
                    console.log(2);
                };
            }
        
            return _type_of();
        }
        "
    );

    test!(
        Syntax::default(),
        |_| tr(),
        in_nameless_fn,
        "(function () {
          (function a(a) {a});
        });
        "
    );

    test!(
        Syntax::default(),
        |_| tr(),
        in_nameless_fn_multiple,
        "// nameless iife
        var x = function() {
            // not transformed
            var b = function a(a) {
                return a;
            };
        }();
        // nameless iife
        var x = function x() {
            var b = function a(_a) {
                return _a;
            };
        }();
        // nameless function
        (function() {
            // not transformed
            var b = function a(a) {
                return a;
            };
        });
        // named function
        (function x() {
            var b = function a(_a) {
                return _a;
            };
        });"
    );
}