ErrorConstructor.cpp 3.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Error.h>
  7. #include <LibJS/Runtime/ErrorConstructor.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. namespace JS {
  10. ErrorConstructor::ErrorConstructor(GlobalObject& global_object)
  11. : NativeFunction(vm().names.Error, *global_object.function_prototype())
  12. {
  13. }
  14. void ErrorConstructor::initialize(GlobalObject& global_object)
  15. {
  16. auto& vm = this->vm();
  17. NativeFunction::initialize(global_object);
  18. define_property(vm.names.prototype, global_object.error_prototype(), 0);
  19. define_property(vm.names.length, Value(1), Attribute::Configurable);
  20. }
  21. Value ErrorConstructor::call()
  22. {
  23. return construct(*this);
  24. }
  25. Value ErrorConstructor::construct(Function&)
  26. {
  27. auto& vm = this->vm();
  28. String message;
  29. if (!vm.argument(0).is_undefined()) {
  30. message = vm.argument(0).to_string(global_object());
  31. if (vm.exception())
  32. return {};
  33. }
  34. return Error::create(global_object(), message);
  35. }
  36. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  37. ConstructorName::ConstructorName(GlobalObject& global_object) \
  38. : NativeFunction(*static_cast<Object*>(global_object.error_constructor())) \
  39. { \
  40. } \
  41. \
  42. void ConstructorName::initialize(GlobalObject& global_object) \
  43. { \
  44. auto& vm = this->vm(); \
  45. NativeFunction::initialize(global_object); \
  46. define_property(vm.names.prototype, global_object.snake_name##_prototype(), 0); \
  47. define_property(vm.names.length, Value(1), Attribute::Configurable); \
  48. } \
  49. \
  50. ConstructorName::~ConstructorName() { } \
  51. \
  52. Value ConstructorName::call() \
  53. { \
  54. return construct(*this); \
  55. } \
  56. \
  57. Value ConstructorName::construct(Function&) \
  58. { \
  59. auto& vm = this->vm(); \
  60. String message = ""; \
  61. if (!vm.argument(0).is_undefined()) { \
  62. message = vm.argument(0).to_string(global_object()); \
  63. if (vm.exception()) \
  64. return {}; \
  65. } \
  66. return ClassName::create(global_object(), message); \
  67. }
  68. JS_ENUMERATE_ERROR_SUBCLASSES
  69. #undef __JS_ENUMERATE
  70. }