fix(codegen): disallow template literals in object property key (#8108)

This commit is contained in:
Boshen 2024-12-25 11:22:54 +00:00
parent 7110c7b94c
commit bdc241d41d
3 changed files with 13 additions and 16 deletions

View file

@ -1337,7 +1337,7 @@ impl Gen for StringLiteral<'_> {
fn gen(&self, p: &mut Codegen, _ctx: Context) {
p.add_source_mapping(self.span);
let s = self.value.as_str();
p.print_quoted_utf16(s);
p.print_quoted_utf16(s, /* allow_backtick */ true);
}
}
@ -1647,6 +1647,9 @@ impl Gen for PropertyKey<'_> {
match self {
Self::StaticIdentifier(ident) => ident.print(p, ctx),
Self::PrivateIdentifier(ident) => ident.print(p, ctx),
Self::StringLiteral(s) => {
p.print_quoted_utf16(s.value.as_str(), /* allow_backtick */ false);
}
match_expression!(Self) => {
self.to_expression().print_expr(p, Precedence::Comma, Context::empty());
}

View file

@ -587,7 +587,7 @@ impl<'a> Codegen<'a> {
}
}
fn print_quoted_utf16(&mut self, s: &str) {
fn print_quoted_utf16(&mut self, s: &str, allow_backtick: bool) {
let quote = if self.options.minify {
let mut single_cost: u32 = 0;
let mut double_cost: u32 = 0;
@ -595,18 +595,10 @@ impl<'a> Codegen<'a> {
let mut bytes = s.as_bytes().iter().peekable();
while let Some(b) = bytes.next() {
match b {
b'\n' if self.options.minify => {
backtick_cost = backtick_cost.saturating_sub(1);
}
b'\'' => {
single_cost += 1;
}
b'"' => {
double_cost += 1;
}
b'`' => {
backtick_cost += 1;
}
b'\n' if self.options.minify => backtick_cost = backtick_cost.saturating_sub(1),
b'\'' => single_cost += 1,
b'"' => double_cost += 1,
b'`' => backtick_cost += 1,
b'$' => {
if bytes.peek() == Some(&&b'{') {
backtick_cost += 1;
@ -618,10 +610,10 @@ impl<'a> Codegen<'a> {
let mut quote = b'"';
if double_cost > single_cost {
quote = b'\'';
if single_cost > backtick_cost {
if single_cost > backtick_cost && allow_backtick {
quote = b'`';
}
} else if double_cost > backtick_cost {
} else if double_cost > backtick_cost && allow_backtick {
quote = b'`';
}
quote

View file

@ -43,6 +43,8 @@ fn expr() {
r#";'eval("\'\\vstr\\ving\\v\'") === "\\vstr\\ving\\v"'"#,
r#";`eval("'\\vstr\\ving\\v'") === "\\vstr\\ving\\v"`;"#,
);
test_minify_same(r#"({"http://a\r\" \n<'b:b@c\r\nd/e?f":{}});"#);
}
#[test]