| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
/* Intl.NumberFormat implementation. */ |
| 8 |
|
| 9 |
#include "builtin/intl/NumberFormat.h" |
| 10 |
|
| 11 |
#include "mozilla/Assertions.h" |
| 12 |
#include "mozilla/Casting.h" |
| 13 |
#include "mozilla/FloatingPoint.h" |
| 14 |
#include "mozilla/intl/Locale.h" |
| 15 |
#include "mozilla/intl/MeasureUnit.h" |
| 16 |
#include "mozilla/intl/MeasureUnitGenerated.h" |
| 17 |
#include "mozilla/intl/NumberFormat.h" |
| 18 |
#include "mozilla/intl/NumberingSystem.h" |
| 19 |
#include "mozilla/intl/NumberRangeFormat.h" |
| 20 |
#include "mozilla/Span.h" |
| 21 |
#include "mozilla/TextUtils.h" |
| 22 |
#include "mozilla/UniquePtr.h" |
| 23 |
|
| 24 |
#include <algorithm> |
| 25 |
#include <stddef.h> |
| 26 |
#include <stdint.h> |
| 27 |
#include <string> |
| 28 |
#include <string_view> |
| 29 |
#include <type_traits> |
| 30 |
|
| 31 |
#include "builtin/Array.h" |
| 32 |
#include "builtin/intl/CommonFunctions.h" |
| 33 |
#include "builtin/intl/FormatBuffer.h" |
| 34 |
#include "builtin/intl/LanguageTag.h" |
| 35 |
#include "builtin/intl/RelativeTimeFormat.h" |
| 36 |
#include "gc/GCContext.h" |
| 37 |
#include "js/CharacterEncoding.h" |
| 38 |
#include "js/PropertySpec.h" |
| 39 |
#include "js/RootingAPI.h" |
| 40 |
#include "js/TypeDecls.h" |
| 41 |
#include "util/Text.h" |
| 42 |
#include "vm/BigIntType.h" |
| 43 |
#include "vm/GlobalObject.h" |
| 44 |
#include "vm/JSContext.h" |
| 45 |
#include "vm/PlainObject.h" // js::PlainObject |
| 46 |
#include "vm/StringType.h" |
| 47 |
|
| 48 |
#include "vm/GeckoProfiler-inl.h" |
| 49 |
#include "vm/JSObject-inl.h" |
| 50 |
#include "vm/NativeObject-inl.h" |
| 51 |
|
| 52 |
using namespace js; |
| 53 |
|
| 54 |
using mozilla::AssertedCast; |
| 55 |
|
| 56 |
using js::intl::DateTimeFormatOptions; |
| 57 |
using js::intl::FieldType; |
| 58 |
|
| 59 |
const JSClassOps NumberFormatObject::classOps_ = { |
| 60 |
nullptr, // addProperty |
| 61 |
nullptr, // delProperty |
| 62 |
nullptr, // enumerate |
| 63 |
nullptr, // newEnumerate |
| 64 |
nullptr, // resolve |
| 65 |
nullptr, // mayResolve |
| 66 |
NumberFormatObject::finalize, // finalize |
| 67 |
nullptr, // call |
| 68 |
nullptr, // construct |
| 69 |
nullptr, // trace |
| 70 |
}; |
| 71 |
|
| 72 |
const JSClass NumberFormatObject::class_ = { |
| 73 |
"Intl.NumberFormat", |
| 74 |
JSCLASS_HAS_RESERVED_SLOTS(NumberFormatObject::SLOT_COUNT) | |
| 75 |
JSCLASS_HAS_CACHED_PROTO(JSProto_NumberFormat) | |
| 76 |
JSCLASS_FOREGROUND_FINALIZE, |
| 77 |
&NumberFormatObject::classOps_, |
| 78 |
&NumberFormatObject::classSpec_, |
| 79 |
}; |
| 80 |
|
| 81 |
const JSClass& NumberFormatObject::protoClass_ = PlainObject::class_; |
| 82 |
|
| 83 |
static bool numberFormat_toSource(JSContext* cx, unsigned argc, Value* vp) { |
| 84 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 85 |
args.rval().setString(cx->names().NumberFormat); |
| 86 |
return true; |
| 87 |
} |
| 88 |
|
| 89 |
static const JSFunctionSpec numberFormat_static_methods[] = { |
| 90 |
JS_SELF_HOSTED_FN("supportedLocalesOf", |
| 91 |
"Intl_NumberFormat_supportedLocalesOf", 1, 0), |
| 92 |
JS_FS_END, |
| 93 |
}; |
| 94 |
|
| 95 |
static const JSFunctionSpec numberFormat_methods[] = { |
| 96 |
JS_SELF_HOSTED_FN("resolvedOptions", "Intl_NumberFormat_resolvedOptions", 0, |
| 97 |
0), |
| 98 |
JS_SELF_HOSTED_FN("formatToParts", "Intl_NumberFormat_formatToParts", 1, 0), |
| 99 |
JS_SELF_HOSTED_FN("formatRange", "Intl_NumberFormat_formatRange", 2, 0), |
| 100 |
JS_SELF_HOSTED_FN("formatRangeToParts", |
| 101 |
"Intl_NumberFormat_formatRangeToParts", 2, 0), |
| 102 |
JS_FN("toSource", numberFormat_toSource, 0, 0), |
| 103 |
JS_FS_END, |
| 104 |
}; |
| 105 |
|
| 106 |
static const JSPropertySpec numberFormat_properties[] = { |
| 107 |
JS_SELF_HOSTED_GET("format", "$Intl_NumberFormat_format_get", 0), |
| 108 |
JS_STRING_SYM_PS(toStringTag, "Intl.NumberFormat", JSPROP_READONLY), |
| 109 |
JS_PS_END, |
| 110 |
}; |
| 111 |
|
| 112 |
static bool NumberFormat(JSContext* cx, unsigned argc, Value* vp); |
| 113 |
|
| 114 |
const ClassSpec NumberFormatObject::classSpec_ = { |
| 115 |
GenericCreateConstructor<NumberFormat, 0, gc::AllocKind::FUNCTION>, |
| 116 |
GenericCreatePrototype<NumberFormatObject>, |
| 117 |
numberFormat_static_methods, |
| 118 |
nullptr, |
| 119 |
numberFormat_methods, |
| 120 |
numberFormat_properties, |
| 121 |
nullptr, |
| 122 |
ClassSpec::DontDefineConstructor, |
| 123 |
}; |
| 124 |
|
| 125 |
/** |
| 126 |
* 15.1.1 Intl.NumberFormat ( [ locales [ , options ] ] ) |
| 127 |
* |
| 128 |
* ES2025 Intl draft rev 5ea95f8a98d660e94c177d6f5e88c6d2962123b1 |
| 129 |
*/ |
| 130 |
static bool NumberFormat(JSContext* cx, const CallArgs& args, bool construct) { |
| 131 |
AutoJSConstructorProfilerEntry pseudoFrame(cx, "Intl.NumberFormat"); |
| 132 |
|
| 133 |
// Step 1 (Handled by OrdinaryCreateFromConstructor fallback code). |
| 134 |
|
| 135 |
// Step 2 (Inlined 9.1.14, OrdinaryCreateFromConstructor). |
| 136 |
RootedObject proto(cx); |
| 137 |
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_NumberFormat, |
| 138 |
&proto)) { |
| 139 |
return false; |
| 140 |
} |
| 141 |
|
| 142 |
Rooted<NumberFormatObject*> numberFormat(cx); |
| 143 |
numberFormat = NewObjectWithClassProto<NumberFormatObject>(cx, proto); |
| 144 |
if (!numberFormat) { |
| 145 |
return false; |
| 146 |
} |
| 147 |
|
| 148 |
RootedValue thisValue(cx, |
| 149 |
construct ? ObjectValue(*numberFormat) : args.thisv()); |
| 150 |
HandleValue locales = args.get(0); |
| 151 |
HandleValue options = args.get(1); |
| 152 |
|
| 153 |
// Steps 3-33. |
| 154 |
return intl::InitializeNumberFormatObject(cx, numberFormat, thisValue, |
| 155 |
locales, options, args.rval()); |
| 156 |
} |
| 157 |
|
| 158 |
static bool NumberFormat(JSContext* cx, unsigned argc, Value* vp) { |
| 159 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 160 |
return NumberFormat(cx, args, args.isConstructing()); |
| 161 |
} |
| 162 |
|
| 163 |
bool js::intl_NumberFormat(JSContext* cx, unsigned argc, Value* vp) { |
| 164 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 165 |
MOZ_ASSERT(args.length() == 2); |
| 166 |
MOZ_ASSERT(!args.isConstructing()); |
| 167 |
// intl_NumberFormat is an intrinsic for self-hosted JavaScript, so it |
| 168 |
// cannot be used with "new", but it still has to be treated as a |
| 169 |
// constructor. |
| 170 |
return NumberFormat(cx, args, true); |
| 171 |
} |
| 172 |
|
| 173 |
void js::NumberFormatObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 174 |
MOZ_ASSERT(gcx->onMainThread()); |
| 175 |
|
| 176 |
auto* numberFormat = &obj->as<NumberFormatObject>(); |
| 177 |
mozilla::intl::NumberFormat* nf = numberFormat->getNumberFormatter(); |
| 178 |
mozilla::intl::NumberRangeFormat* nrf = |
| 179 |
numberFormat->getNumberRangeFormatter(); |
| 180 |
|
| 181 |
if (nf) { |
| 182 |
intl::RemoveICUCellMemory(gcx, obj, NumberFormatObject::EstimatedMemoryUse); |
| 183 |
// This was allocated using `new` in mozilla::intl::NumberFormat, so we |
| 184 |
// delete here. |
| 185 |
delete nf; |
| 186 |
} |
| 187 |
|
| 188 |
if (nrf) { |
| 189 |
intl::RemoveICUCellMemory(gcx, obj, EstimatedRangeFormatterMemoryUse); |
| 190 |
// This was allocated using `new` in mozilla::intl::NumberRangeFormat, so we |
| 191 |
// delete here. |
| 192 |
delete nrf; |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
bool js::intl_numberingSystem(JSContext* cx, unsigned argc, Value* vp) { |
| 197 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 198 |
MOZ_ASSERT(args.length() == 1); |
| 199 |
MOZ_ASSERT(args[0].isString()); |
| 200 |
|
| 201 |
UniqueChars locale = intl::EncodeLocale(cx, args[0].toString()); |
| 202 |
if (!locale) { |
| 203 |
return false; |
| 204 |
} |
| 205 |
|
| 206 |
auto numberingSystem = |
| 207 |
mozilla::intl::NumberingSystem::TryCreate(locale.get()); |
| 208 |
if (numberingSystem.isErr()) { |
| 209 |
intl::ReportInternalError(cx, numberingSystem.unwrapErr()); |
| 210 |
return false; |
| 211 |
} |
| 212 |
|
| 213 |
auto name = numberingSystem.inspect()->GetName(); |
| 214 |
if (name.isErr()) { |
| 215 |
intl::ReportInternalError(cx, name.unwrapErr()); |
| 216 |
return false; |
| 217 |
} |
| 218 |
|
| 219 |
JSString* jsname = NewStringCopy<CanGC>(cx, name.unwrap()); |
| 220 |
if (!jsname) { |
| 221 |
return false; |
| 222 |
} |
| 223 |
|
| 224 |
args.rval().setString(jsname); |
| 225 |
return true; |
| 226 |
} |
| 227 |
|
| 228 |
#if DEBUG || MOZ_SYSTEM_ICU |
| 229 |
bool js::intl_availableMeasurementUnits(JSContext* cx, unsigned argc, |
| 230 |
Value* vp) { |
| 231 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 232 |
MOZ_ASSERT(args.length() == 0); |
| 233 |
|
| 234 |
RootedObject measurementUnits(cx, NewPlainObjectWithProto(cx, nullptr)); |
| 235 |
if (!measurementUnits) { |
| 236 |
return false; |
| 237 |
} |
| 238 |
|
| 239 |
auto units = mozilla::intl::MeasureUnit::GetAvailable(); |
| 240 |
if (units.isErr()) { |
| 241 |
intl::ReportInternalError(cx, units.unwrapErr()); |
| 242 |
return false; |
| 243 |
} |
| 244 |
|
| 245 |
Rooted<JSAtom*> unitAtom(cx); |
| 246 |
for (auto unit : units.unwrap()) { |
| 247 |
if (unit.isErr()) { |
| 248 |
intl::ReportInternalError(cx); |
| 249 |
return false; |
| 250 |
} |
| 251 |
auto unitIdentifier = unit.unwrap(); |
| 252 |
|
| 253 |
unitAtom = Atomize(cx, unitIdentifier.data(), unitIdentifier.size()); |
| 254 |
if (!unitAtom) { |
| 255 |
return false; |
| 256 |
} |
| 257 |
|
| 258 |
if (!DefineDataProperty(cx, measurementUnits, unitAtom->asPropertyName(), |
| 259 |
TrueHandleValue)) { |
| 260 |
return false; |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
args.rval().setObject(*measurementUnits); |
| 265 |
return true; |
| 266 |
} |
| 267 |
#endif |
| 268 |
|
| 269 |
static constexpr size_t MaxUnitLength() { |
| 270 |
size_t length = 0; |
| 271 |
for (const auto& unit : mozilla::intl::simpleMeasureUnits) { |
| 272 |
length = std::max(length, std::char_traits<char>::length(unit.name)); |
| 273 |
} |
| 274 |
return length * 2 + std::char_traits<char>::length("-per-"); |
| 275 |
} |
| 276 |
|
| 277 |
static UniqueChars NumberFormatLocale(JSContext* cx, HandleObject internals) { |
| 278 |
RootedValue value(cx); |
| 279 |
if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) { |
| 280 |
return nullptr; |
| 281 |
} |
| 282 |
|
| 283 |
// ICU expects numberingSystem as a Unicode locale extensions on locale. |
| 284 |
|
| 285 |
mozilla::intl::Locale tag; |
| 286 |
{ |
| 287 |
Rooted<JSLinearString*> locale(cx, value.toString()->ensureLinear(cx)); |
| 288 |
if (!locale) { |
| 289 |
return nullptr; |
| 290 |
} |
| 291 |
|
| 292 |
if (!intl::ParseLocale(cx, locale, tag)) { |
| 293 |
return nullptr; |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
JS::RootedVector<intl::UnicodeExtensionKeyword> keywords(cx); |
| 298 |
|
| 299 |
if (!GetProperty(cx, internals, internals, cx->names().numberingSystem, |
| 300 |
&value)) { |
| 301 |
return nullptr; |
| 302 |
} |
| 303 |
|
| 304 |
{ |
| 305 |
JSLinearString* numberingSystem = value.toString()->ensureLinear(cx); |
| 306 |
if (!numberingSystem) { |
| 307 |
return nullptr; |
| 308 |
} |
| 309 |
|
| 310 |
if (!keywords.emplaceBack("nu", numberingSystem)) { |
| 311 |
return nullptr; |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
// |ApplyUnicodeExtensionToTag| applies the new keywords to the front of |
| 316 |
// the Unicode extension subtag. We're then relying on ICU to follow RFC |
| 317 |
// 6067, which states that any trailing keywords using the same key |
| 318 |
// should be ignored. |
| 319 |
if (!intl::ApplyUnicodeExtensionToTag(cx, tag, keywords)) { |
| 320 |
return nullptr; |
| 321 |
} |
| 322 |
|
| 323 |
intl::FormatBuffer<char> buffer(cx); |
| 324 |
if (auto result = tag.ToString(buffer); result.isErr()) { |
| 325 |
intl::ReportInternalError(cx, result.unwrapErr()); |
| 326 |
return nullptr; |
| 327 |
} |
| 328 |
return buffer.extractStringZ(); |
| 329 |
} |
| 330 |
|
| 331 |
struct NumberFormatOptions : public mozilla::intl::NumberRangeFormatOptions { |
| 332 |
static_assert(std::is_base_of_v<mozilla::intl::NumberFormatOptions, |
| 333 |
mozilla::intl::NumberRangeFormatOptions>); |
| 334 |
|
| 335 |
char currencyChars[3] = {}; |
| 336 |
char unitChars[MaxUnitLength()] = {}; |
| 337 |
}; |
| 338 |
|
| 339 |
static bool FillNumberFormatOptions(JSContext* cx, HandleObject internals, |
| 340 |
NumberFormatOptions& options) { |
| 341 |
RootedValue value(cx); |
| 342 |
if (!GetProperty(cx, internals, internals, cx->names().style, &value)) { |
| 343 |
return false; |
| 344 |
} |
| 345 |
|
| 346 |
bool accountingSign = false; |
| 347 |
{ |
| 348 |
JSLinearString* style = value.toString()->ensureLinear(cx); |
| 349 |
if (!style) { |
| 350 |
return false; |
| 351 |
} |
| 352 |
|
| 353 |
if (StringEqualsLiteral(style, "currency")) { |
| 354 |
if (!GetProperty(cx, internals, internals, cx->names().currency, |
| 355 |
&value)) { |
| 356 |
return false; |
| 357 |
} |
| 358 |
JSLinearString* currency = value.toString()->ensureLinear(cx); |
| 359 |
if (!currency) { |
| 360 |
return false; |
| 361 |
} |
| 362 |
|
| 363 |
MOZ_RELEASE_ASSERT( |
| 364 |
currency->length() == 3, |
| 365 |
"IsWellFormedCurrencyCode permits only length-3 strings"); |
| 366 |
MOZ_ASSERT(StringIsAscii(currency), |
| 367 |
"IsWellFormedCurrencyCode permits only ASCII strings"); |
| 368 |
CopyChars(reinterpret_cast<Latin1Char*>(options.currencyChars), |
| 369 |
*currency); |
| 370 |
|
| 371 |
if (!GetProperty(cx, internals, internals, cx->names().currencyDisplay, |
| 372 |
&value)) { |
| 373 |
return false; |
| 374 |
} |
| 375 |
JSLinearString* currencyDisplay = value.toString()->ensureLinear(cx); |
| 376 |
if (!currencyDisplay) { |
| 377 |
return false; |
| 378 |
} |
| 379 |
|
| 380 |
using CurrencyDisplay = |
| 381 |
mozilla::intl::NumberFormatOptions::CurrencyDisplay; |
| 382 |
|
| 383 |
CurrencyDisplay display; |
| 384 |
if (StringEqualsLiteral(currencyDisplay, "code")) { |
| 385 |
display = CurrencyDisplay::Code; |
| 386 |
} else if (StringEqualsLiteral(currencyDisplay, "symbol")) { |
| 387 |
display = CurrencyDisplay::Symbol; |
| 388 |
} else if (StringEqualsLiteral(currencyDisplay, "narrowSymbol")) { |
| 389 |
display = CurrencyDisplay::NarrowSymbol; |
| 390 |
} else { |
| 391 |
MOZ_ASSERT(StringEqualsLiteral(currencyDisplay, "name")); |
| 392 |
display = CurrencyDisplay::Name; |
| 393 |
} |
| 394 |
|
| 395 |
if (!GetProperty(cx, internals, internals, cx->names().currencySign, |
| 396 |
&value)) { |
| 397 |
return false; |
| 398 |
} |
| 399 |
JSLinearString* currencySign = value.toString()->ensureLinear(cx); |
| 400 |
if (!currencySign) { |
| 401 |
return false; |
| 402 |
} |
| 403 |
|
| 404 |
if (StringEqualsLiteral(currencySign, "accounting")) { |
| 405 |
accountingSign = true; |
| 406 |
} else { |
| 407 |
MOZ_ASSERT(StringEqualsLiteral(currencySign, "standard")); |
| 408 |
} |
| 409 |
|
| 410 |
options.mCurrency = mozilla::Some( |
| 411 |
std::make_pair(std::string_view(options.currencyChars, 3), display)); |
| 412 |
} else if (StringEqualsLiteral(style, "percent")) { |
| 413 |
options.mPercent = true; |
| 414 |
} else if (StringEqualsLiteral(style, "unit")) { |
| 415 |
if (!GetProperty(cx, internals, internals, cx->names().unit, &value)) { |
| 416 |
return false; |
| 417 |
} |
| 418 |
JSLinearString* unit = value.toString()->ensureLinear(cx); |
| 419 |
if (!unit) { |
| 420 |
return false; |
| 421 |
} |
| 422 |
|
| 423 |
size_t unit_str_length = unit->length(); |
| 424 |
|
| 425 |
MOZ_ASSERT(StringIsAscii(unit)); |
| 426 |
MOZ_RELEASE_ASSERT(unit_str_length <= MaxUnitLength()); |
| 427 |
CopyChars(reinterpret_cast<Latin1Char*>(options.unitChars), *unit); |
| 428 |
|
| 429 |
if (!GetProperty(cx, internals, internals, cx->names().unitDisplay, |
| 430 |
&value)) { |
| 431 |
return false; |
| 432 |
} |
| 433 |
JSLinearString* unitDisplay = value.toString()->ensureLinear(cx); |
| 434 |
if (!unitDisplay) { |
| 435 |
return false; |
| 436 |
} |
| 437 |
|
| 438 |
using UnitDisplay = mozilla::intl::NumberFormatOptions::UnitDisplay; |
| 439 |
|
| 440 |
UnitDisplay display; |
| 441 |
if (StringEqualsLiteral(unitDisplay, "short")) { |
| 442 |
display = UnitDisplay::Short; |
| 443 |
} else if (StringEqualsLiteral(unitDisplay, "narrow")) { |
| 444 |
display = UnitDisplay::Narrow; |
| 445 |
} else { |
| 446 |
MOZ_ASSERT(StringEqualsLiteral(unitDisplay, "long")); |
| 447 |
display = UnitDisplay::Long; |
| 448 |
} |
| 449 |
|
| 450 |
options.mUnit = mozilla::Some(std::make_pair( |
| 451 |
std::string_view(options.unitChars, unit_str_length), display)); |
| 452 |
} else { |
| 453 |
MOZ_ASSERT(StringEqualsLiteral(style, "decimal")); |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
bool hasMinimumSignificantDigits; |
| 458 |
if (!HasProperty(cx, internals, cx->names().minimumSignificantDigits, |
| 459 |
&hasMinimumSignificantDigits)) { |
| 460 |
return false; |
| 461 |
} |
| 462 |
|
| 463 |
if (hasMinimumSignificantDigits) { |
| 464 |
if (!GetProperty(cx, internals, internals, |
| 465 |
cx->names().minimumSignificantDigits, &value)) { |
| 466 |
return false; |
| 467 |
} |
| 468 |
uint32_t minimumSignificantDigits = AssertedCast<uint32_t>(value.toInt32()); |
| 469 |
|
| 470 |
if (!GetProperty(cx, internals, internals, |
| 471 |
cx->names().maximumSignificantDigits, &value)) { |
| 472 |
return false; |
| 473 |
} |
| 474 |
uint32_t maximumSignificantDigits = AssertedCast<uint32_t>(value.toInt32()); |
| 475 |
|
| 476 |
options.mSignificantDigits = mozilla::Some( |
| 477 |
std::make_pair(minimumSignificantDigits, maximumSignificantDigits)); |
| 478 |
} |
| 479 |
|
| 480 |
bool hasMinimumFractionDigits; |
| 481 |
if (!HasProperty(cx, internals, cx->names().minimumFractionDigits, |
| 482 |
&hasMinimumFractionDigits)) { |
| 483 |
return false; |
| 484 |
} |
| 485 |
|
| 486 |
if (hasMinimumFractionDigits) { |
| 487 |
if (!GetProperty(cx, internals, internals, |
| 488 |
cx->names().minimumFractionDigits, &value)) { |
| 489 |
return false; |
| 490 |
} |
| 491 |
uint32_t minimumFractionDigits = AssertedCast<uint32_t>(value.toInt32()); |
| 492 |
|
| 493 |
if (!GetProperty(cx, internals, internals, |
| 494 |
cx->names().maximumFractionDigits, &value)) { |
| 495 |
return false; |
| 496 |
} |
| 497 |
uint32_t maximumFractionDigits = AssertedCast<uint32_t>(value.toInt32()); |
| 498 |
|
| 499 |
options.mFractionDigits = mozilla::Some( |
| 500 |
std::make_pair(minimumFractionDigits, maximumFractionDigits)); |
| 501 |
} |
| 502 |
|
| 503 |
if (!GetProperty(cx, internals, internals, cx->names().roundingPriority, |
| 504 |
&value)) { |
| 505 |
return false; |
| 506 |
} |
| 507 |
|
| 508 |
{ |
| 509 |
JSLinearString* roundingPriority = value.toString()->ensureLinear(cx); |
| 510 |
if (!roundingPriority) { |
| 511 |
return false; |
| 512 |
} |
| 513 |
|
| 514 |
using RoundingPriority = |
| 515 |
mozilla::intl::NumberFormatOptions::RoundingPriority; |
| 516 |
|
| 517 |
RoundingPriority priority; |
| 518 |
if (StringEqualsLiteral(roundingPriority, "auto")) { |
| 519 |
priority = RoundingPriority::Auto; |
| 520 |
} else if (StringEqualsLiteral(roundingPriority, "morePrecision")) { |
| 521 |
priority = RoundingPriority::MorePrecision; |
| 522 |
} else { |
| 523 |
MOZ_ASSERT(StringEqualsLiteral(roundingPriority, "lessPrecision")); |
| 524 |
priority = RoundingPriority::LessPrecision; |
| 525 |
} |
| 526 |
|
| 527 |
options.mRoundingPriority = priority; |
| 528 |
} |
| 529 |
|
| 530 |
if (!GetProperty(cx, internals, internals, cx->names().minimumIntegerDigits, |
| 531 |
&value)) { |
| 532 |
return false; |
| 533 |
} |
| 534 |
options.mMinIntegerDigits = |
| 535 |
mozilla::Some(AssertedCast<uint32_t>(value.toInt32())); |
| 536 |
|
| 537 |
if (!GetProperty(cx, internals, internals, cx->names().useGrouping, &value)) { |
| 538 |
return false; |
| 539 |
} |
| 540 |
|
| 541 |
if (value.isString()) { |
| 542 |
JSLinearString* useGrouping = value.toString()->ensureLinear(cx); |
| 543 |
if (!useGrouping) { |
| 544 |
return false; |
| 545 |
} |
| 546 |
|
| 547 |
using Grouping = mozilla::intl::NumberFormatOptions::Grouping; |
| 548 |
|
| 549 |
Grouping grouping; |
| 550 |
if (StringEqualsLiteral(useGrouping, "auto")) { |
| 551 |
grouping = Grouping::Auto; |
| 552 |
} else if (StringEqualsLiteral(useGrouping, "always")) { |
| 553 |
grouping = Grouping::Always; |
| 554 |
} else { |
| 555 |
MOZ_ASSERT(StringEqualsLiteral(useGrouping, "min2")); |
| 556 |
grouping = Grouping::Min2; |
| 557 |
} |
| 558 |
|
| 559 |
options.mGrouping = grouping; |
| 560 |
} else { |
| 561 |
MOZ_ASSERT(value.isBoolean()); |
| 562 |
MOZ_ASSERT(value.toBoolean() == false); |
| 563 |
|
| 564 |
using Grouping = mozilla::intl::NumberFormatOptions::Grouping; |
| 565 |
|
| 566 |
options.mGrouping = Grouping::Never; |
| 567 |
} |
| 568 |
|
| 569 |
if (!GetProperty(cx, internals, internals, cx->names().notation, &value)) { |
| 570 |
return false; |
| 571 |
} |
| 572 |
|
| 573 |
{ |
| 574 |
JSLinearString* notation = value.toString()->ensureLinear(cx); |
| 575 |
if (!notation) { |
| 576 |
return false; |
| 577 |
} |
| 578 |
|
| 579 |
using Notation = mozilla::intl::NumberFormatOptions::Notation; |
| 580 |
|
| 581 |
Notation style; |
| 582 |
if (StringEqualsLiteral(notation, "standard")) { |
| 583 |
style = Notation::Standard; |
| 584 |
} else if (StringEqualsLiteral(notation, "scientific")) { |
| 585 |
style = Notation::Scientific; |
| 586 |
} else if (StringEqualsLiteral(notation, "engineering")) { |
| 587 |
style = Notation::Engineering; |
| 588 |
} else { |
| 589 |
MOZ_ASSERT(StringEqualsLiteral(notation, "compact")); |
| 590 |
|
| 591 |
if (!GetProperty(cx, internals, internals, cx->names().compactDisplay, |
| 592 |
&value)) { |
| 593 |
return false; |
| 594 |
} |
| 595 |
|
| 596 |
JSLinearString* compactDisplay = value.toString()->ensureLinear(cx); |
| 597 |
if (!compactDisplay) { |
| 598 |
return false; |
| 599 |
} |
| 600 |
|
| 601 |
if (StringEqualsLiteral(compactDisplay, "short")) { |
| 602 |
style = Notation::CompactShort; |
| 603 |
} else { |
| 604 |
MOZ_ASSERT(StringEqualsLiteral(compactDisplay, "long")); |
| 605 |
style = Notation::CompactLong; |
| 606 |
} |
| 607 |
} |
| 608 |
|
| 609 |
options.mNotation = style; |
| 610 |
} |
| 611 |
|
| 612 |
if (!GetProperty(cx, internals, internals, cx->names().signDisplay, &value)) { |
| 613 |
return false; |
| 614 |
} |
| 615 |
|
| 616 |
{ |
| 617 |
JSLinearString* signDisplay = value.toString()->ensureLinear(cx); |
| 618 |
if (!signDisplay) { |
| 619 |
return false; |
| 620 |
} |
| 621 |
|
| 622 |
using SignDisplay = mozilla::intl::NumberFormatOptions::SignDisplay; |
| 623 |
|
| 624 |
SignDisplay display; |
| 625 |
if (StringEqualsLiteral(signDisplay, "auto")) { |
| 626 |
if (accountingSign) { |
| 627 |
display = SignDisplay::Accounting; |
| 628 |
} else { |
| 629 |
display = SignDisplay::Auto; |
| 630 |
} |
| 631 |
} else if (StringEqualsLiteral(signDisplay, "never")) { |
| 632 |
display = SignDisplay::Never; |
| 633 |
} else if (StringEqualsLiteral(signDisplay, "always")) { |
| 634 |
if (accountingSign) { |
| 635 |
display = SignDisplay::AccountingAlways; |
| 636 |
} else { |
| 637 |
display = SignDisplay::Always; |
| 638 |
} |
| 639 |
} else if (StringEqualsLiteral(signDisplay, "exceptZero")) { |
| 640 |
if (accountingSign) { |
| 641 |
display = SignDisplay::AccountingExceptZero; |
| 642 |
} else { |
| 643 |
display = SignDisplay::ExceptZero; |
| 644 |
} |
| 645 |
} else { |
| 646 |
MOZ_ASSERT(StringEqualsLiteral(signDisplay, "negative")); |
| 647 |
if (accountingSign) { |
| 648 |
display = SignDisplay::AccountingNegative; |
| 649 |
} else { |
| 650 |
display = SignDisplay::Negative; |
| 651 |
} |
| 652 |
} |
| 653 |
|
| 654 |
options.mSignDisplay = display; |
| 655 |
} |
| 656 |
|
| 657 |
if (!GetProperty(cx, internals, internals, cx->names().roundingIncrement, |
| 658 |
&value)) { |
| 659 |
return false; |
| 660 |
} |
| 661 |
options.mRoundingIncrement = AssertedCast<uint32_t>(value.toInt32()); |
| 662 |
|
| 663 |
if (!GetProperty(cx, internals, internals, cx->names().roundingMode, |
| 664 |
&value)) { |
| 665 |
return false; |
| 666 |
} |
| 667 |
|
| 668 |
{ |
| 669 |
JSLinearString* roundingMode = value.toString()->ensureLinear(cx); |
| 670 |
if (!roundingMode) { |
| 671 |
return false; |
| 672 |
} |
| 673 |
|
| 674 |
using RoundingMode = mozilla::intl::NumberFormatOptions::RoundingMode; |
| 675 |
|
| 676 |
RoundingMode rounding; |
| 677 |
if (StringEqualsLiteral(roundingMode, "halfExpand")) { |
| 678 |
// "halfExpand" is the default mode, so we handle it first. |
| 679 |
rounding = RoundingMode::HalfExpand; |
| 680 |
} else if (StringEqualsLiteral(roundingMode, "ceil")) { |
| 681 |
rounding = RoundingMode::Ceil; |
| 682 |
} else if (StringEqualsLiteral(roundingMode, "floor")) { |
| 683 |
rounding = RoundingMode::Floor; |
| 684 |
} else if (StringEqualsLiteral(roundingMode, "expand")) { |
| 685 |
rounding = RoundingMode::Expand; |
| 686 |
} else if (StringEqualsLiteral(roundingMode, "trunc")) { |
| 687 |
rounding = RoundingMode::Trunc; |
| 688 |
} else if (StringEqualsLiteral(roundingMode, "halfCeil")) { |
| 689 |
rounding = RoundingMode::HalfCeil; |
| 690 |
} else if (StringEqualsLiteral(roundingMode, "halfFloor")) { |
| 691 |
rounding = RoundingMode::HalfFloor; |
| 692 |
} else if (StringEqualsLiteral(roundingMode, "halfTrunc")) { |
| 693 |
rounding = RoundingMode::HalfTrunc; |
| 694 |
} else { |
| 695 |
MOZ_ASSERT(StringEqualsLiteral(roundingMode, "halfEven")); |
| 696 |
rounding = RoundingMode::HalfEven; |
| 697 |
} |
| 698 |
|
| 699 |
options.mRoundingMode = rounding; |
| 700 |
} |
| 701 |
|
| 702 |
if (!GetProperty(cx, internals, internals, cx->names().trailingZeroDisplay, |
| 703 |
&value)) { |
| 704 |
return false; |
| 705 |
} |
| 706 |
|
| 707 |
{ |
| 708 |
JSLinearString* trailingZeroDisplay = value.toString()->ensureLinear(cx); |
| 709 |
if (!trailingZeroDisplay) { |
| 710 |
return false; |
| 711 |
} |
| 712 |
|
| 713 |
if (StringEqualsLiteral(trailingZeroDisplay, "auto")) { |
| 714 |
options.mStripTrailingZero = false; |
| 715 |
} else { |
| 716 |
MOZ_ASSERT(StringEqualsLiteral(trailingZeroDisplay, "stripIfInteger")); |
| 717 |
options.mStripTrailingZero = true; |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
return true; |
| 722 |
} |
| 723 |
|
| 724 |
/** |
| 725 |
* Returns a new mozilla::intl::Number[Range]Format with the locale and number |
| 726 |
* formatting options of the given NumberFormat, or a nullptr if |
| 727 |
* initialization failed. |
| 728 |
*/ |
| 729 |
template <class Formatter> |
| 730 |
static Formatter* NewNumberFormat(JSContext* cx, |
| 731 |
Handle<NumberFormatObject*> numberFormat) { |
| 732 |
RootedObject internals(cx, intl::GetInternalsObject(cx, numberFormat)); |
| 733 |
if (!internals) { |
| 734 |
return nullptr; |
| 735 |
} |
| 736 |
|
| 737 |
UniqueChars locale = NumberFormatLocale(cx, internals); |
| 738 |
if (!locale) { |
| 739 |
return nullptr; |
| 740 |
} |
| 741 |
|
| 742 |
NumberFormatOptions options; |
| 743 |
if (!FillNumberFormatOptions(cx, internals, options)) { |
| 744 |
return nullptr; |
| 745 |
} |
| 746 |
|
| 747 |
options.mRangeCollapse = NumberFormatOptions::RangeCollapse::Auto; |
| 748 |
options.mRangeIdentityFallback = |
| 749 |
NumberFormatOptions::RangeIdentityFallback::Approximately; |
| 750 |
|
| 751 |
mozilla::Result<mozilla::UniquePtr<Formatter>, mozilla::intl::ICUError> |
| 752 |
result = Formatter::TryCreate(locale.get(), options); |
| 753 |
|
| 754 |
if (result.isOk()) { |
| 755 |
return result.unwrap().release(); |
| 756 |
} |
| 757 |
|
| 758 |
intl::ReportInternalError(cx, result.unwrapErr()); |
| 759 |
return nullptr; |
| 760 |
} |
| 761 |
|
| 762 |
static mozilla::intl::NumberFormat* GetOrCreateNumberFormat( |
| 763 |
JSContext* cx, Handle<NumberFormatObject*> numberFormat) { |
| 764 |
// Obtain a cached mozilla::intl::NumberFormat object. |
| 765 |
mozilla::intl::NumberFormat* nf = numberFormat->getNumberFormatter(); |
| 766 |
if (nf) { |
| 767 |
return nf; |
| 768 |
} |
| 769 |
|
| 770 |
nf = NewNumberFormat<mozilla::intl::NumberFormat>(cx, numberFormat); |
| 771 |
if (!nf) { |
| 772 |
return nullptr; |
| 773 |
} |
| 774 |
numberFormat->setNumberFormatter(nf); |
| 775 |
|
| 776 |
intl::AddICUCellMemory(numberFormat, NumberFormatObject::EstimatedMemoryUse); |
| 777 |
return nf; |
| 778 |
} |
| 779 |
|
| 780 |
static mozilla::intl::NumberRangeFormat* GetOrCreateNumberRangeFormat( |
| 781 |
JSContext* cx, Handle<NumberFormatObject*> numberFormat) { |
| 782 |
// Obtain a cached mozilla::intl::NumberRangeFormat object. |
| 783 |
mozilla::intl::NumberRangeFormat* nrf = |
| 784 |
numberFormat->getNumberRangeFormatter(); |
| 785 |
if (nrf) { |
| 786 |
return nrf; |
| 787 |
} |
| 788 |
|
| 789 |
nrf = NewNumberFormat<mozilla::intl::NumberRangeFormat>(cx, numberFormat); |
| 790 |
if (!nrf) { |
| 791 |
return nullptr; |
| 792 |
} |
| 793 |
numberFormat->setNumberRangeFormatter(nrf); |
| 794 |
|
| 795 |
intl::AddICUCellMemory(numberFormat, |
| 796 |
NumberFormatObject::EstimatedRangeFormatterMemoryUse); |
| 797 |
return nrf; |
| 798 |
} |
| 799 |
|
| 800 |
static FieldType GetFieldTypeForNumberPartType( |
| 801 |
mozilla::intl::NumberPartType type) { |
| 802 |
switch (type) { |
| 803 |
case mozilla::intl::NumberPartType::ApproximatelySign: |
| 804 |
return &JSAtomState::approximatelySign; |
| 805 |
case mozilla::intl::NumberPartType::Compact: |
| 806 |
return &JSAtomState::compact; |
| 807 |
case mozilla::intl::NumberPartType::Currency: |
| 808 |
return &JSAtomState::currency; |
| 809 |
case mozilla::intl::NumberPartType::Decimal: |
| 810 |
return &JSAtomState::decimal; |
| 811 |
case mozilla::intl::NumberPartType::ExponentInteger: |
| 812 |
return &JSAtomState::exponentInteger; |
| 813 |
case mozilla::intl::NumberPartType::ExponentMinusSign: |
| 814 |
return &JSAtomState::exponentMinusSign; |
| 815 |
case mozilla::intl::NumberPartType::ExponentSeparator: |
| 816 |
return &JSAtomState::exponentSeparator; |
| 817 |
case mozilla::intl::NumberPartType::Fraction: |
| 818 |
return &JSAtomState::fraction; |
| 819 |
case mozilla::intl::NumberPartType::Group: |
| 820 |
return &JSAtomState::group; |
| 821 |
case mozilla::intl::NumberPartType::Infinity: |
| 822 |
return &JSAtomState::infinity; |
| 823 |
case mozilla::intl::NumberPartType::Integer: |
| 824 |
return &JSAtomState::integer; |
| 825 |
case mozilla::intl::NumberPartType::Literal: |
| 826 |
return &JSAtomState::literal; |
| 827 |
case mozilla::intl::NumberPartType::MinusSign: |
| 828 |
return &JSAtomState::minusSign; |
| 829 |
case mozilla::intl::NumberPartType::Nan: |
| 830 |
return &JSAtomState::nan; |
| 831 |
case mozilla::intl::NumberPartType::Percent: |
| 832 |
return &JSAtomState::percentSign; |
| 833 |
case mozilla::intl::NumberPartType::PlusSign: |
| 834 |
return &JSAtomState::plusSign; |
| 835 |
case mozilla::intl::NumberPartType::Unit: |
| 836 |
return &JSAtomState::unit; |
| 837 |
} |
| 838 |
|
| 839 |
MOZ_ASSERT_UNREACHABLE( |
| 840 |
"unenumerated, undocumented format field returned by iterator"); |
| 841 |
return nullptr; |
| 842 |
} |
| 843 |
|
| 844 |
static FieldType GetFieldTypeForNumberPartSource( |
| 845 |
mozilla::intl::NumberPartSource source) { |
| 846 |
switch (source) { |
| 847 |
case mozilla::intl::NumberPartSource::Shared: |
| 848 |
return &JSAtomState::shared; |
| 849 |
case mozilla::intl::NumberPartSource::Start: |
| 850 |
return &JSAtomState::startRange; |
| 851 |
case mozilla::intl::NumberPartSource::End: |
| 852 |
return &JSAtomState::endRange; |
| 853 |
} |
| 854 |
|
| 855 |
MOZ_CRASH("unexpected number part source"); |
| 856 |
} |
| 857 |
|
| 858 |
enum class DisplayNumberPartSource : bool { No, Yes }; |
| 859 |
|
| 860 |
static bool FormattedNumberToParts(JSContext* cx, HandleString str, |
| 861 |
const mozilla::intl::NumberPartVector& parts, |
| 862 |
DisplayNumberPartSource displaySource, |
| 863 |
FieldType unitType, |
| 864 |
MutableHandleValue result) { |
| 865 |
size_t lastEndIndex = 0; |
| 866 |
|
| 867 |
RootedObject singlePart(cx); |
| 868 |
RootedValue propVal(cx); |
| 869 |
|
| 870 |
Rooted<ArrayObject*> partsArray( |
| 871 |
cx, NewDenseFullyAllocatedArray(cx, parts.length())); |
| 872 |
if (!partsArray) { |
| 873 |
return false; |
| 874 |
} |
| 875 |
partsArray->ensureDenseInitializedLength(0, parts.length()); |
| 876 |
|
| 877 |
size_t index = 0; |
| 878 |
for (const auto& part : parts) { |
| 879 |
FieldType type = GetFieldTypeForNumberPartType(part.type); |
| 880 |
size_t endIndex = part.endIndex; |
| 881 |
|
| 882 |
MOZ_ASSERT(lastEndIndex < endIndex); |
| 883 |
|
| 884 |
singlePart = NewPlainObject(cx); |
| 885 |
if (!singlePart) { |
| 886 |
return false; |
| 887 |
} |
| 888 |
|
| 889 |
propVal.setString(cx->names().*type); |
| 890 |
if (!DefineDataProperty(cx, singlePart, cx->names().type, propVal)) { |
| 891 |
return false; |
| 892 |
} |
| 893 |
|
| 894 |
JSLinearString* partSubstr = |
| 895 |
NewDependentString(cx, str, lastEndIndex, endIndex - lastEndIndex); |
| 896 |
if (!partSubstr) { |
| 897 |
return false; |
| 898 |
} |
| 899 |
|
| 900 |
propVal.setString(partSubstr); |
| 901 |
if (!DefineDataProperty(cx, singlePart, cx->names().value, propVal)) { |
| 902 |
return false; |
| 903 |
} |
| 904 |
|
| 905 |
if (displaySource == DisplayNumberPartSource::Yes) { |
| 906 |
FieldType source = GetFieldTypeForNumberPartSource(part.source); |
| 907 |
|
| 908 |
propVal.setString(cx->names().*source); |
| 909 |
if (!DefineDataProperty(cx, singlePart, cx->names().source, propVal)) { |
| 910 |
return false; |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
if (unitType != nullptr && type != &JSAtomState::literal) { |
| 915 |
propVal.setString(cx->names().*unitType); |
| 916 |
if (!DefineDataProperty(cx, singlePart, cx->names().unit, propVal)) { |
| 917 |
return false; |
| 918 |
} |
| 919 |
} |
| 920 |
|
| 921 |
partsArray->initDenseElement(index++, ObjectValue(*singlePart)); |
| 922 |
|
| 923 |
lastEndIndex = endIndex; |
| 924 |
} |
| 925 |
|
| 926 |
MOZ_ASSERT(index == parts.length()); |
| 927 |
MOZ_ASSERT(lastEndIndex == str->length(), |
| 928 |
"result array must partition the entire string"); |
| 929 |
|
| 930 |
result.setObject(*partsArray); |
| 931 |
return true; |
| 932 |
} |
| 933 |
|
| 934 |
bool js::intl::FormattedRelativeTimeToParts( |
| 935 |
JSContext* cx, HandleString str, |
| 936 |
const mozilla::intl::NumberPartVector& parts, FieldType relativeTimeUnit, |
| 937 |
MutableHandleValue result) { |
| 938 |
return FormattedNumberToParts(cx, str, parts, DisplayNumberPartSource::No, |
| 939 |
relativeTimeUnit, result); |
| 940 |
} |
| 941 |
|
| 942 |
// Return true if the string starts with "0[bBoOxX]", possibly skipping over |
| 943 |
// leading whitespace. |
| 944 |
template <typename CharT> |
| 945 |
static bool IsNonDecimalNumber(mozilla::Range<const CharT> chars) { |
| 946 |
const CharT* end = chars.begin().get() + chars.length(); |
| 947 |
const CharT* start = SkipSpace(chars.begin().get(), end); |
| 948 |
|
| 949 |
if (end - start >= 2 && start[0] == '0') { |
| 950 |
CharT ch = start[1]; |
| 951 |
return ch == 'b' || ch == 'B' || ch == 'o' || ch == 'O' || ch == 'x' || |
| 952 |
ch == 'X'; |
| 953 |
} |
| 954 |
return false; |
| 955 |
} |
| 956 |
|
| 957 |
static bool IsNonDecimalNumber(const JSLinearString* str) { |
| 958 |
JS::AutoCheckCannotGC nogc; |
| 959 |
return str->hasLatin1Chars() ? IsNonDecimalNumber(str->latin1Range(nogc)) |
| 960 |
: IsNonDecimalNumber(str->twoByteRange(nogc)); |
| 961 |
} |
| 962 |
|
| 963 |
/** |
| 964 |
* 15.5.16 ToIntlMathematicalValue ( value ) |
| 965 |
* |
| 966 |
* ES2024 Intl draft rev 74ca7099f103d143431b2ea422ae640c6f43e3e6 |
| 967 |
*/ |
| 968 |
static bool ToIntlMathematicalValue(JSContext* cx, MutableHandleValue value) { |
| 969 |
// Step 1. |
| 970 |
if (!ToPrimitive(cx, JSTYPE_NUMBER, value)) { |
| 971 |
return false; |
| 972 |
} |
| 973 |
|
| 974 |
// Step 2. |
| 975 |
if (value.isBigInt()) { |
| 976 |
return true; |
| 977 |
} |
| 978 |
|
| 979 |
// Step 4. |
| 980 |
if (!value.isString()) { |
| 981 |
// Step 4.a. (Steps 4.b-10 not applicable in our implementation.) |
| 982 |
return ToNumber(cx, value); |
| 983 |
} |
| 984 |
|
| 985 |
// Step 3. |
| 986 |
JSLinearString* str = value.toString()->ensureLinear(cx); |
| 987 |
if (!str) { |
| 988 |
return false; |
| 989 |
} |
| 990 |
|
| 991 |
// Steps 5-6, 8, and 9.a. |
| 992 |
double number = LinearStringToNumber(str); |
| 993 |
|
| 994 |
// Step 7. |
| 995 |
if (std::isnan(number)) { |
| 996 |
// Set to NaN if the input can't be parsed as a number. |
| 997 |
value.setNaN(); |
| 998 |
return true; |
| 999 |
} |
| 1000 |
|
| 1001 |
// Step 9. |
| 1002 |
if (number == 0.0 || std::isinf(number)) { |
| 1003 |
// Step 9.a. (Reordered) |
| 1004 |
|
| 1005 |
// Steps 9.b-e. |
| 1006 |
value.setDouble(number); |
| 1007 |
return true; |
| 1008 |
} |
| 1009 |
|
| 1010 |
// Step 10. |
| 1011 |
if (IsNonDecimalNumber(str)) { |
| 1012 |
// ICU doesn't accept non-decimal numbers, so we have to convert the input |
| 1013 |
// into a base-10 string. |
| 1014 |
|
| 1015 |
MOZ_ASSERT(!mozilla::IsNegative(number), |
| 1016 |
"non-decimal numbers can't be negative"); |
| 1017 |
|
| 1018 |
if (number < DOUBLE_INTEGRAL_PRECISION_LIMIT) { |
| 1019 |
// Fast-path if we can guarantee there was no loss of precision. |
| 1020 |
value.setDouble(number); |
| 1021 |
} else { |
| 1022 |
// For the slow-path convert the string into a BigInt. |
| 1023 |
|
| 1024 |
// StringToBigInt can't fail (other than OOM) when StringToNumber already |
| 1025 |
// succeeded. |
| 1026 |
RootedString rooted(cx, str); |
| 1027 |
BigInt* bi; |
| 1028 |
JS_TRY_VAR_OR_RETURN_FALSE(cx, bi, StringToBigInt(cx, rooted)); |
| 1029 |
MOZ_ASSERT(bi); |
| 1030 |
|
| 1031 |
value.setBigInt(bi); |
| 1032 |
} |
| 1033 |
} |
| 1034 |
return true; |
| 1035 |
} |
| 1036 |
|
| 1037 |
// Return the number part of the input by removing leading and trailing |
| 1038 |
// whitespace. |
| 1039 |
template <typename CharT> |
| 1040 |
static mozilla::Span<const CharT> NumberPart(const CharT* chars, |
| 1041 |
size_t length) { |
| 1042 |
const CharT* start = chars; |
| 1043 |
const CharT* end = chars + length; |
| 1044 |
|
| 1045 |
start = SkipSpace(start, end); |
| 1046 |
|
| 1047 |
// |SkipSpace| only supports forward iteration, so inline the backwards |
| 1048 |
// iteration here. |
| 1049 |
MOZ_ASSERT(start <= end); |
| 1050 |
while (end > start && unicode::IsSpace(end[-1])) { |
| 1051 |
end--; |
| 1052 |
} |
| 1053 |
|
| 1054 |
// The number part is a non-empty, ASCII-only substring. |
| 1055 |
MOZ_ASSERT(start < end); |
| 1056 |
MOZ_ASSERT(mozilla::IsAscii(mozilla::Span(start, end))); |
| 1057 |
|
| 1058 |
return {start, end}; |
| 1059 |
} |
| 1060 |
|
| 1061 |
static bool NumberPart(JSContext* cx, JSLinearString* str, |
| 1062 |
const JS::AutoCheckCannotGC& nogc, |
| 1063 |
JS::UniqueChars& latin1, std::string_view& result) { |
| 1064 |
if (str->hasLatin1Chars()) { |
| 1065 |
auto span = NumberPart( |
| 1066 |
reinterpret_cast<const char*>(str->latin1Chars(nogc)), str->length()); |
| 1067 |
|
| 1068 |
result = {span.data(), span.size()}; |
| 1069 |
return true; |
| 1070 |
} |
| 1071 |
|
| 1072 |
auto span = NumberPart(str->twoByteChars(nogc), str->length()); |
| 1073 |
|
| 1074 |
latin1.reset(JS::LossyTwoByteCharsToNewLatin1CharsZ(cx, span).c_str()); |
| 1075 |
if (!latin1) { |
| 1076 |
return false; |
| 1077 |
} |
| 1078 |
|
| 1079 |
result = {latin1.get(), span.size()}; |
| 1080 |
return true; |
| 1081 |
} |
| 1082 |
|
| 1083 |
bool js::intl_FormatNumber(JSContext* cx, unsigned argc, Value* vp) { |
| 1084 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1085 |
MOZ_ASSERT(args.length() == 3); |
| 1086 |
MOZ_ASSERT(args[0].isObject()); |
| 1087 |
MOZ_ASSERT(args[2].isBoolean()); |
| 1088 |
|
| 1089 |
Rooted<NumberFormatObject*> numberFormat( |
| 1090 |
cx, &args[0].toObject().as<NumberFormatObject>()); |
| 1091 |
|
| 1092 |
RootedValue value(cx, args[1]); |
| 1093 |
if (!ToIntlMathematicalValue(cx, &value)) { |
| 1094 |
return false; |
| 1095 |
} |
| 1096 |
|
| 1097 |
mozilla::intl::NumberFormat* nf = GetOrCreateNumberFormat(cx, numberFormat); |
| 1098 |
if (!nf) { |
| 1099 |
return false; |
| 1100 |
} |
| 1101 |
|
| 1102 |
// Actually format the number |
| 1103 |
using ICUError = mozilla::intl::ICUError; |
| 1104 |
|
| 1105 |
bool formatToParts = args[2].toBoolean(); |
| 1106 |
mozilla::Result<std::u16string_view, ICUError> result = |
| 1107 |
mozilla::Err(ICUError::InternalError); |
| 1108 |
mozilla::intl::NumberPartVector parts; |
| 1109 |
if (value.isNumber()) { |
| 1110 |
double num = value.toNumber(); |
| 1111 |
if (formatToParts) { |
| 1112 |
result = nf->formatToParts(num, parts); |
| 1113 |
} else { |
| 1114 |
result = nf->format(num); |
| 1115 |
} |
| 1116 |
} else if (value.isBigInt()) { |
| 1117 |
RootedBigInt bi(cx, value.toBigInt()); |
| 1118 |
|
| 1119 |
int64_t num; |
| 1120 |
if (BigInt::isInt64(bi, &num)) { |
| 1121 |
if (formatToParts) { |
| 1122 |
result = nf->formatToParts(num, parts); |
| 1123 |
} else { |
| 1124 |
result = nf->format(num); |
| 1125 |
} |
| 1126 |
} else { |
| 1127 |
JSLinearString* str = BigInt::toString<CanGC>(cx, bi, 10); |
| 1128 |
if (!str) { |
| 1129 |
return false; |
| 1130 |
} |
| 1131 |
MOZ_RELEASE_ASSERT(str->hasLatin1Chars()); |
| 1132 |
|
| 1133 |
JS::AutoCheckCannotGC nogc; |
| 1134 |
|
| 1135 |
const char* chars = reinterpret_cast<const char*>(str->latin1Chars(nogc)); |
| 1136 |
if (formatToParts) { |
| 1137 |
result = |
| 1138 |
nf->formatToParts(std::string_view(chars, str->length()), parts); |
| 1139 |
} else { |
| 1140 |
result = nf->format(std::string_view(chars, str->length())); |
| 1141 |
} |
| 1142 |
} |
| 1143 |
} else { |
| 1144 |
JSLinearString* str = value.toString()->ensureLinear(cx); |
| 1145 |
if (!str) { |
| 1146 |
return false; |
| 1147 |
} |
| 1148 |
|
| 1149 |
JS::AutoCheckCannotGC nogc; |
| 1150 |
|
| 1151 |
// Two-byte strings have to be copied into a separate |char| buffer. |
| 1152 |
JS::UniqueChars latin1; |
| 1153 |
|
| 1154 |
std::string_view sv; |
| 1155 |
if (!NumberPart(cx, str, nogc, latin1, sv)) { |
| 1156 |
return false; |
| 1157 |
} |
| 1158 |
|
| 1159 |
if (formatToParts) { |
| 1160 |
result = nf->formatToParts(sv, parts); |
| 1161 |
} else { |
| 1162 |
result = nf->format(sv); |
| 1163 |
} |
| 1164 |
} |
| 1165 |
|
| 1166 |
if (result.isErr()) { |
| 1167 |
intl::ReportInternalError(cx, result.unwrapErr()); |
| 1168 |
return false; |
| 1169 |
} |
| 1170 |
|
| 1171 |
RootedString str(cx, NewStringCopy<CanGC>(cx, result.unwrap())); |
| 1172 |
if (!str) { |
| 1173 |
return false; |
| 1174 |
} |
| 1175 |
|
| 1176 |
if (formatToParts) { |
| 1177 |
return FormattedNumberToParts(cx, str, parts, DisplayNumberPartSource::No, |
| 1178 |
nullptr, args.rval()); |
| 1179 |
} |
| 1180 |
|
| 1181 |
args.rval().setString(str); |
| 1182 |
return true; |
| 1183 |
} |
| 1184 |
|
| 1185 |
static JSLinearString* ToLinearString(JSContext* cx, HandleValue val) { |
| 1186 |
// Special case to preserve negative zero. |
| 1187 |
if (val.isDouble() && mozilla::IsNegativeZero(val.toDouble())) { |
| 1188 |
constexpr std::string_view negativeZero = "-0"; |
| 1189 |
return NewStringCopy<CanGC>(cx, negativeZero); |
| 1190 |
} |
| 1191 |
|
| 1192 |
JSString* str = ToString(cx, val); |
| 1193 |
return str ? str->ensureLinear(cx) : nullptr; |
| 1194 |
}; |
| 1195 |
|
| 1196 |
bool js::intl_FormatNumberRange(JSContext* cx, unsigned argc, Value* vp) { |
| 1197 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1198 |
MOZ_ASSERT(args.length() == 4); |
| 1199 |
MOZ_ASSERT(args[0].isObject()); |
| 1200 |
MOZ_ASSERT(!args[1].isUndefined()); |
| 1201 |
MOZ_ASSERT(!args[2].isUndefined()); |
| 1202 |
MOZ_ASSERT(args[3].isBoolean()); |
| 1203 |
|
| 1204 |
Rooted<NumberFormatObject*> numberFormat( |
| 1205 |
cx, &args[0].toObject().as<NumberFormatObject>()); |
| 1206 |
bool formatToParts = args[3].toBoolean(); |
| 1207 |
|
| 1208 |
RootedValue start(cx, args[1]); |
| 1209 |
if (!ToIntlMathematicalValue(cx, &start)) { |
| 1210 |
return false; |
| 1211 |
} |
| 1212 |
|
| 1213 |
RootedValue end(cx, args[2]); |
| 1214 |
if (!ToIntlMathematicalValue(cx, &end)) { |
| 1215 |
return false; |
| 1216 |
} |
| 1217 |
|
| 1218 |
// PartitionNumberRangePattern, step 1. |
| 1219 |
if (start.isDouble() && std::isnan(start.toDouble())) { |
| 1220 |
JS_ReportErrorNumberASCII( |
| 1221 |
cx, GetErrorMessage, nullptr, JSMSG_NAN_NUMBER_RANGE, "start", |
| 1222 |
"NumberFormat", formatToParts ? "formatRangeToParts" : "formatRange"); |
| 1223 |
return false; |
| 1224 |
} |
| 1225 |
if (end.isDouble() && std::isnan(end.toDouble())) { |
| 1226 |
JS_ReportErrorNumberASCII( |
| 1227 |
cx, GetErrorMessage, nullptr, JSMSG_NAN_NUMBER_RANGE, "end", |
| 1228 |
"NumberFormat", formatToParts ? "formatRangeToParts" : "formatRange"); |
| 1229 |
return false; |
| 1230 |
} |
| 1231 |
|
| 1232 |
using NumberRangeFormat = mozilla::intl::NumberRangeFormat; |
| 1233 |
NumberRangeFormat* nf = GetOrCreateNumberRangeFormat(cx, numberFormat); |
| 1234 |
if (!nf) { |
| 1235 |
return false; |
| 1236 |
} |
| 1237 |
|
| 1238 |
auto valueRepresentableAsDouble = [](const Value& val, double* num) { |
| 1239 |
if (val.isNumber()) { |
| 1240 |
*num = val.toNumber(); |
| 1241 |
return true; |
| 1242 |
} |
| 1243 |
if (val.isBigInt()) { |
| 1244 |
int64_t i64; |
| 1245 |
if (BigInt::isInt64(val.toBigInt(), &i64) && |
| 1246 |
i64 < int64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT) && |
| 1247 |
i64 > -int64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)) { |
| 1248 |
*num = double(i64); |
| 1249 |
return true; |
| 1250 |
} |
| 1251 |
} |
| 1252 |
return false; |
| 1253 |
}; |
| 1254 |
|
| 1255 |
// Actually format the number range. |
| 1256 |
using ICUError = mozilla::intl::ICUError; |
| 1257 |
|
| 1258 |
mozilla::Result<std::u16string_view, ICUError> result = |
| 1259 |
mozilla::Err(ICUError::InternalError); |
| 1260 |
mozilla::intl::NumberPartVector parts; |
| 1261 |
|
| 1262 |
double numStart, numEnd; |
| 1263 |
if (valueRepresentableAsDouble(start, &numStart) && |
| 1264 |
valueRepresentableAsDouble(end, &numEnd)) { |
| 1265 |
if (formatToParts) { |
| 1266 |
result = nf->formatToParts(numStart, numEnd, parts); |
| 1267 |
} else { |
| 1268 |
result = nf->format(numStart, numEnd); |
| 1269 |
} |
| 1270 |
} else { |
| 1271 |
Rooted<JSLinearString*> strStart(cx, ToLinearString(cx, start)); |
| 1272 |
if (!strStart) { |
| 1273 |
return false; |
| 1274 |
} |
| 1275 |
|
| 1276 |
Rooted<JSLinearString*> strEnd(cx, ToLinearString(cx, end)); |
| 1277 |
if (!strEnd) { |
| 1278 |
return false; |
| 1279 |
} |
| 1280 |
|
| 1281 |
JS::AutoCheckCannotGC nogc; |
| 1282 |
|
| 1283 |
// Two-byte strings have to be copied into a separate |char| buffer. |
| 1284 |
JS::UniqueChars latin1Start; |
| 1285 |
JS::UniqueChars latin1End; |
| 1286 |
|
| 1287 |
std::string_view svStart; |
| 1288 |
if (!NumberPart(cx, strStart, nogc, latin1Start, svStart)) { |
| 1289 |
return false; |
| 1290 |
} |
| 1291 |
|
| 1292 |
std::string_view svEnd; |
| 1293 |
if (!NumberPart(cx, strEnd, nogc, latin1End, svEnd)) { |
| 1294 |
return false; |
| 1295 |
} |
| 1296 |
|
| 1297 |
if (formatToParts) { |
| 1298 |
result = nf->formatToParts(svStart, svEnd, parts); |
| 1299 |
} else { |
| 1300 |
result = nf->format(svStart, svEnd); |
| 1301 |
} |
| 1302 |
} |
| 1303 |
|
| 1304 |
if (result.isErr()) { |
| 1305 |
intl::ReportInternalError(cx, result.unwrapErr()); |
| 1306 |
return false; |
| 1307 |
} |
| 1308 |
|
| 1309 |
RootedString str(cx, NewStringCopy<CanGC>(cx, result.unwrap())); |
| 1310 |
if (!str) { |
| 1311 |
return false; |
| 1312 |
} |
| 1313 |
|
| 1314 |
if (formatToParts) { |
| 1315 |
return FormattedNumberToParts(cx, str, parts, DisplayNumberPartSource::Yes, |
| 1316 |
nullptr, args.rval()); |
| 1317 |
} |
| 1318 |
|
| 1319 |
args.rval().setString(str); |
| 1320 |
return true; |
| 1321 |
} |