FunctionConstructor.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <LibJS/AST.h>
  8. #include <LibJS/Interpreter.h>
  9. #include <LibJS/Parser.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/FunctionConstructor.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. namespace JS {
  14. FunctionConstructor::FunctionConstructor(GlobalObject& global_object)
  15. : NativeFunction(vm().names.Function, *global_object.function_prototype())
  16. {
  17. }
  18. void FunctionConstructor::initialize(GlobalObject& global_object)
  19. {
  20. auto& vm = this->vm();
  21. NativeFunction::initialize(global_object);
  22. define_property(vm.names.prototype, global_object.function_prototype(), 0);
  23. define_property(vm.names.length, Value(1), Attribute::Configurable);
  24. }
  25. FunctionConstructor::~FunctionConstructor()
  26. {
  27. }
  28. Value FunctionConstructor::call()
  29. {
  30. return construct(*this);
  31. }
  32. Value FunctionConstructor::construct(Function&)
  33. {
  34. auto& vm = this->vm();
  35. String parameters_source = "";
  36. String body_source = "";
  37. if (vm.argument_count() == 1) {
  38. body_source = vm.argument(0).to_string(global_object());
  39. if (vm.exception())
  40. return {};
  41. }
  42. if (vm.argument_count() > 1) {
  43. Vector<String> parameters;
  44. for (size_t i = 0; i < vm.argument_count() - 1; ++i) {
  45. parameters.append(vm.argument(i).to_string(global_object()));
  46. if (vm.exception())
  47. return {};
  48. }
  49. StringBuilder parameters_builder;
  50. parameters_builder.join(',', parameters);
  51. parameters_source = parameters_builder.build();
  52. body_source = vm.argument(vm.argument_count() - 1).to_string(global_object());
  53. if (vm.exception())
  54. return {};
  55. }
  56. auto source = String::formatted("function anonymous({}\n) {{\n{}\n}}", parameters_source, body_source);
  57. auto parser = Parser(Lexer(source));
  58. auto function_expression = parser.parse_function_node<FunctionExpression>();
  59. if (parser.has_errors()) {
  60. auto error = parser.errors()[0];
  61. vm.throw_exception<SyntaxError>(global_object(), error.to_string());
  62. return {};
  63. }
  64. OwnPtr<Interpreter> local_interpreter;
  65. Interpreter* interpreter = vm.interpreter_if_exists();
  66. if (!interpreter) {
  67. local_interpreter = Interpreter::create_with_existing_global_object(global_object());
  68. interpreter = local_interpreter.ptr();
  69. }
  70. VM::InterpreterExecutionScope scope(*interpreter);
  71. return function_expression->execute(*interpreter, global_object());
  72. }
  73. }