CalendarConstructor.cpp 2.4 KB

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