swc_ecma_minifier/compress/optimize/
strings.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
use swc_common::{util::take::Take, Spanned, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::{ExprExt, Value::Known};

use super::Optimizer;

impl Optimizer<'_> {
    pub(super) fn optimize_expr_in_str_ctx_unsafely(&mut self, e: &mut Expr) {
        if !self.options.unsafe_passes {
            return;
        }

        if let Expr::Call(CallExpr {
            callee: Callee::Expr(callee),
            args,
            ..
        }) = e
        {
            if args
                .iter()
                .any(|arg| arg.expr.may_have_side_effects(&self.ctx.expr_ctx))
            {
                return;
            }

            if callee.is_ident_ref_to("RegExp") && self.options.unsafe_regexp {
                if args.len() != 1 {
                    return;
                }

                self.optimize_expr_in_str_ctx(&mut args[0].expr);

                if let Expr::Lit(Lit::Str(..)) = &*args[0].expr {
                    self.changed = true;
                    report_change!("strings: Unsafely reduced `RegExp` call in a string context");

                    *e = *args[0].expr.take();
                }
            }
        }
    }

    /// Convert expressions to string literal if possible.
    pub(super) fn optimize_expr_in_str_ctx(&mut self, n: &mut Expr) {
        match n {
            Expr::Lit(Lit::Str(..)) => return,
            Expr::Paren(e) => {
                self.optimize_expr_in_str_ctx(&mut e.expr);
                if let Expr::Lit(Lit::Str(..)) = &*e.expr {
                    *n = *e.expr.take();
                    self.changed = true;
                    report_change!("string: Removed a paren in a string context");
                }

                return;
            }
            _ => {}
        }

        let value = n.as_pure_string(&self.ctx.expr_ctx);
        if let Known(value) = value {
            let span = n.span();

            self.changed = true;
            report_change!(
                "strings: Converted an expression into a string literal (in string context)"
            );
            *n = Lit::Str(Str {
                span,
                raw: None,
                value: value.into(),
            })
            .into();
            return;
        }

        match n {
            Expr::Lit(Lit::Num(v)) => {
                self.changed = true;
                report_change!(
                    "strings: Converted a numeric literal ({}) into a string literal (in string \
                     context)",
                    v.value
                );

                let value = format!("{:?}", v.value);

                *n = Lit::Str(Str {
                    span: v.span,
                    raw: None,
                    value: value.into(),
                })
                .into();
            }

            Expr::Lit(Lit::Regex(v)) => {
                if !self.options.evaluate {
                    return;
                }
                self.changed = true;
                report_change!(
                    "strings: Converted a regex (/{}/{}) into a string literal (in string context)",
                    v.exp,
                    v.flags
                );

                let value = format!("/{}/{}", v.exp, v.flags);

                *n = Lit::Str(Str {
                    span: v.span,
                    raw: None,
                    value: value.into(),
                })
                .into();
            }

            Expr::Bin(BinExpr {
                span,
                op: op!("/"),
                left,
                right,
            }) => {
                if let (Expr::Lit(Lit::Num(l)), Expr::Lit(Lit::Num(r))) = (&**left, &**right) {
                    if l.value == 0.0 && r.value == 0.0 {
                        *n = Ident::new(
                            "NaN".into(),
                            *span,
                            SyntaxContext::empty().apply_mark(self.marks.unresolved_mark),
                        )
                        .into();
                        self.changed = true;
                        report_change!("strings: Evaluated 0 / 0 => NaN in string context");
                    }
                }
            }

            _ => {}
        }
    }
}