CalendarConstructor.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/GlobalObject.h>
  7. #include <LibJS/Runtime/Temporal/Calendar.h>
  8. #include <LibJS/Runtime/Temporal/CalendarConstructor.h>
  9. namespace JS::Temporal {
  10. // 12.2 The Temporal.Calendar Constructor, https://tc39.es/proposal-temporal/#sec-temporal-calendar-constructor
  11. CalendarConstructor::CalendarConstructor(GlobalObject& global_object)
  12. : NativeFunction(vm().names.Calendar.as_string(), *global_object.function_prototype())
  13. {
  14. }
  15. void CalendarConstructor::initialize(GlobalObject& global_object)
  16. {
  17. NativeFunction::initialize(global_object);
  18. auto& vm = this->vm();
  19. // 12.3.1 Temporal.Calendar.prototype, https://tc39.es/proposal-temporal/#sec-temporal-calendar-prototype
  20. define_direct_property(vm.names.prototype, global_object.temporal_calendar_prototype(), 0);
  21. u8 attr = Attribute::Writable | Attribute::Configurable;
  22. define_native_function(vm.names.from, from, 1, attr);
  23. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  24. }
  25. // 12.2.1 Temporal.Calendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal.calendar
  26. Value CalendarConstructor::call()
  27. {
  28. auto& vm = this->vm();
  29. // 1. If NewTarget is undefined, then
  30. // a. Throw a TypeError exception.
  31. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, "Temporal.Calendar");
  32. return {};
  33. }
  34. // 12.2.1 Temporal.Calendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal.calendar
  35. Value CalendarConstructor::construct(FunctionObject& new_target)
  36. {
  37. auto& vm = this->vm();
  38. auto& global_object = this->global_object();
  39. // 2. Set id to ? ToString(id).
  40. auto identifier = vm.argument(0).to_string(global_object);
  41. if (vm.exception())
  42. return {};
  43. // 3. If ! IsBuiltinCalendar(id) is false, then
  44. if (!is_builtin_calendar(identifier)) {
  45. // a. Throw a RangeError exception.
  46. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, identifier);
  47. return {};
  48. }
  49. // 4. Return ? CreateTemporalCalendar(id, NewTarget).
  50. return TRY_OR_DISCARD(create_temporal_calendar(global_object, identifier, &new_target));
  51. }
  52. // 12.3.2 Temporal.Calendar.from ( item ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.from
  53. JS_DEFINE_NATIVE_FUNCTION(CalendarConstructor::from)
  54. {
  55. auto item = vm.argument(0);
  56. // 1. Return ? ToTemporalCalendar(item).
  57. return TRY_OR_DISCARD(to_temporal_calendar(global_object, item));
  58. }
  59. }