Skip to content

Commit

Permalink
fix(codegen): disallow template literals in object property key (#8108)
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Dec 25, 2024
1 parent 7110c7b commit bdc241d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 16 deletions.
5 changes: 4 additions & 1 deletion crates/oxc_codegen/src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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());
}
Expand Down
22 changes: 7 additions & 15 deletions crates/oxc_codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,26 +587,18 @@ 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;
let mut backtick_cost: u32 = 0;
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;
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions crates/oxc_codegen/tests/integration/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit bdc241d

Please sign in to comment.