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
use swc_atoms::{atom, Atom, Wtf8Atom};
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(
atom!("NaN"),
*span,
SyntaxContext::empty().apply_mark(self.marks.unresolved_mark),
)
.into();
self.changed = true;
report_change!("strings: Evaluated 0 / 0 => NaN in string context");
}
}
}
_ => {}
}
}
/// Convert string literals with escaped newline `'\n'` to template literal
/// with newline character.
pub(super) fn reduce_escaped_newline_for_str_lit(&mut self, expr: &mut Expr) {
if self.options.ecma < EsVersion::Es2015
|| !self.options.experimental.reduce_escaped_newline
{
return;
}
if let Expr::Lit(Lit::Str(s)) = expr {
let mut template_longer_count = 0;
let mut iter = s.value.code_points().peekable();
while let Some(cp) = iter.next() {
if let Some(ch) = cp.to_char() {
match ch {
'`' => {
template_longer_count += 1;
}
'\r' | '\n' => {
template_longer_count -= 1;
}
'$' if iter.peek().and_then(|cp| cp.to_char()) == Some('{') => {
iter.next();
let mut cloned_iter = iter.clone();
while let Some(cp) = cloned_iter.next() {
if let Some(ch) = cp.to_char() {
if ch == '}' {
iter = cloned_iter;
template_longer_count += 1;
break;
}
}
}
}
_ => {}
}
}
}
if template_longer_count < 0 {
*expr = Expr::Tpl(Tpl {
span: s.span,
exprs: Default::default(),
quasis: vec![TplElement {
span: s.span,
cooked: Some(s.value.clone()),
raw: convert_str_value_to_tpl_raw(&s.value),
tail: true,
}],
});
self.changed = true;
report_change!("strings: Reduced escaped newline for a string literal");
}
}
}
}
pub(super) fn convert_str_value_to_tpl_raw(value: &Wtf8Atom) -> Atom {
let mut result = String::with_capacity(value.len());
let mut code_points = value.code_points().peekable();
while let Some(code_point) = code_points.next() {
if let Some(ch) = code_point.to_char() {
// Valid Unicode character
match ch {
'\\' => result.push_str("\\\\"),
'`' => result.push_str("\\`"),
'\r' => result.push_str("\\r"),
'$' if code_points.peek().and_then(|cp| cp.to_char()) == Some('{') => {
result.push_str("\\${");
code_points.next(); // Consume the '{'
}
// Escape control characters (0x00-0x1f) except \n (0x0a) and \t (0x09)
// which can be safely included in template literals
'\x00' => {
// Check if next char is a digit - if so, use \x00 to avoid ambiguity
if code_points
.peek()
.and_then(|cp| cp.to_char())
.is_some_and(|c| c.is_ascii_digit())
{
result.push_str("\\x00");
} else {
result.push_str("\\0");
}
}
'\x01'..='\x08' | '\x0b' | '\x0c' | '\x0e'..='\x1f' => {
// Use \xNN format for other control characters
use std::fmt::Write;
write!(result, "\\x{:02x}", ch as u8).unwrap();
}
_ => result.push(ch),
}
} else {
// Unparied surrogate, escape as \\uXXXX (two backslashes)
result.push_str(&format!("\\\\u{:04X}", code_point.to_u32()));
}
}
Atom::new(result)
}