From 0d41e542b70bdcd2eea6eac7dc2748bb5b1f2f79 Mon Sep 17 00:00:00 2001 From: Brian Gianforcaro Date: Sun, 12 Apr 2020 15:50:49 -0700 Subject: [PATCH] LibJS: Throw on assignment of an const variable Was stubbed out as an assert, should be handled with a runtime exception. --- Libraries/LibJS/Interpreter.cpp | 6 +++-- Libraries/LibJS/Tests/variable-declaration.js | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 Libraries/LibJS/Tests/variable-declaration.js diff --git a/Libraries/LibJS/Interpreter.cpp b/Libraries/LibJS/Interpreter.cpp index c3b74cff9c..756855b499 100644 --- a/Libraries/LibJS/Interpreter.cpp +++ b/Libraries/LibJS/Interpreter.cpp @@ -145,8 +145,10 @@ void Interpreter::set_variable(const FlyString& name, Value value, bool first_as auto possible_match = scope.variables.get(name); if (possible_match.has_value()) { - if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) - ASSERT_NOT_REACHED(); + if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) { + throw_exception("Assignment to constant variable"); + return; + } scope.variables.set(move(name), { move(value), possible_match.value().declaration_kind }); return; diff --git a/Libraries/LibJS/Tests/variable-declaration.js b/Libraries/LibJS/Tests/variable-declaration.js new file mode 100644 index 0000000000..ef634867c9 --- /dev/null +++ b/Libraries/LibJS/Tests/variable-declaration.js @@ -0,0 +1,25 @@ +try { + + const ConstantValue = 1; + try { + ConstantValue = 2; + } catch (e) { + assert(e.name === "TypeError"); + assert(e.message === "Assignment to constant variable"); + assert(ConstantValue === 1); + } + + // Make sure we can define new constants in inner scopes. + // + const ConstantValue2 = 1; + + do + { + const ConstantValue2 = 2; + } + while (false) + + console.log("PASS"); +} catch (e) { + console.log("FAIL: " + e); +}