NativeFunction.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Interpreter.h>
  7. #include <LibJS/Runtime/FunctionEnvironment.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/NativeFunction.h>
  10. #include <LibJS/Runtime/Value.h>
  11. namespace JS {
  12. NativeFunction* NativeFunction::create(GlobalObject& global_object, const FlyString& name, Function<Value(VM&, GlobalObject&)> function)
  13. {
  14. return global_object.heap().allocate<NativeFunction>(global_object, name, move(function), *global_object.function_prototype());
  15. }
  16. // FIXME: m_realm is supposed to be the realm argument of CreateBuiltinFunction, or the current
  17. // Realm Record. The former is not something that's commonly used or we support, the
  18. // latter is impossible as no ExecutionContext exists when most NativeFunctions are created...
  19. NativeFunction::NativeFunction(Object& prototype)
  20. : FunctionObject(prototype)
  21. , m_realm(vm().interpreter_if_exists() ? &vm().interpreter().realm() : nullptr)
  22. {
  23. }
  24. NativeFunction::NativeFunction(FlyString name, Function<Value(VM&, GlobalObject&)> native_function, Object& prototype)
  25. : FunctionObject(prototype)
  26. , m_name(move(name))
  27. , m_native_function(move(native_function))
  28. , m_realm(vm().interpreter_if_exists() ? &vm().interpreter().realm() : nullptr)
  29. {
  30. }
  31. NativeFunction::NativeFunction(FlyString name, Object& prototype)
  32. : FunctionObject(prototype)
  33. , m_name(move(name))
  34. , m_realm(vm().interpreter_if_exists() ? &vm().interpreter().realm() : nullptr)
  35. {
  36. }
  37. NativeFunction::~NativeFunction()
  38. {
  39. }
  40. Value NativeFunction::call()
  41. {
  42. return m_native_function(vm(), global_object());
  43. }
  44. Value NativeFunction::construct(FunctionObject&)
  45. {
  46. return {};
  47. }
  48. FunctionEnvironment* NativeFunction::new_function_environment(Object* new_target)
  49. {
  50. // Simplified version of 9.1.2.4 NewFunctionEnvironment ( F, newTarget )
  51. Environment* parent_scope = nullptr;
  52. if (!vm().execution_context_stack().is_empty())
  53. parent_scope = vm().lexical_environment();
  54. auto* environment = heap().allocate<FunctionEnvironment>(global_object(), parent_scope);
  55. environment->set_new_target(new_target ? new_target : js_undefined());
  56. return environment;
  57. }
  58. bool NativeFunction::is_strict_mode() const
  59. {
  60. return true;
  61. }
  62. }