CalendarConstructor.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. 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>(global_object(), 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. auto& global_object = this->global_object();
  38. // 2. Set id to ? ToString(id).
  39. auto identifier = TRY(vm.argument(0).to_string(global_object));
  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>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, identifier);
  44. }
  45. // 4. Return ? CreateTemporalCalendar(id, NewTarget).
  46. return TRY(create_temporal_calendar(global_object, identifier, &new_target));
  47. }
  48. // 12.3.2 Temporal.Calendar.from ( item ), https://tc39.es/proposal-temporal/#sec-temporal.calendar.from
  49. JS_DEFINE_NATIVE_FUNCTION(CalendarConstructor::from)
  50. {
  51. auto item = vm.argument(0);
  52. // 1. Return ? ToTemporalCalendar(item).
  53. return TRY(to_temporal_calendar(global_object, item));
  54. }
  55. }