swc_ecma_compat_es2015/
typeof_symbol.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
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::{helper, perf::Parallel};
use swc_ecma_utils::{quote_str, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;

pub fn typeof_symbol() -> impl Pass {
    visit_mut_pass(TypeOfSymbol)
}

#[derive(Clone, Copy)]
struct TypeOfSymbol;

#[swc_trace]
impl Parallel for TypeOfSymbol {
    fn merge(&mut self, _: Self) {}

    fn create(&self) -> Self {
        TypeOfSymbol
    }
}

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

    fn visit_mut_bin_expr(&mut self, expr: &mut BinExpr) {
        match expr.op {
            op!("==") | op!("!=") | op!("===") | op!("!==") => {}
            _ => {
                expr.visit_mut_children_with(self);
                return;
            }
        }

        if let Expr::Unary(UnaryExpr {
            op: op!("typeof"), ..
        }) = *expr.left
        {
            if is_non_symbol_literal(&expr.right) {
                return;
            }
        }
        if let Expr::Unary(UnaryExpr {
            op: op!("typeof"), ..
        }) = *expr.right
        {
            if is_non_symbol_literal(&expr.left) {
                return;
            }
        }

        expr.visit_mut_children_with(self)
    }

    fn visit_mut_expr(&mut self, expr: &mut Expr) {
        expr.visit_mut_children_with(self);

        if let Expr::Unary(UnaryExpr {
            span,
            op: op!("typeof"),
            arg,
        }) = expr
        {
            match &**arg {
                Expr::Ident(..) => {
                    let undefined_str: Box<Expr> = quote_str!("undefined").into();

                    let test = BinExpr {
                        span: DUMMY_SP,
                        op: op!("==="),
                        left: Box::new(
                            UnaryExpr {
                                span: DUMMY_SP,
                                op: op!("typeof"),
                                arg: arg.clone(),
                            }
                            .into(),
                        ),
                        right: undefined_str.clone(),
                    }
                    .into();

                    let call = CallExpr {
                        span: *span,
                        callee: helper!(*span, type_of),
                        args: vec![arg.take().as_arg()],
                        ..Default::default()
                    }
                    .into();

                    *expr = CondExpr {
                        span: *span,
                        test,
                        cons: undefined_str,
                        alt: Box::new(call),
                    }
                    .into();
                }
                _ => {
                    let call = CallExpr {
                        span: *span,
                        callee: helper!(*span, type_of),
                        args: vec![arg.take().as_arg()],

                        ..Default::default()
                    }
                    .into();

                    *expr = call;
                }
            }
        }
    }

    fn visit_mut_fn_decl(&mut self, f: &mut FnDecl) {
        if &f.ident.sym == "_type_of" {
            return;
        }

        f.visit_mut_children_with(self);
    }

    fn visit_mut_function(&mut self, f: &mut Function) {
        if let Some(body) = &f.body {
            if let Some(Stmt::Expr(first)) = body.stmts.first() {
                if let Expr::Lit(Lit::Str(s)) = &*first.expr {
                    match &*s.value {
                        "@swc/helpers - typeof" | "@babel/helpers - typeof" => return,
                        _ => {}
                    }
                }
            }
        }

        f.visit_mut_children_with(self);
    }
}

#[tracing::instrument(level = "info", skip_all)]
fn is_non_symbol_literal(e: &Expr) -> bool {
    match e {
        Expr::Lit(Lit::Str(Str { value, .. })) => matches!(
            &**value,
            "undefined" | "boolean" | "number" | "string" | "function"
        ),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use swc_ecma_parser::Syntax;
    use swc_ecma_transforms_testing::test;

    use super::*;

    test!(
        Syntax::default(),
        |_| typeof_symbol(),
        dont_touch_non_symbol_comparison,
        "typeof window !== 'undefined'"
    );

    test!(
        Syntax::default(),
        |_| typeof_symbol(),
        dont_touch_non_symbol_comparison_02,
        "'undefined' !== typeof window"
    );

    test!(
        Syntax::default(),
        |_| typeof_symbol(),
        issue_1843_1,
        "
        function isUndef(type) {
            return type === 'undefined';
        }

        var isWeb = !isUndef(typeof window) && 'onload' in window;
        exports.isWeb = isWeb;
        var isNode = !isUndef(typeof process) && !!(process.versions && process.versions.node);
        exports.isNode = isNode;
        var isWeex = !isUndef(typeof WXEnvironment) && WXEnvironment.platform !== 'Web';
        exports.isWeex = isWeex;
        "
    );
}