fix(es/minifier): Collect raw str values for new Tpl element (#9261)

**Description:**

Convert `raw` value to `cooked` for creating a new Tpl element.


**Related issue:**

 - Closes https://github.com/swc-project/swc/issues/9184
This commit is contained in:
pshu 2024-07-17 13:50:04 +08:00 committed by GitHub
parent 38c8453103
commit 6ddbfa04db
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 42 additions and 14 deletions

View File

@ -121,13 +121,15 @@ impl Pure<'_> {
quasis: Default::default(),
exprs: Default::default(),
};
let mut cur_str_value = String::new();
let mut cur_cooked_str = String::new();
let mut cur_raw_str = String::new();
for idx in 0..(tpl.quasis.len() + tpl.exprs.len()) {
if idx % 2 == 0 {
let q = tpl.quasis[idx / 2].take();
cur_str_value.push_str(q.cooked.as_deref().unwrap_or(&*q.raw));
cur_cooked_str.push_str(&Str::from_tpl_raw(&q.raw));
cur_raw_str.push_str(&q.raw);
} else {
let mut e = tpl.exprs[idx / 2].take();
self.eval_nested_tpl(&mut e);
@ -141,16 +143,19 @@ impl Pure<'_> {
if idx % 2 == 0 {
let q = e.quasis[idx / 2].take();
cur_str_value.push_str(q.cooked.as_deref().unwrap_or(&*q.raw));
cur_cooked_str.push_str(Str::from_tpl_raw(&q.raw).as_ref());
cur_raw_str.push_str(&q.raw);
} else {
let s = Atom::from(&*cur_str_value);
cur_str_value.clear();
let cooked = Atom::from(&*cur_cooked_str);
let raw = Atom::from(&*cur_raw_str);
cur_cooked_str.clear();
cur_raw_str.clear();
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(s.clone()),
raw: s,
cooked: Some(cooked),
raw,
});
let e = e.exprs[idx / 2].take();
@ -160,14 +165,16 @@ impl Pure<'_> {
}
}
_ => {
let s = Atom::from(&*cur_str_value);
cur_str_value.clear();
let cooked = Atom::from(&*cur_cooked_str);
let raw = Atom::from(&*cur_raw_str);
cur_cooked_str.clear();
cur_raw_str.clear();
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(s.clone()),
raw: s,
cooked: Some(cooked),
raw,
});
new_tpl.exprs.push(e);
@ -176,12 +183,13 @@ impl Pure<'_> {
}
}
let s = Atom::from(&*cur_str_value);
let cooked = Atom::from(&*cur_cooked_str);
let raw = Atom::from(&*cur_raw_str);
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(s.clone()),
raw: s,
cooked: Some(cooked),
raw,
});
*e = new_tpl.into();

View File

@ -11325,3 +11325,23 @@ fn issue_9010() {
"#,
);
}
#[test]
fn issue_9184() {
run_default_exec_test(
r#"
let pi= Math.random() >1.1 ? "foo": "bar";
console.log(`(${`${pi}`} - ${`\\*${pi}`})`)
"#,
);
}
#[test]
fn issue_9184_2() {
run_default_exec_test(
r#"
let pi= Math.random() < -1 ? "foo": "bar";
console.log(`(${`${pi}`} - ${`\\*${pi}`})`)
"#,
);
}