Truly independent web browser
LibJS: Name a field initializer's value by the field's computed key
Shannon Booth5e8301cdf0be
diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.Sindex 585cc71504d..513cc0c3b59 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S@@ -22,6 +22,7 @@ asm_dispatch_table:.quad asm_handler_ConcatString.quad asm_handler_CopyObjectExcludingProperties.quad asm_handler_ImportCall+ .quad asm_handler_GetClassFieldInitializerName.quad asm_handler_GetClassProtoParent.quad asm_handler_NewClass.quad asm_handler_Jump@@ -268,7 +269,6 @@ asm_dispatch_table:.quad asm_handler_fallback.quad asm_handler_fallback.quad asm_handler_fallback- .quad asm_handler_fallback.globl CSYM(js_interpreter_debug_dispatch_table)CSYM(js_interpreter_debug_dispatch_table):@@ -569,6 +569,10 @@ CSYM(js_interpreter_handler_ranges):.quad asm_handler_ImportCall_hot_end.quad asm_handler_ImportCall_cold.quad asm_handler_ImportCall_cold_end+ .quad asm_handler_GetClassFieldInitializerName+ .quad asm_handler_GetClassFieldInitializerName_hot_end+ .quad asm_handler_GetClassFieldInitializerName_cold+ .quad asm_handler_GetClassFieldInitializerName_cold_end.quad asm_handler_GetClassProtoParent.quad asm_handler_GetClassProtoParent_hot_end.quad asm_handler_GetClassProtoParent_cold@@ -1553,10 +1557,6 @@ CSYM(js_interpreter_handler_ranges):.quad asm_handler_fallback_hot_end.quad asm_handler_fallback_cold.quad asm_handler_fallback_cold_end- .quad asm_handler_fallback- .quad asm_handler_fallback_hot_end- .quad asm_handler_fallback_cold- .quad asm_handler_fallback_cold_end.text@@ -9061,6 +9061,45 @@ asm_handler_ImportCall_hot_end:asm_handler_ImportCall_cold:asm_handler_ImportCall_cold_end:+.p2align 4+asm_handler_GetClassFieldInitializerName:+ mov x0, x20+ sub w1, w21, w26+ str w1, [x28, #64]+ mov x0, x20+ sub w1, w21, w26+ mov x2, x21+ bl CSYM(asm_slow_path_get_class_field_initializer_name)+ tbnz x0, #63, .Lasm_GetClassFieldInitializerName.scalar_result_done_0+ tbz x0, #32, .Lasm_GetClassFieldInitializerName.scalar_result_done_0+ ldr w9, [x21, #4]+ str x1, [x27, x9, lsl #3]+ add x21, x26, w0, uxtw+ ldrb w9, [x21]+ ldr x10, [x19, x9, lsl #3]+ br x10+.Lasm_GetClassFieldInitializerName.scalar_result_done_0:+ tbz x0, #63, 1f+ b .Lexit+1:+ tbz x0, #32, .Lasm_GetClassFieldInitializerName.slow_path_transfer_1+ add x21, x26, w0, uxtw+ ldrb w9, [x21]+ ldr x10, [x19, x9, lsl #3]+ br x10+.Lasm_GetClassFieldInitializerName.slow_path_transfer_1:+ ldr x28, [x20]+ ldr x9, [x28, #88]+ ldr x26, [x9, #40]+ add x27, x28, #128+ add x21, x26, w0, uxtw+ ldrb w9, [x21]+ ldr x10, [x19, x9, lsl #3]+ br x10+asm_handler_GetClassFieldInitializerName_hot_end:+asm_handler_GetClassFieldInitializerName_cold:+asm_handler_GetClassFieldInitializerName_cold_end:+.p2align 4asm_handler_GetClassProtoParent:mov x0, x20diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.Sindex f2b3a24f9d6..5085c2135fb 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S@@ -23,6 +23,7 @@ asm_dispatch_table:.quad asm_handler_ConcatString.quad asm_handler_CopyObjectExcludingProperties.quad asm_handler_ImportCall+ .quad asm_handler_GetClassFieldInitializerName.quad asm_handler_GetClassProtoParent.quad asm_handler_NewClass.quad asm_handler_Jump@@ -269,7 +270,6 @@ asm_dispatch_table:.quad asm_handler_fallback.quad asm_handler_fallback.quad asm_handler_fallback- .quad asm_handler_fallback.globl CSYM(js_interpreter_debug_dispatch_table)CSYM(js_interpreter_debug_dispatch_table):@@ -570,6 +570,10 @@ CSYM(js_interpreter_handler_ranges):.quad asm_handler_ImportCall_hot_end.quad asm_handler_ImportCall_cold.quad asm_handler_ImportCall_cold_end+ .quad asm_handler_GetClassFieldInitializerName+ .quad asm_handler_GetClassFieldInitializerName_hot_end+ .quad asm_handler_GetClassFieldInitializerName_cold+ .quad asm_handler_GetClassFieldInitializerName_cold_end.quad asm_handler_GetClassProtoParent.quad asm_handler_GetClassProtoParent_hot_end.quad asm_handler_GetClassProtoParent_cold@@ -1554,10 +1558,6 @@ CSYM(js_interpreter_handler_ranges):.quad asm_handler_fallback_hot_end.quad asm_handler_fallback_cold.quad asm_handler_fallback_cold_end- .quad asm_handler_fallback- .quad asm_handler_fallback_hot_end- .quad asm_handler_fallback_cold- .quad asm_handler_fallback_cold_end.text@@ -9073,6 +9073,45 @@ asm_handler_ImportCall_hot_end:asm_handler_ImportCall_cold:asm_handler_ImportCall_cold_end:+.p2align 4+asm_handler_GetClassFieldInitializerName:+ mov DWORD PTR [rbx + -64], r13d+ lea r11, [r14 + r13]+ mov rdi, QWORD PTR [rbp - 48]+ mov esi, r13d+ lea rdx, [r14 + r13]+ call CSYM(asm_slow_path_get_class_field_initializer_name)+ test rax, rax+ js .Lasm_GetClassFieldInitializerName.scalar_result_done_0+ bt rax, 32+ jnc .Lasm_GetClassFieldInitializerName.scalar_result_done_0+ lea rcx, [r14 + r13]+ mov r10d, DWORD PTR [rcx + 4]+ mov QWORD PTR [rbx + r10 * 8], rdx+ mov r13d, eax+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+.Lasm_GetClassFieldInitializerName.scalar_result_done_0:+ test rax, rax+ js .Lexit+ bt rax, 32+ jnc .Lasm_GetClassFieldInitializerName.slow_path_transfer_1+ mov r13d, eax+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+.Lasm_GetClassFieldInitializerName.slow_path_transfer_1:+ mov rcx, QWORD PTR [rbp - 48]+ mov rbx, QWORD PTR [rcx]+ add rbx, 128+ mov rcx, QWORD PTR [rbx + -40]+ mov r14, QWORD PTR [rcx + 40]+ mov r13d, eax+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+asm_handler_GetClassFieldInitializerName_hot_end:+asm_handler_GetClassFieldInitializerName_cold:+asm_handler_GetClassFieldInitializerName_cold_end:+.p2align 4asm_handler_GetClassProtoParent:mov DWORD PTR [rbx + -64], r13ddiff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flapindex 50a31e04672..8bc6b8a9d44 100644--- a/Libraries/LibJS/Interpreter/interpreter.flap+++ b/Libraries/LibJS/Interpreter/interpreter.flap@@ -1515,6 +1515,10 @@ handler ImportCall(options: Operand) @cold = call_slow_path(import_call);+handler GetClassFieldInitializerName(+ dst: out Operand+) @cold = call_slow_path(get_class_field_initializer_name);+handler GetClassProtoParent(dst: out Operand,super_class: Operanddiff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rsindex 3f648d84861..1fe8eb95701 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs@@ -286,6 +286,7 @@ pub fn handling(opcode: OpCode) -> Handling {O::Exp| O::CopyObjectExcludingProperties| O::ImportCall+ | O::GetClassFieldInitializerName| O::GetClassProtoParent| O::NewClass| O::GetImportMetadiff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rsindex 9481c97086e..482d846ec60 100644--- a/Libraries/LibJS/Rust/src/ast.rs+++ b/Libraries/LibJS/Rust/src/ast.rs@@ -1677,7 +1677,8 @@ pub struct FunctionDeclarationData {#[derive(Clone, Debug)]pub struct ClassFieldInitializerData {pub expression: Box<Expression>,- pub field_name: Utf16String,+ /// The name of the field, unless its key is computed.+ pub field_name: Option<Utf16String>,}// =============================================================================diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rsindex 7f77ba6965a..5b603a37f11 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs@@ -1377,13 +1377,34 @@ pub fn generate_statement(// === ClassFieldInitializer ===StatementKind::ClassFieldInitializer(data) => {- // Only set pending_lhs_name for compile-time-known keys (non-empty names).- // For computed keys, field_name is empty and the name is set at runtime.- if !data.field_name.is_empty() {- generator.pending_lhs_name = Some(generator.intern_identifier(&data.field_name));- }- let value = generate_expression_or_undefined(&data.expression, generator, None);- generator.pending_lhs_name = None;+ // https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody+ // Initializer : = AssignmentExpression+ // 3. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then+ // a. Let value be ? NamedEvaluation of Initializer with argument func.[[ClassFieldInitializerName]].+ // 4. Else,+ // a. Let rhs be ? Evaluation of AssignmentExpression.+ // b. Let value be ? GetValue(rhs).+ let value = if let Some(field_name) = &data.field_name {+ generator.pending_lhs_name = Some(generator.intern_identifier(field_name));+ let value = generate_expression_or_undefined(&data.expression, generator, None);+ generator.pending_lhs_name = None;+ value+ } else if is_anonymous_function_definition(generator, &data.expression) {+ // NB: A computed key is only known once the class is defined, so the function reads it.+ let name = generator.allocate_register();+ generator.emit(Instruction::GetClassFieldInitializerName { dst: name.operand() });+ if matches!(data.expression.inner, ExpressionKind::Class(_)) {+ generator.pending_computed_class_name = Some(name);+ generate_expression_or_undefined(&data.expression, generator, None)+ } else {+ let value = generate_expression_or_undefined(&data.expression, generator, None);+ emit_set_function_name(generator, &value, &name, FunctionNamePrefix::None);+ value+ }+ } else {+ generate_expression_or_undefined(&data.expression, generator, None)+ };+ // 5. Return ReturnCompletion(value).generator.emit(Instruction::Return { value: value.operand() });None}@@ -7254,21 +7275,7 @@ fn generate_class_expression(};if !is_literal {- // Determine field name for anonymous function naming.- let arena = generator.arena.clone();- let field_name = match &key.inner {- ExpressionKind::Identifier(ident) => arena.name_of(*ident).clone(),- ExpressionKind::StringLiteral(s) => (**s).clone(),- ExpressionKind::PrivateIdentifier(p) => p.name.clone(),- ExpressionKind::NumericLiteral(n) => crate::host::js_number_to_utf16(*n),- ExpressionKind::BigIntLiteral(s) => {- let digits = String::from_utf16_lossy(bigint_literal_digits(s));- let value =- parse_bigint(&digits).expect("the lexer only produces valid BigInt literals");- Utf16String(value.to_string().encode_utf16().collect())- }- _ => Utf16String::new(),- };+ let field_name = class_field_literal_name(key);// Use the ClassFieldInitializer statement directly as the// synthetic function's body. compile_function_payload tolerates@@ -7277,7 +7284,7 @@ fn generate_class_expression(init_expression.range,StatementKind::ClassFieldInitializer(Box::new(ClassFieldInitializerData {expression: Box::new(init_expression.as_ref().clone()),- field_name,+ field_name: field_name.clone(),})),);@@ -7304,16 +7311,8 @@ fn generate_class_expression(});let index = emit_new_function(generator, function_data, Some(utf16!("field")));- let key_is_private = is_private_key(key);- let key_name: Utf16String = match &key.inner {- ExpressionKind::PrivateIdentifier(ident) => ident.name.clone(),- ExpressionKind::Identifier(ident) => arena.name_of(*ident).clone(),- ExpressionKind::StringLiteral(s) => (**s).clone(),- ExpressionKind::NumericLiteral(n) => crate::host::js_number_to_utf16(*n),- _ => Utf16String::new(),- };- if !key_name.is_empty() {- generator.set_class_field_initializer_name(index, key_name, key_is_private);+ if let Some(field_name) = field_name {+ generator.set_class_field_initializer_name(index, field_name, is_private_key(key));}sfd_index = Some(index);@@ -7444,6 +7443,22 @@ fn generate_class_element_key(generator: &mut Generator, key: &Expression) -> OpSome(property_key)}+/// The name of a class field whose key is a literal, which a computed key gets only when the class is defined.+// https://tc39.es/ecma262/#sec-static-semantics-propname+fn class_field_literal_name(key: &Expression) -> Option<Utf16String> {+ match &key.inner {+ ExpressionKind::StringLiteral(string) => Some((**string).clone()),+ ExpressionKind::PrivateIdentifier(identifier) => Some(identifier.name.clone()),+ ExpressionKind::NumericLiteral(number) => Some(crate::host::js_number_to_utf16(*number)),+ ExpressionKind::BigIntLiteral(literal) => {+ let digits = String::from_utf16_lossy(bigint_literal_digits(literal));+ let value = parse_bigint(&digits).expect("the lexer only produces valid BigInt literals");+ Some(Utf16String(value.to_string().encode_utf16().collect()))+ }+ _ => None,+ }+}+/// Synthesize a default constructor SharedFunctionInstanceData.fn emit_default_constructor(generator: &mut Generator, has_super: bool) -> u32 {use crate::parser::Parser;diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rsindex d043a378035..ecb19cc7458 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs@@ -45,7 +45,7 @@ use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunuse crate::runtime::object::{Object, StackFrameInfo};use crate::runtime::property_attributes::DEFAULT_ATTRIBUTES;use crate::runtime::property_key::PropertyKey;-use crate::runtime::shared_function_instance_data::{ConstructorKind, FunctionKind};+use crate::runtime::shared_function_instance_data::{ClassFieldInitializerName, ConstructorKind, FunctionKind};use crate::utf16::Utf16Display;/// Op::CallType: how a call instruction calls its callee.@@ -158,6 +158,24 @@ fn element_key_operands(instruction: &op::NewClass) -> &[OptionalOperand] {instruction.element_keys()}+/// The [[ClassFieldInitializerName]] of the running field initializer, whose field has a computed key.+pub fn get_class_field_initializer_name(+ vm: &Vm,+ pc: u32,+ values: &mut op::GetClassFieldInitializerNameValues,+) -> SlowPathControl {+ let function = running_execution_context(vm)+ .function+ .get()+ .and_then(as_ecmascript_function_object)+ .expect("a field initializer is an ECMAScript function");+ let ClassFieldInitializerName::PropertyKey(name) = function.class_field_initializer_name() else {+ unreachable!("a field with a computed key is named by a property key");+ };+ values.dst = name.to_value(vm);+ SlowPathControl::continue_at(pc + op::GetClassFieldInitializerName::LENGTH)+}+pub fn get_class_proto_parent(vm: &Vm, pc: u32, values: &mut op::GetClassProtoParentValues) -> SlowPathControl {values.dst = asm_try!(vm, pc, class_proto_parent(vm, values.super_class));SlowPathControl::continue_at(pc + op::GetClassProtoParent::LENGTH)diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rsindex d0507187680..7f22f85033c 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs@@ -1155,6 +1155,15 @@ impl RuntimeFunctions for Runtime {calls::get_super_constructor(vm, pc, values)}+ fn get_class_field_initializer_name(+ vm: &Vm,+ pc: u32,+ _instruction: &op::GetClassFieldInitializerName,+ values: &mut op::GetClassFieldInitializerNameValues,+ ) -> SlowPathControl {+ calls::get_class_field_initializer_name(vm, pc, values)+ }+fn get_class_proto_parent(vm: &Vm,pc: u32,diff --git a/Libraries/LibJS/Rust/src/runtime/class_construction.rs b/Libraries/LibJS/Rust/src/runtime/class_construction.rsindex dcab65612d5..55b79b3aed5 100644--- a/Libraries/LibJS/Rust/src/runtime/class_construction.rs+++ b/Libraries/LibJS/Rust/src/runtime/class_construction.rs@@ -346,23 +346,10 @@ pub fn construct_class(.shared_function_data_index.expect("a field initializer has shared function data"),);-- // Set class_field_initializer_name at runtime for computed keys.- if !descriptor.is_private- && matches!(- shared_data.class_field_initializer_name(),- ClassFieldInitializerName::Empty- )- {- shared_data.set_class_field_initializer_name(match &element_name {- ClassElementName::PropertyKey(key) => {- ClassFieldInitializerName::PropertyKey(key.clone())- }- ClassElementName::PrivateName(name) => {- ClassFieldInitializerName::PrivateName(name.description.clone())- }- });- }+ let has_computed_name = matches!(+ shared_data.class_field_initializer_name(),+ ClassFieldInitializerName::Empty+ );let function = EcmascriptFunctionObject::create_method(vm,@@ -373,6 +360,15 @@ pub fn construct_class(home_object,realm.function_prototype(),);+ if has_computed_name {+ let ClassElementName::PropertyKey(key) = &element_name else {+ unreachable!("a private name is never computed");+ };+ function.set_class_field_initializer_name(+ vm,+ ClassFieldInitializerName::PropertyKey(key.clone()),+ );+ }initializer = ClassFieldInitializer::Function(function);}}diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex 4bb42b7b61a..520aeeed65c 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -61,9 +61,11 @@ use crate::utf16::to_utf16_fly_string;struct ClassData {fields: Vec<ClassFieldDefinition>, // [[Fields]]private_methods: Vec<PrivateElement>, // [[PrivateMethods]]+ /// The [[ClassFieldInitializerName]] of an initializer of a field whose key is computed.+ class_field_initializer_name: ClassFieldInitializerName,}-/// The parts of a class constructor that the interpreter does not read.+/// The parts of a class constructor, or of a field initializer, that the interpreter does not read.#[derive(Default)]pub struct EcmascriptFunctionObjectStorage {class_data: OnceCell<Box<GcRefCell<ClassData>>>,@@ -907,7 +909,7 @@ impl EcmascriptFunctionObject {fn class_data_to_add_to(&self) -> &GcRefCell<ClassData> {self.with_rare_data()- .expect("a class constructor has rare data")+ .expect("a class constructor or a field initializer has rare data").storage.class_data.get_or_init(Box::default)@@ -1091,9 +1093,20 @@ impl EcmascriptFunctionObject {}pub fn class_field_initializer_name(&self) -> ClassFieldInitializerName {+ // NB: The shared data has the name of a field whose key is not computed.+ if let Some(class_data) = self.class_data() {+ let name = class_data.borrow().class_field_initializer_name.clone();+ if !matches!(name, ClassFieldInitializerName::Empty) {+ return name;+ }+ }self.shared_data().class_field_initializer_name()}+ pub fn set_class_field_initializer_name(&self, vm: &Vm, name: ClassFieldInitializerName) {+ self.class_data_to_add_to().borrow_mut(vm).class_field_initializer_name = name;+ }+pub fn allocates_function_environment(&self) -> bool {self.shared_data().function_environment_needed()}diff --git a/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt b/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txtindex fbdf7e4ef18..7b80e82caa9 100644--- a/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt+++ b/Tests/LibJS/Bytecode/expected/class-computed-field-lhs-name.txt@@ -30,11 +30,13 @@ block0:[ 8] End value:Undefined-field$60576772 class-computed-field-lhs-name.js:2:15- Registers: 6+field$dc317dda class-computed-field-lhs-name.js:2:15+ Registers: 7Blocks: 1block0:[ 0] Enter- [ 8] NewFunction dst:reg5, shared_function_data_index:0- [ 20] Return value:reg5+ [ 8] GetClassFieldInitializerName dst:reg5+ [ 10] NewFunction dst:reg6, shared_function_data_index:0+ [ 28] SetFunctionName function:reg6, name:reg5+ [ 38] Return value:reg6diff --git a/Tests/LibJS/Runtime/classes/class-public-fields.js b/Tests/LibJS/Runtime/classes/class-public-fields.jsindex ed7e3d842aa..5027f8f8043 100644--- a/Tests/LibJS/Runtime/classes/class-public-fields.js+++ b/Tests/LibJS/Runtime/classes/class-public-fields.js@@ -184,6 +184,40 @@ test("anonymous function initializer is named by a literal key", () => {expect(A["a string"].name).toBe("a string");});+test("anonymous function initializer is named by a computed key", () => {+ const key = "named";+ const symbol = Symbol("description");+ class A {+ static [key] = function () {};+ static [`${key}Class`] = class {+ static seenName = this.name;+ };+ static [symbol] = () => {};+ [key] = () => {};+ static [(0, "notAnonymous")] = (0, function () {});+ }++ expect(A.named.name).toBe("named");+ expect(A.namedClass.name).toBe("namedClass");+ expect(A.namedClass.seenName).toBe("namedClass");+ expect(A[symbol].name).toBe("[description]");+ expect(new A().named.name).toBe("named");+ expect(A.notAnonymous.name).toBe("");+});++test("each evaluation of a class names initializers by its own computed keys", () => {+ function makeClass(key) {+ return class {+ [key] = function () {};+ };+ }++ const First = makeClass("first");+ const Second = makeClass("second");+ expect(new First().first.name).toBe("first");+ expect(new Second().second.name).toBe("second");+});+test("regex field initializer", () => {class A {pattern = /hello/;