From 45e6b5e601af44e97f10bce9720fed528a0f8c47 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Mon, 15 Mar 2021 21:42:44 +0100 Subject: [PATCH] LibJS: Make eval() return the last value from the executed statement This is kinda awkward but since the statement we're executing is actually a JS::Program, we have to get the result via VM::last_value(). --- Userland/Libraries/LibJS/Runtime/GlobalObject.cpp | 6 ++++-- Userland/Libraries/LibJS/Tests/eval-basic.js | 10 ++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 Userland/Libraries/LibJS/Tests/eval-basic.js diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp index 952858077e..bcd06266dd 100644 --- a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp @@ -325,8 +325,10 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval) auto& caller_frame = vm.call_stack().at(vm.call_stack().size() - 2); TemporaryChange scope_change(vm.call_frame().scope, caller_frame->scope); - // FIXME: eval() should return the result of the executed code. This currently does not work. - return vm.interpreter().execute_statement(global_object, program); + vm.interpreter().execute_statement(global_object, program); + if (vm.exception()) + return {}; + return vm.last_value(); } } diff --git a/Userland/Libraries/LibJS/Tests/eval-basic.js b/Userland/Libraries/LibJS/Tests/eval-basic.js new file mode 100644 index 0000000000..955e86dc22 --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/eval-basic.js @@ -0,0 +1,10 @@ +test("basic eval() functionality", () => { + expect(eval("1 + 2")).toBe(3); + + function foo(a) { + var x = 5; + eval("x += a"); + return x; + } + expect(foo(7)).toBe(12); +});