From bfcfe6ce355c8ccdb41947a44fa3a61f1dca1f44 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 1 Apr 2024 22:02:03 -0400 Subject: [PATCH] LibJS: Support numeric literal expressions in nullish object exceptions --- Userland/Libraries/LibJS/AST.h | 3 +++ Userland/Libraries/LibJS/Bytecode/Generator.cpp | 5 +++++ .../Libraries/LibJS/Tests/null-or-undefined-access.js | 10 ++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Userland/Libraries/LibJS/AST.h b/Userland/Libraries/LibJS/AST.h index bfc599aab3..76dd573b66 100644 --- a/Userland/Libraries/LibJS/AST.h +++ b/Userland/Libraries/LibJS/AST.h @@ -91,6 +91,7 @@ public: virtual bool is_import_call() const { return false; } virtual bool is_array_expression() const { return false; } virtual bool is_object_expression() const { return false; } + virtual bool is_numeric_literal() const { return false; } virtual bool is_string_literal() const { return false; } virtual bool is_update_expression() const { return false; } virtual bool is_call_expression() const { return false; } @@ -1182,6 +1183,8 @@ public: virtual Value value() const override { return m_value; } private: + virtual bool is_numeric_literal() const override { return true; } + Value m_value; }; diff --git a/Userland/Libraries/LibJS/Bytecode/Generator.cpp b/Userland/Libraries/LibJS/Bytecode/Generator.cpp index 5a7c3b1a0a..f1949477c3 100644 --- a/Userland/Libraries/LibJS/Bytecode/Generator.cpp +++ b/Userland/Libraries/LibJS/Bytecode/Generator.cpp @@ -453,6 +453,11 @@ static Optional expression_identifier(Expression const& expression) return identifier.string(); } + if (expression.is_numeric_literal()) { + auto const& literal = static_cast(expression); + return literal.value().to_string_without_side_effects().to_byte_string(); + } + if (expression.is_member_expression()) { auto const& member_expression = static_cast(expression); StringBuilder builder; diff --git a/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js b/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js index b4d6c7425a..939a9bd33f 100644 --- a/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js +++ b/Userland/Libraries/LibJS/Tests/null-or-undefined-access.js @@ -47,11 +47,17 @@ test("null/undefined array index", () => { expect(() => { foo[0].bar; - }).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object`); + }).toThrowWithMessage( + TypeError, + `Cannot access property "bar" on ${value} object "foo[0]"` + ); expect(() => { foo[0].bar = 1; - }).toThrowWithMessage(TypeError, `Cannot access property "bar" on ${value} object`); + }).toThrowWithMessage( + TypeError, + `Cannot access property "bar" on ${value} object "foo[0]"` + ); expect(() => { foo[index].bar;