EncodedJSValue JSC_HOST_CALL IntlCollatorConstructorFuncSupportedLocalesOf(ExecState* state) { // 10.2.2 Intl.Collator.supportedLocalesOf(locales [, options]) (ECMA-402 2.0) // 1. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(*state, state->argument(0)); // 2. ReturnIfAbrupt(requestedLocales). if (state->hadException()) return JSValue::encode(jsUndefined()); // 3. Return SupportedLocales(%Collator%.[[availableLocales]], requestedLocales, options). JSGlobalObject* globalObject = state->callee()->globalObject(); return JSValue::encode(supportedLocales(*state, globalObject->intlCollatorAvailableLocales(), requestedLocales, state->argument(1))); }
EncodedJSValue JSC_HOST_CALL IntlDateTimeFormatConstructorFuncSupportedLocalesOf(ExecState* state) { // 12.2.2 Intl.DateTimeFormat.supportedLocalesOf(locales [, options]) (ECMA-402 2.0) // 1. Let availableLocales be %DateTimeFormat%.[[availableLocales]]. JSGlobalObject* globalObject = state->callee()->globalObject(); const HashSet<String> availableLocales = globalObject->intlDateTimeFormatAvailableLocales(); // 2. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(*state, state->argument(0)); if (state->hadException()) return JSValue::encode(jsUndefined()); // 3. Return SupportedLocales(availableLocales, requestedLocales, options). return JSValue::encode(supportedLocales(*state, availableLocales, requestedLocales, state->argument(1))); }
EncodedJSValue JSC_HOST_CALL IntlCollatorConstructorFuncSupportedLocalesOf(ExecState* state) { VM& vm = state->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 10.2.2 Intl.Collator.supportedLocalesOf(locales [, options]) (ECMA-402 2.0) // 1. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(*state, state->argument(0)); // 2. ReturnIfAbrupt(requestedLocales). RETURN_IF_EXCEPTION(scope, encodedJSValue()); // 3. Return SupportedLocales(%Collator%.[[availableLocales]], requestedLocales, options). JSGlobalObject* globalObject = state->jsCallee()->globalObject(vm); RELEASE_AND_RETURN(scope, JSValue::encode(supportedLocales(*state, globalObject->intlCollatorAvailableLocales(), requestedLocales, state->argument(1)))); }
void IntlNumberFormat::initializeNumberFormat(ExecState& state, JSValue locales, JSValue optionsValue) { VM& vm = state.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 11.1.2 InitializeNumberFormat (numberFormat, locales, options) (ECMA-402) // https://tc39.github.io/ecma402/#sec-initializenumberformat auto requestedLocales = canonicalizeLocaleList(state, locales); RETURN_IF_EXCEPTION(scope, void()); JSObject* options; if (optionsValue.isUndefined()) options = constructEmptyObject(&state, state.lexicalGlobalObject()->nullPrototypeObjectStructure()); else { options = optionsValue.toObject(&state); RETURN_IF_EXCEPTION(scope, void()); } HashMap<String, String> opt; String matcher = intlStringOption(state, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit"); RETURN_IF_EXCEPTION(scope, void()); opt.add("localeMatcher"_s, matcher); auto& availableLocales = state.jsCallee()->globalObject(vm)->intlNumberFormatAvailableLocales(); auto result = resolveLocale(state, availableLocales, requestedLocales, opt, relevantNumberExtensionKeys, WTF_ARRAY_LENGTH(relevantNumberExtensionKeys), IntlNFInternal::localeData); m_locale = result.get("locale"_s); if (m_locale.isEmpty()) { throwTypeError(&state, scope, "failed to initialize NumberFormat due to invalid locale"_s); return; } m_numberingSystem = result.get("nu"_s); String styleString = intlStringOption(state, options, Identifier::fromString(&vm, "style"), { "decimal", "percent", "currency" }, "style must be either \"decimal\", \"percent\", or \"currency\"", "decimal"); RETURN_IF_EXCEPTION(scope, void()); if (styleString == "decimal") m_style = Style::Decimal; else if (styleString == "percent") m_style = Style::Percent; else if (styleString == "currency") m_style = Style::Currency; else ASSERT_NOT_REACHED(); String currency = intlStringOption(state, options, Identifier::fromString(&vm, "currency"), { }, nullptr, nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!currency.isNull()) { if (currency.length() != 3 || !currency.isAllSpecialCharacters<isASCIIAlpha>()) { throwException(&state, scope, createRangeError(&state, "currency is not a well-formed currency code"_s)); return; } } unsigned currencyDigits = 0; if (m_style == Style::Currency) { if (currency.isNull()) { throwTypeError(&state, scope, "currency must be a string"_s); return; } currency = currency.convertToASCIIUppercase(); m_currency = currency; currencyDigits = computeCurrencyDigits(currency); } String currencyDisplayString = intlStringOption(state, options, Identifier::fromString(&vm, "currencyDisplay"), { "code", "symbol", "name" }, "currencyDisplay must be either \"code\", \"symbol\", or \"name\"", "symbol"); RETURN_IF_EXCEPTION(scope, void()); if (m_style == Style::Currency) { if (currencyDisplayString == "code") m_currencyDisplay = CurrencyDisplay::Code; else if (currencyDisplayString == "symbol") m_currencyDisplay = CurrencyDisplay::Symbol; else if (currencyDisplayString == "name") m_currencyDisplay = CurrencyDisplay::Name; else ASSERT_NOT_REACHED(); } unsigned minimumIntegerDigits = intlNumberOption(state, options, Identifier::fromString(&vm, "minimumIntegerDigits"), 1, 21, 1); RETURN_IF_EXCEPTION(scope, void()); m_minimumIntegerDigits = minimumIntegerDigits; unsigned minimumFractionDigitsDefault = (m_style == Style::Currency) ? currencyDigits : 0; unsigned minimumFractionDigits = intlNumberOption(state, options, Identifier::fromString(&vm, "minimumFractionDigits"), 0, 20, minimumFractionDigitsDefault); RETURN_IF_EXCEPTION(scope, void()); m_minimumFractionDigits = minimumFractionDigits; unsigned maximumFractionDigitsDefault; if (m_style == Style::Currency) maximumFractionDigitsDefault = std::max(minimumFractionDigits, currencyDigits); else if (m_style == Style::Percent) maximumFractionDigitsDefault = minimumFractionDigits; else maximumFractionDigitsDefault = std::max(minimumFractionDigits, 3u); unsigned maximumFractionDigits = intlNumberOption(state, options, Identifier::fromString(&vm, "maximumFractionDigits"), minimumFractionDigits, 20, maximumFractionDigitsDefault); RETURN_IF_EXCEPTION(scope, void()); m_maximumFractionDigits = maximumFractionDigits; JSValue minimumSignificantDigitsValue = options->get(&state, Identifier::fromString(&vm, "minimumSignificantDigits")); RETURN_IF_EXCEPTION(scope, void()); JSValue maximumSignificantDigitsValue = options->get(&state, Identifier::fromString(&vm, "maximumSignificantDigits")); RETURN_IF_EXCEPTION(scope, void()); if (!minimumSignificantDigitsValue.isUndefined() || !maximumSignificantDigitsValue.isUndefined()) { unsigned minimumSignificantDigits = intlDefaultNumberOption(state, minimumSignificantDigitsValue, Identifier::fromString(&vm, "minimumSignificantDigits"), 1, 21, 1); RETURN_IF_EXCEPTION(scope, void()); unsigned maximumSignificantDigits = intlDefaultNumberOption(state, maximumSignificantDigitsValue, Identifier::fromString(&vm, "maximumSignificantDigits"), minimumSignificantDigits, 21, 21); RETURN_IF_EXCEPTION(scope, void()); m_minimumSignificantDigits = minimumSignificantDigits; m_maximumSignificantDigits = maximumSignificantDigits; } bool usesFallback; bool useGrouping = intlBooleanOption(state, options, Identifier::fromString(&vm, "useGrouping"), usesFallback); if (usesFallback) useGrouping = true; RETURN_IF_EXCEPTION(scope, void()); m_useGrouping = useGrouping; UNumberFormatStyle style = UNUM_DEFAULT; switch (m_style) { case Style::Decimal: style = UNUM_DECIMAL; break; case Style::Percent: style = UNUM_PERCENT; break; case Style::Currency: switch (m_currencyDisplay) { case CurrencyDisplay::Code: style = UNUM_CURRENCY_ISO; break; case CurrencyDisplay::Symbol: style = UNUM_CURRENCY; break; case CurrencyDisplay::Name: style = UNUM_CURRENCY_PLURAL; break; default: ASSERT_NOT_REACHED(); } break; default: ASSERT_NOT_REACHED(); } UErrorCode status = U_ZERO_ERROR; m_numberFormat = std::unique_ptr<UNumberFormat, UNumberFormatDeleter>(unum_open(style, nullptr, 0, m_locale.utf8().data(), nullptr, &status)); if (U_FAILURE(status)) { throwTypeError(&state, scope, "failed to initialize NumberFormat"_s); return; } if (m_style == Style::Currency) { unum_setTextAttribute(m_numberFormat.get(), UNUM_CURRENCY_CODE, StringView(m_currency).upconvertedCharacters(), m_currency.length(), &status); if (U_FAILURE(status)) { throwTypeError(&state, scope, "failed to initialize NumberFormat"_s); return; } } if (!m_minimumSignificantDigits) { unum_setAttribute(m_numberFormat.get(), UNUM_MIN_INTEGER_DIGITS, m_minimumIntegerDigits); unum_setAttribute(m_numberFormat.get(), UNUM_MIN_FRACTION_DIGITS, m_minimumFractionDigits); unum_setAttribute(m_numberFormat.get(), UNUM_MAX_FRACTION_DIGITS, m_maximumFractionDigits); } else { unum_setAttribute(m_numberFormat.get(), UNUM_SIGNIFICANT_DIGITS_USED, true); unum_setAttribute(m_numberFormat.get(), UNUM_MIN_SIGNIFICANT_DIGITS, m_minimumSignificantDigits); unum_setAttribute(m_numberFormat.get(), UNUM_MAX_SIGNIFICANT_DIGITS, m_maximumSignificantDigits); } unum_setAttribute(m_numberFormat.get(), UNUM_GROUPING_USED, m_useGrouping); unum_setAttribute(m_numberFormat.get(), UNUM_ROUNDING_MODE, UNUM_ROUND_HALFUP); m_initializedNumberFormat = true; }
void IntlCollator::initializeCollator(ExecState& state, JSValue locales, JSValue optionsValue) { // 10.1.1 InitializeCollator (collator, locales, options) (ECMA-402 2.0) // 1. If collator has an [[initializedIntlObject]] internal slot with value true, throw a TypeError exception. // 2. Set collator.[[initializedIntlObject]] to true. // 3. Let requestedLocales be CanonicalizeLocaleList(locales). auto requestedLocales = canonicalizeLocaleList(state, locales); // 4. ReturnIfAbrupt(requestedLocales). if (state.hadException()) return; // 5. If options is undefined, then JSObject* options; if (optionsValue.isUndefined()) { // a. Let options be ObjectCreate(%ObjectPrototype%). options = constructEmptyObject(&state); } else { // 6. Else // a. Let options be ToObject(options). options = optionsValue.toObject(&state); // b. ReturnIfAbrupt(options). if (state.hadException()) return; } // 7. Let u be GetOption(options, "usage", "string", «"sort", "search"», "sort"). String usageString = intlStringOption(state, options, state.vm().propertyNames->usage, { "sort", "search" }, "usage must be either \"sort\" or \"search\"", "sort"); // 8. ReturnIfAbrupt(u). if (state.hadException()) return; // 9. Set collator.[[usage]] to u. if (usageString == "sort") m_usage = Usage::Sort; else if (usageString == "search") m_usage = Usage::Search; else ASSERT_NOT_REACHED(); // 10. If u is "sort", then // a. Let localeData be the value of %Collator%.[[sortLocaleData]]; // 11. Else // a. Let localeData be the value of %Collator%.[[searchLocaleData]]. Vector<String> (*localeData)(const String&, size_t); if (m_usage == Usage::Sort) localeData = sortLocaleData; else localeData = searchLocaleData; // 12. Let opt be a new Record. HashMap<String, String> opt; // 13. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit"). String matcher = intlStringOption(state, options, state.vm().propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit"); // 14. ReturnIfAbrupt(matcher). if (state.hadException()) return; // 15. Set opt.[[localeMatcher]] to matcher. opt.add(ASCIILiteral("localeMatcher"), matcher); // 16. For each row in Table 1, except the header row, do: // a. Let key be the name given in the Key column of the row. // b. Let prop be the name given in the Property column of the row. // c. Let type be the string given in the Type column of the row. // d. Let list be a List containing the Strings given in the Values column of the row, or undefined if no strings are given. // e. Let value be GetOption(options, prop, type, list, undefined). // f. ReturnIfAbrupt(value). // g. If the string given in the Type column of the row is "boolean" and value is not undefined, then // i. Let value be ToString(value). // ii. ReturnIfAbrupt(value). // h. Set opt.[[<key>]] to value. { String numericString; bool usesFallback; bool numeric = intlBooleanOption(state, options, state.vm().propertyNames->numeric, usesFallback); if (state.hadException()) return; if (!usesFallback) numericString = ASCIILiteral(numeric ? "true" : "false"); opt.add(ASCIILiteral("kn"), numericString); } { String caseFirst = intlStringOption(state, options, state.vm().propertyNames->caseFirst, { "upper", "lower", "false" }, "caseFirst must be either \"upper\", \"lower\", or \"false\"", nullptr); if (state.hadException()) return; opt.add(ASCIILiteral("kf"), caseFirst); } // 17. Let relevantExtensionKeys be the value of %Collator%.[[relevantExtensionKeys]]. // 18. Let r be ResolveLocale(%Collator%.[[availableLocales]], requestedLocales, opt, relevantExtensionKeys, localeData). auto& availableLocales = state.callee()->globalObject()->intlCollatorAvailableLocales(); auto result = resolveLocale(state, availableLocales, requestedLocales, opt, relevantExtensionKeys, WTF_ARRAY_LENGTH(relevantExtensionKeys), localeData); // 19. Set collator.[[locale]] to the value of r.[[locale]]. m_locale = result.get(ASCIILiteral("locale")); // 20. Let k be 0. // 21. Let lenValue be Get(relevantExtensionKeys, "length"). // 22. Let len be ToLength(lenValue). // 23. Repeat while k < len: // a. Let Pk be ToString(k). // b. Let key be Get(relevantExtensionKeys, Pk). // c. ReturnIfAbrupt(key). // d. If key is "co", then // i. Let property be "collation". // ii. Let value be the value of r.[[co]]. // iii. If value is null, let value be "default". // e. Else use the row of Table 1 that contains the value of key in the Key column: // i. Let property be the name given in the Property column of the row. // ii. Let value be the value of r.[[<key>]]. // iii. If the name given in the Type column of the row is "boolean", let value be the result of comparing value with "true". // f. Set collator.[[<property>]] to value. // g. Increase k by 1. const String& collation = result.get(ASCIILiteral("co")); m_collation = collation.isNull() ? ASCIILiteral("default") : collation; m_numeric = (result.get(ASCIILiteral("kn")) == "true"); // 24. Let s be GetOption(options, "sensitivity", "string", «"base", "accent", "case", "variant"», undefined). String sensitivityString = intlStringOption(state, options, state.vm().propertyNames->sensitivity, { "base", "accent", "case", "variant" }, "sensitivity must be either \"base\", \"accent\", \"case\", or \"variant\"", nullptr); // 25. ReturnIfAbrupt(s). if (state.hadException()) return; // 26. If s is undefined, then // a. If u is "sort", then let s be "variant". // b. Else // i. Let dataLocale be the value of r.[[dataLocale]]. // ii. Let dataLocaleData be Get(localeData, dataLocale). // iii. Let s be Get(dataLocaleData, "sensitivity"). // 10.2.3 "[[searchLocaleData]][locale] must have a sensitivity property with a String value equal to "base", "accent", "case", or "variant" for all locale values." // 27. Set collator.[[sensitivity]] to s. if (sensitivityString == "base") m_sensitivity = Sensitivity::Base; else if (sensitivityString == "accent") m_sensitivity = Sensitivity::Accent; else if (sensitivityString == "case") m_sensitivity = Sensitivity::Case; else m_sensitivity = Sensitivity::Variant; // 28. Let ip be GetOption(options, "ignorePunctuation", "boolean", undefined, false). bool usesFallback; bool ignorePunctuation = intlBooleanOption(state, options, state.vm().propertyNames->ignorePunctuation, usesFallback); if (usesFallback) ignorePunctuation = false; // 29. ReturnIfAbrupt(ip). if (state.hadException()) return; // 30. Set collator.[[ignorePunctuation]] to ip. m_ignorePunctuation = ignorePunctuation; // 31. Set collator.[[boundCompare]] to undefined. // 32. Set collator.[[initializedCollator]] to true. m_initializedCollator = true; // 33. Return collator. }
void IntlDateTimeFormat::initializeDateTimeFormat(ExecState& exec, JSValue locales, JSValue originalOptions) { VM& vm = exec.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 12.1.1 InitializeDateTimeFormat (dateTimeFormat, locales, options) (ECMA-402 2.0) // 1. If dateTimeFormat.[[initializedIntlObject]] is true, throw a TypeError exception. // 2. Set dateTimeFormat.[[initializedIntlObject]] to true. // 3. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(exec, locales); // 4. ReturnIfAbrupt(requestedLocales), RETURN_IF_EXCEPTION(scope, void()); // 5. Let options be ToDateTimeOptions(options, "any", "date"). JSObject* options = toDateTimeOptionsAnyDate(exec, originalOptions); // 6. ReturnIfAbrupt(options). RETURN_IF_EXCEPTION(scope, void()); // 7. Let opt be a new Record. HashMap<String, String> localeOpt; // 8. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit"). String localeMatcher = intlStringOption(exec, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit"); // 9. ReturnIfAbrupt(matcher). RETURN_IF_EXCEPTION(scope, void()); // 10. Set opt.[[localeMatcher]] to matcher. localeOpt.add(vm.propertyNames->localeMatcher.string(), localeMatcher); // 11. Let localeData be the value of %DateTimeFormat%.[[localeData]]. // 12. Let r be ResolveLocale( %DateTimeFormat%.[[availableLocales]], requestedLocales, opt, %DateTimeFormat%.[[relevantExtensionKeys]], localeData). const HashSet<String> availableLocales = exec.jsCallee()->globalObject()->intlDateTimeFormatAvailableLocales(); HashMap<String, String> resolved = resolveLocale(exec, availableLocales, requestedLocales, localeOpt, relevantExtensionKeys, WTF_ARRAY_LENGTH(relevantExtensionKeys), localeData); // 13. Set dateTimeFormat.[[locale]] to the value of r.[[locale]]. m_locale = resolved.get(vm.propertyNames->locale.string()); if (m_locale.isEmpty()) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat due to invalid locale")); return; } // 14. Set dateTimeFormat.[[calendar]] to the value of r.[[ca]]. m_calendar = resolved.get(ASCIILiteral("ca")); // Switch to preferred aliases. if (m_calendar == "gregory") m_calendar = ASCIILiteral("gregorian"); else if (m_calendar == "islamicc") m_calendar = ASCIILiteral("islamic-civil"); else if (m_calendar == "ethioaa") m_calendar = ASCIILiteral("ethiopic-amete-alem"); // 15. Set dateTimeFormat.[[numberingSystem]] to the value of r.[[nu]]. m_numberingSystem = resolved.get(ASCIILiteral("nu")); // 16. Let dataLocale be the value of r.[[dataLocale]]. String dataLocale = resolved.get(ASCIILiteral("dataLocale")); // 17. Let tz be Get(options, "timeZone"). JSValue tzValue = options->get(&exec, vm.propertyNames->timeZone); // 18. ReturnIfAbrupt(tz). RETURN_IF_EXCEPTION(scope, void()); // 19. If tz is not undefined, then String tz; if (!tzValue.isUndefined()) { // a. Let tz be ToString(tz). String originalTz = tzValue.toWTFString(&exec); // b. ReturnIfAbrupt(tz). RETURN_IF_EXCEPTION(scope, void()); // c. If the result of IsValidTimeZoneName(tz) is false, then i. Throw a RangeError exception. // d. Let tz be CanonicalizeTimeZoneName(tz). tz = canonicalizeTimeZoneName(originalTz); if (tz.isNull()) { throwRangeError(&exec, scope, String::format("invalid time zone: %s", originalTz.utf8().data())); return; } } else { // 20. Else, // a. Let tz be DefaultTimeZone(). tz = defaultTimeZone(); } // 21. Set dateTimeFormat.[[timeZone]] to tz. m_timeZone = tz; // 22. Let opt be a new Record. // Rather than building a record, build the skeleton pattern. StringBuilder skeletonBuilder; // 23. For each row of Table 3, except the header row, do: // a. Let prop be the name given in the Property column of the row. // b. Let value be GetOption(options, prop, "string", «the strings given in the Values column of the row», undefined). // c. ReturnIfAbrupt(value). // d. Set opt.[[<prop>]] to value. auto narrowShortLong = { "narrow", "short", "long" }; auto twoDigitNumeric = { "2-digit", "numeric" }; auto twoDigitNumericNarrowShortLong = { "2-digit", "numeric", "narrow", "short", "long" }; auto shortLong = { "short", "long" }; String weekday = intlStringOption(exec, options, vm.propertyNames->weekday, narrowShortLong, "weekday must be \"narrow\", \"short\", or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!weekday.isNull()) { if (weekday == "narrow") skeletonBuilder.appendLiteral("EEEEE"); else if (weekday == "short") skeletonBuilder.appendLiteral("EEE"); else if (weekday == "long") skeletonBuilder.appendLiteral("EEEE"); } String era = intlStringOption(exec, options, vm.propertyNames->era, narrowShortLong, "era must be \"narrow\", \"short\", or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!era.isNull()) { if (era == "narrow") skeletonBuilder.appendLiteral("GGGGG"); else if (era == "short") skeletonBuilder.appendLiteral("GGG"); else if (era == "long") skeletonBuilder.appendLiteral("GGGG"); } String year = intlStringOption(exec, options, vm.propertyNames->year, twoDigitNumeric, "year must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!year.isNull()) { if (year == "2-digit") skeletonBuilder.appendLiteral("yy"); else if (year == "numeric") skeletonBuilder.append('y'); } String month = intlStringOption(exec, options, vm.propertyNames->month, twoDigitNumericNarrowShortLong, "month must be \"2-digit\", \"numeric\", \"narrow\", \"short\", or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!month.isNull()) { if (month == "2-digit") skeletonBuilder.appendLiteral("MM"); else if (month == "numeric") skeletonBuilder.append('M'); else if (month == "narrow") skeletonBuilder.appendLiteral("MMMMM"); else if (month == "short") skeletonBuilder.appendLiteral("MMM"); else if (month == "long") skeletonBuilder.appendLiteral("MMMM"); } String day = intlStringOption(exec, options, vm.propertyNames->day, twoDigitNumeric, "day must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!day.isNull()) { if (day == "2-digit") skeletonBuilder.appendLiteral("dd"); else if (day == "numeric") skeletonBuilder.append('d'); } String hour = intlStringOption(exec, options, vm.propertyNames->hour, twoDigitNumeric, "hour must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); // We need hour12 to make the hour skeleton pattern decision, so do this early. // 32. Let hr12 be GetOption(options, "hour12", "boolean", undefined, undefined). bool isHour12Undefined; bool hr12 = intlBooleanOption(exec, options, vm.propertyNames->hour12, isHour12Undefined); // 33. ReturnIfAbrupt(hr12). RETURN_IF_EXCEPTION(scope, void()); if (!hour.isNull()) { if (isHour12Undefined) { if (hour == "2-digit") skeletonBuilder.appendLiteral("jj"); else if (hour == "numeric") skeletonBuilder.append('j'); } else if (hr12) { if (hour == "2-digit") skeletonBuilder.appendLiteral("hh"); else if (hour == "numeric") skeletonBuilder.append('h'); } else { if (hour == "2-digit") skeletonBuilder.appendLiteral("HH"); else if (hour == "numeric") skeletonBuilder.append('H'); } } String minute = intlStringOption(exec, options, vm.propertyNames->minute, twoDigitNumeric, "minute must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!minute.isNull()) { if (minute == "2-digit") skeletonBuilder.appendLiteral("mm"); else if (minute == "numeric") skeletonBuilder.append('m'); } String second = intlStringOption(exec, options, vm.propertyNames->second, twoDigitNumeric, "second must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!second.isNull()) { if (second == "2-digit") skeletonBuilder.appendLiteral("ss"); else if (second == "numeric") skeletonBuilder.append('s'); } String timeZoneName = intlStringOption(exec, options, vm.propertyNames->timeZoneName, shortLong, "timeZoneName must be \"short\" or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!timeZoneName.isNull()) { if (timeZoneName == "short") skeletonBuilder.append('z'); else if (timeZoneName == "long") skeletonBuilder.appendLiteral("zzzz"); } // 24. Let dataLocaleData be Get(localeData, dataLocale). // 25. Let formats be Get(dataLocaleData, "formats"). // 26. Let matcher be GetOption(options, "formatMatcher", "string", «"basic", "best fit"», "best fit"). intlStringOption(exec, options, vm.propertyNames->formatMatcher, { "basic", "best fit" }, "formatMatcher must be either \"basic\" or \"best fit\"", "best fit"); // 27. ReturnIfAbrupt(matcher). RETURN_IF_EXCEPTION(scope, void()); // Always use ICU date format generator, rather than our own pattern list and matcher. // Covers steps 28-36. UErrorCode status = U_ZERO_ERROR; UDateTimePatternGenerator* generator = udatpg_open(dataLocale.utf8().data(), &status); if (U_FAILURE(status)) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat")); return; } String skeleton = skeletonBuilder.toString(); StringView skeletonView(skeleton); Vector<UChar, 32> patternBuffer(32); status = U_ZERO_ERROR; auto patternLength = udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternBuffer.size(), &status); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; patternBuffer.grow(patternLength); udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternLength, &status); } udatpg_close(generator); if (U_FAILURE(status)) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat")); return; } StringView pattern(patternBuffer.data(), patternLength); setFormatsFromPattern(pattern); status = U_ZERO_ERROR; StringView timeZoneView(m_timeZone); m_dateFormat = std::unique_ptr<UDateFormat, UDateFormatDeleter>(udat_open(UDAT_PATTERN, UDAT_PATTERN, m_locale.utf8().data(), timeZoneView.upconvertedCharacters(), timeZoneView.length(), pattern.upconvertedCharacters(), pattern.length(), &status)); if (U_FAILURE(status)) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat")); return; } // 37. Set dateTimeFormat.[[boundFormat]] to undefined. // Already undefined. // 38. Set dateTimeFormat.[[initializedDateTimeFormat]] to true. m_initializedDateTimeFormat = true; // 39. Return dateTimeFormat. }
static IntlCollator* initializeCollator(ExecState& state, IntlCollator& collator, JSValue locales, JSValue optionsValue) { // 10.1.1 InitializeCollator (collator, locales, options) (ECMA-402 2.0) // 1. If collator has an [[initializedIntlObject]] internal slot with value true, throw a TypeError exception. // 2. Set collator.[[initializedIntlObject]] to true. // 3. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(state, locales); // 4. ReturnIfAbrupt(requestedLocales). if (state.hadException()) return nullptr; // 5. If options is undefined, then JSObject* options; if (optionsValue.isUndefined()) { // a. Let options be ObjectCreate(%ObjectPrototype%). options = constructEmptyObject(&state); } else { // 6. Else // a. Let options be ToObject(options). options = optionsValue.toObject(&state); // b. ReturnIfAbrupt(options). if (state.hadException()) return nullptr; } // 7. Let u be GetOption(options, "usage", "string", «"sort", "search"», "sort"). const HashSet<String> usages({ ASCIILiteral("sort"), ASCIILiteral("search") }); String usage = intlStringOption(state, options, state.vm().propertyNames->usage, usages, "usage must be either \"sort\" or \"search\"", ASCIILiteral("sort")); // 8. ReturnIfAbrupt(u). if (state.hadException()) return nullptr; // 9. Set collator.[[usage]] to u. collator.setUsage(usage); // 10. If u is "sort", then // a. Let localeData be the value of %Collator%.[[sortLocaleData]]; // 11. Else // a. Let localeData be the value of %Collator%.[[searchLocaleData]]. Vector<String> (*localeData)(const String&, const String&); if (usage == "sort") localeData = sortLocaleData; else localeData = searchLocaleData; // 12. Let opt be a new Record. HashMap<String, String> opt; // 13. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit"). const HashSet<String> matchers({ ASCIILiteral("lookup"), ASCIILiteral("best fit") }); String matcher = intlStringOption(state, options, state.vm().propertyNames->localeMatcher, matchers, "localeMatcher must be either \"lookup\" or \"best fit\"", ASCIILiteral("best fit")); // 14. ReturnIfAbrupt(matcher). if (state.hadException()) return nullptr; // 15. Set opt.[[localeMatcher]] to matcher. opt.set(ASCIILiteral("localeMatcher"), matcher); // 16. For each row in Table 1, except the header row, do: // a. Let key be the name given in the Key column of the row. // b. Let prop be the name given in the Property column of the row. // c. Let type be the string given in the Type column of the row. // d. Let list be a List containing the Strings given in the Values column of the row, or undefined if no strings are given. // e. Let value be GetOption(options, prop, type, list, undefined). // f. ReturnIfAbrupt(value). // g. If the string given in the Type column of the row is "boolean" and value is not undefined, then // i. Let value be ToString(value). // ii. ReturnIfAbrupt(value). // h. Set opt.[[<key>]] to value. { String numericString; bool usesFallback; bool numeric = intlBooleanOption(state, options, state.vm().propertyNames->numeric, usesFallback); if (state.hadException()) return nullptr; if (!usesFallback) numericString = ASCIILiteral(numeric ? "true" : "false"); opt.set(ASCIILiteral("kn"), numericString); } { const HashSet<String> caseFirsts({ ASCIILiteral("upper"), ASCIILiteral("lower"), ASCIILiteral("false") }); String caseFirst = intlStringOption(state, options, state.vm().propertyNames->caseFirst, caseFirsts, "caseFirst must be either \"upper\", \"lower\", or \"false\"", String()); if (state.hadException()) return nullptr; opt.set(ASCIILiteral("kf"), caseFirst); } // 17. Let relevantExtensionKeys be the value of %Collator%.[[relevantExtensionKeys]]. // FIXME: Implement kf (caseFirst). const Vector<String> relevantExtensionKeys { ASCIILiteral("co"), ASCIILiteral("kn") }; // 18. Let r be ResolveLocale(%Collator%.[[availableLocales]], requestedLocales, opt, relevantExtensionKeys, localeData). const HashSet<String>& availableLocales = state.callee()->globalObject()->intlCollatorAvailableLocales(); HashMap<String, String> result = resolveLocale(availableLocales, requestedLocales, opt, relevantExtensionKeys, localeData); // 19. Set collator.[[locale]] to the value of r.[[locale]]. collator.setLocale(result.get(ASCIILiteral("locale"))); // 20. Let k be 0. // 21. Let lenValue be Get(relevantExtensionKeys, "length"). // 22. Let len be ToLength(lenValue). // 23. Repeat while k < len: // a. Let Pk be ToString(k). // b. Let key be Get(relevantExtensionKeys, Pk). // c. ReturnIfAbrupt(key). // d. If key is "co", then // i. Let property be "collation". // ii. Let value be the value of r.[[co]]. // iii. If value is null, let value be "default". // e. Else use the row of Table 1 that contains the value of key in the Key column: // i. Let property be the name given in the Property column of the row. // ii. Let value be the value of r.[[<key>]]. // iii. If the name given in the Type column of the row is "boolean", let value be the result of comparing value with "true". // f. Set collator.[[<property>]] to value. // g. Increase k by 1. ASSERT(relevantExtensionKeys.size() == 2); { ASSERT(relevantExtensionKeys[0] == "co"); const String& value = result.get(ASCIILiteral("co")); collator.setCollation(value.isNull() ? ASCIILiteral("default") : value); } { ASSERT(relevantExtensionKeys[1] == "kn"); const String& value = result.get(ASCIILiteral("kn")); collator.setNumeric(value == "true"); } // 24. Let s be GetOption(options, "sensitivity", "string", «"base", "accent", "case", "variant"», undefined). const HashSet<String> sensitivities({ ASCIILiteral("base"), ASCIILiteral("accent"), ASCIILiteral("case"), ASCIILiteral("variant") }); String sensitivity = intlStringOption(state, options, state.vm().propertyNames->sensitivity, sensitivities, "sensitivity must be either \"base\", \"accent\", \"case\", or \"variant\"", String()); // 25. ReturnIfAbrupt(s). if (state.hadException()) return nullptr; // 26. If s is undefined, then if (sensitivity.isNull()) { // a. If u is "sort", then let s be "variant". if (usage == "sort") sensitivity = ASCIILiteral("variant"); else { // b. Else // i. Let dataLocale be the value of r.[[dataLocale]]. // ii. Let dataLocaleData be Get(localeData, dataLocale). // iii. Let s be Get(dataLocaleData, "sensitivity"). const String& dataLocale = result.get(ASCIILiteral("dataLocale")); sensitivity = localeData(dataLocale, ASCIILiteral("sensitivity"))[0]; } } // 27. Set collator.[[sensitivity]] to s. collator.setSensitivity(sensitivity); // 28. Let ip be GetOption(options, "ignorePunctuation", "boolean", undefined, false). bool usesFallback; bool ignorePunctuation = intlBooleanOption(state, options, state.vm().propertyNames->ignorePunctuation, usesFallback); if (usesFallback) ignorePunctuation = false; // 29. ReturnIfAbrupt(ip). if (state.hadException()) return nullptr; // 30. Set collator.[[ignorePunctuation]] to ip. collator.setIgnorePunctuation(ignorePunctuation); // 31. Set collator.[[boundCompare]] to undefined. // 32. Set collator.[[initializedCollator]] to true. // 33. Return collator. return &collator; }
void IntlPluralRules::initializePluralRules(ExecState& exec, JSValue locales, JSValue optionsValue) { VM& vm = exec.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 13.1.1 InitializePluralRules (pluralRules, locales, options) // https://tc39.github.io/ecma402/#sec-initializepluralrules Vector<String> requestedLocales = canonicalizeLocaleList(exec, locales); RETURN_IF_EXCEPTION(scope, void()); JSObject* options; if (optionsValue.isUndefined()) options = constructEmptyObject(&exec, exec.lexicalGlobalObject()->nullPrototypeObjectStructure()); else { options = optionsValue.toObject(&exec); RETURN_IF_EXCEPTION(scope, void()); } HashMap<String, String> localeOpt; String localeMatcher = intlStringOption(exec, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit"); RETURN_IF_EXCEPTION(scope, void()); localeOpt.add(vm.propertyNames->localeMatcher.string(), localeMatcher); const HashSet<String> availableLocales = exec.jsCallee()->globalObject(vm)->intlNumberFormatAvailableLocales(); HashMap<String, String> resolved = resolveLocale(exec, availableLocales, requestedLocales, localeOpt, nullptr, 0, IntlPRInternal::localeData); m_locale = resolved.get(vm.propertyNames->locale.string()); if (m_locale.isEmpty()) { throwTypeError(&exec, scope, "failed to initialize PluralRules due to invalid locale"_s); return; } String typeString = intlStringOption(exec, options, Identifier::fromString(&vm, "type"), { "cardinal", "ordinal" }, "type must be \"cardinal\" or \"ordinal\"", "cardinal"); RETURN_IF_EXCEPTION(scope, void()); m_type = typeString == "ordinal" ? UPLURAL_TYPE_ORDINAL : UPLURAL_TYPE_CARDINAL; unsigned minimumIntegerDigits = intlNumberOption(exec, options, Identifier::fromString(&vm, "minimumIntegerDigits"), 1, 21, 1); RETURN_IF_EXCEPTION(scope, void()); m_minimumIntegerDigits = minimumIntegerDigits; unsigned minimumFractionDigitsDefault = 0; unsigned minimumFractionDigits = intlNumberOption(exec, options, Identifier::fromString(&vm, "minimumFractionDigits"), 0, 20, minimumFractionDigitsDefault); RETURN_IF_EXCEPTION(scope, void()); m_minimumFractionDigits = minimumFractionDigits; unsigned maximumFractionDigitsDefault = std::max(minimumFractionDigits, 3u); unsigned maximumFractionDigits = intlNumberOption(exec, options, Identifier::fromString(&vm, "maximumFractionDigits"), minimumFractionDigits, 20, maximumFractionDigitsDefault); RETURN_IF_EXCEPTION(scope, void()); m_maximumFractionDigits = maximumFractionDigits; JSValue minimumSignificantDigitsValue = options->get(&exec, Identifier::fromString(&vm, "minimumSignificantDigits")); RETURN_IF_EXCEPTION(scope, void()); JSValue maximumSignificantDigitsValue = options->get(&exec, Identifier::fromString(&vm, "maximumSignificantDigits")); RETURN_IF_EXCEPTION(scope, void()); if (!minimumSignificantDigitsValue.isUndefined() || !maximumSignificantDigitsValue.isUndefined()) { unsigned minimumSignificantDigits = intlNumberOption(exec, options, Identifier::fromString(&vm, "minimumSignificantDigits"), 1, 21, 1); RETURN_IF_EXCEPTION(scope, void()); unsigned maximumSignificantDigits = intlNumberOption(exec, options, Identifier::fromString(&vm, "maximumSignificantDigits"), minimumSignificantDigits, 21, 21); RETURN_IF_EXCEPTION(scope, void()); m_minimumSignificantDigits = minimumSignificantDigits; m_maximumSignificantDigits = maximumSignificantDigits; } UErrorCode status = U_ZERO_ERROR; m_numberFormat = std::unique_ptr<UNumberFormat, UNumberFormatDeleter>(unum_open(UNUM_DECIMAL, nullptr, 0, m_locale.utf8().data(), nullptr, &status)); if (U_FAILURE(status)) { throwTypeError(&exec, scope, "failed to initialize PluralRules"_s); return; } if (m_minimumSignificantDigits) { unum_setAttribute(m_numberFormat.get(), UNUM_SIGNIFICANT_DIGITS_USED, true); unum_setAttribute(m_numberFormat.get(), UNUM_MIN_SIGNIFICANT_DIGITS, m_minimumSignificantDigits.value()); unum_setAttribute(m_numberFormat.get(), UNUM_MAX_SIGNIFICANT_DIGITS, m_maximumSignificantDigits.value()); } else { unum_setAttribute(m_numberFormat.get(), UNUM_MIN_INTEGER_DIGITS, m_minimumIntegerDigits); unum_setAttribute(m_numberFormat.get(), UNUM_MIN_FRACTION_DIGITS, m_minimumFractionDigits); unum_setAttribute(m_numberFormat.get(), UNUM_MAX_FRACTION_DIGITS, m_maximumFractionDigits); } status = U_ZERO_ERROR; m_pluralRules = std::unique_ptr<UPluralRules, UPluralRulesDeleter>(uplrules_openForType(m_locale.utf8().data(), m_type, &status)); if (U_FAILURE(status)) { throwTypeError(&exec, scope, "failed to initialize PluralRules"_s); return; } m_initializedPluralRules = true; }