From 02b653c06116ca1ddcfefc1d713711868299c70f Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Sun, 15 Dec 2024 16:55:00 +0000 Subject: [PATCH] feat(transformer/class-properties): do not create temp var for template literal computed key (#7919) Do not create temp var for computed key which is `TemplateLiteral` with no expressions. Evaluating such a template literal cannot have side effects. ```js class C { [`foo`] = 1; } ``` But this *can* have side effects: ```js class C { [`foo${bar}`] = 1; } ``` --- .../src/es2022/class_properties/computed_key.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/oxc_transformer/src/es2022/class_properties/computed_key.rs b/crates/oxc_transformer/src/es2022/class_properties/computed_key.rs index 3a088e7e9151c..3a4e7560d2a4e 100644 --- a/crates/oxc_transformer/src/es2022/class_properties/computed_key.rs +++ b/crates/oxc_transformer/src/es2022/class_properties/computed_key.rs @@ -112,6 +112,12 @@ fn key_needs_temp_var(key: &Expression, ctx: &TraverseCtx) -> bool { | Expression::BigIntLiteral(_) | Expression::RegExpLiteral(_) | Expression::StringLiteral(_) => false, + // Template literal cannot have side effects if it has no expressions. + // If it *does* have expressions, but they're all literals, then also cannot have side effects, + // but don't bother checking for that as it shouldn't occur in real world code. + // Why would you write "`x${9}z`" when you can just write "`x9z`"? + // Note: "`x${foo}`" *can* have side effects if `foo` is an object with a `valueOf` method. + Expression::TemplateLiteral(lit) => !lit.expressions.is_empty(), // `IdentifierReference`s can have side effects if is unbound. // // If var is mutated, it also needs a temp var, because of cases like