From 2d603c7c3fb21c0a16298cfc490f8fb3c1979875 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 1 Apr 2024 22:00:29 -0400 Subject: [PATCH] LibJS: Support computed member expressions in nullish object exceptions --- Userland/Libraries/LibJS/Bytecode/Generator.cpp | 7 ++++--- .../LibJS/Tests/null-or-undefined-access.js | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Userland/Libraries/LibJS/Bytecode/Generator.cpp b/Userland/Libraries/LibJS/Bytecode/Generator.cpp index 122a6c9b549..5a7c3b1a0a2 100644 --- a/Userland/Libraries/LibJS/Bytecode/Generator.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Generator.cpp @@ -461,9 +461,10 @@ static Optional expression_identifier(Expression const& expression) builder.append(*identifer); if (auto identifer = expression_identifier(member_expression.property()); identifer.has_value()) { - if (!builder.is_empty()) - builder.append('.'); - builder.append(*identifer); + if (member_expression.is_computed()) + builder.appendff("[{}]", *identifer); + else + builder.appendff(".{}", *identifer); } return builder.to_byte_string(); diff --git a/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js b/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js index c5a1a754cdc..b4d6c7425ae 100644 --- a/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js +++ b/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js @@ -43,6 +43,7 @@ test("null/undefined object key", () => { test("null/undefined array index", () => { [null, undefined].forEach(value => { let foo = [value]; + let index = 0; expect(() => { foo[0].bar; @@ -51,5 +52,19 @@ test("null/undefined array index", () => { expect(() => { foo[0].bar = 1; }).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object`); + + expect(() => { + foo[index].bar; + }).toThrowWithMessage( + TypeError, + `Cannot access property "bar" on ${value} object "foo[index]"` + ); + + expect(() => { + foo[index].bar = 1; + }).toThrowWithMessage( + TypeError, + `Cannot access property "bar" on ${value} object "foo[index]"` + ); }); });