CalendarConstructor.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2021-2023, 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. JS_DEFINE_ALLOCATOR(CalendarConstructor);
  11. // 12.2 The Temporal.Calendar Constructor, https://tc39.es/proposal-temporal/#sec-temporal-calendar-constructor
  12. CalendarConstructor::CalendarConstructor(Realm& realm)
  13. : NativeFunction(realm.vm().names.Calendar.as_string(), realm.intrinsics().function_prototype())
  14. {
  15. }
  16. void CalendarConstructor::initialize(Realm& realm)
  17. {
  18. Base::initialize(realm);
  19. auto& vm = this->vm();
  20. // 12.3.1 Temporal.Calendar.prototype, https://tc39.es/proposal-temporal/#sec-temporal.calendar.prototype
  21. define_direct_property(vm.names.prototype, realm.intrinsics().temporal_calendar_prototype(), 0);
  22. u8 attr = Attribute::Writable | Attribute::Configurable;
  23. define_native_function(realm, vm.names.from, from, 1, attr);
  24. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  25. }
  26. // 12.2.1 Temporal.Calendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal.calendar
  27. ThrowCompletionOr<Value> CalendarConstructor::call()
  28. {
  29. auto& vm = this->vm();
  30. // 1. If NewTarget is undefined, then
  31. // a. Throw a TypeError exception.
  32. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, "Temporal.Calendar");
  33. }
  34. // 12.2.1 Temporal.Calendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal.calendar
  35. ThrowCompletionOr<NonnullGCPtr<Object>> CalendarConstructor::construct(FunctionObject& new_target)
  36. {
  37. auto& vm = this->vm();
  38. // 2. Set id to ? ToString(id).
  39. auto identifier = TRY(vm.argument(0).to_string(vm));
  40. // 3. If IsBuiltinCalendar(id) is false, then
  41. if (!is_builtin_calendar(identifier)) {
  42. // a. Throw a RangeError exception.
  43. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, identifier);
  44. }
  45. // 4. Return ? CreateTemporalCalendar(id, NewTarget).
  46. return *TRY(create_temporal_calendar(vm, identifier, &new_target));
  47. }
  48. // 12.3.2 Temporal.Calendar.from ( calendarLike ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.from
  49. JS_DEFINE_NATIVE_FUNCTION(CalendarConstructor::from)
  50. {
  51. auto calendar_like = vm.argument(0);
  52. // 1. Return ? ToTemporalCalendar(calendarLike).
  53. return TRY(to_temporal_calendar(vm, calendar_like));
  54. }
  55. }