From 4da3e5d91fd10424ffe791ecdc93b982daa0cc16 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 14 Mar 2021 16:20:01 +0100 Subject: LibJS: Add naive implementation of eval() :^) This parses and executes a code string in the caller's lexical scope. --- Userland/Libraries/LibJS/Runtime/GlobalObject.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'Userland/Libraries/LibJS/Runtime/GlobalObject.cpp') diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp index 0a17ac6186..952858077e 100644 --- a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp @@ -25,9 +25,13 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include #include #include #include +#include +#include +#include #include #include #include @@ -119,6 +123,7 @@ void GlobalObject::initialize() define_native_function(vm.names.isFinite, is_finite, 1, attr); define_native_function(vm.names.parseFloat, parse_float, 1, attr); define_native_function(vm.names.parseInt, parse_int, 1, attr); + define_native_function(vm.names.eval, eval, 1, attr); define_property(vm.names.NaN, js_nan(), 0); define_property(vm.names.Infinity, js_infinity(), 0); @@ -309,4 +314,19 @@ Value GlobalObject::get_this_binding(GlobalObject&) const return Value(this); } +JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval) +{ + auto code = vm.argument(0).to_string(global_object); + if (code.is_null()) + return {}; + JS::Parser parser { JS::Lexer { code } }; + auto program = parser.parse_program(); + + 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); +} + } -- cgit v1.2.3