summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2021-03-14 16:20:01 +0100
committerAndreas Kling <kling@serenityos.org>2021-03-15 21:20:33 +0100
commit4da3e5d91fd10424ffe791ecdc93b982daa0cc16 (patch)
treeae8c16efef3d6e8e28022e073cd94542717f3a3f /Userland/Libraries/LibJS/Runtime/GlobalObject.cpp
parent64cb04996f31c5163a3376a6ab649df59816430c (diff)
downloadserenity-4da3e5d91fd10424ffe791ecdc93b982daa0cc16.zip
LibJS: Add naive implementation of eval() :^)
This parses and executes a code string in the caller's lexical scope.
Diffstat (limited to 'Userland/Libraries/LibJS/Runtime/GlobalObject.cpp')
-rw-r--r--Userland/Libraries/LibJS/Runtime/GlobalObject.cpp20
1 files changed, 20 insertions, 0 deletions
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 <AK/TemporaryChange.h>
#include <AK/Utf8View.h>
#include <LibJS/Console.h>
#include <LibJS/Heap/DeferGC.h>
+#include <LibJS/Interpreter.h>
+#include <LibJS/Lexer.h>
+#include <LibJS/Parser.h>
#include <LibJS/Runtime/ArrayBufferConstructor.h>
#include <LibJS/Runtime/ArrayBufferPrototype.h>
#include <LibJS/Runtime/ArrayConstructor.h>
@@ -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);
+}
+
}