Debian Codegraph @

js/src/builtin/intl/PluralRules.cpp

raw
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 /* Implementation of the Intl.PluralRules proposal. */
8
9 #include "builtin/intl/PluralRules.h"
10
11 #include "mozilla/Assertions.h"
12 #include "mozilla/Casting.h"
13 #include "mozilla/intl/PluralRules.h"
14
15 #include "builtin/Array.h"
16 #include "builtin/intl/CommonFunctions.h"
17 #include "gc/GCContext.h"
18 #include "js/PropertySpec.h"
19 #include "vm/GlobalObject.h"
20 #include "vm/JSContext.h"
21 #include "vm/PlainObject.h" // js::PlainObject
22 #include "vm/StringType.h"
23
24 #include "vm/JSObject-inl.h"
25 #include "vm/NativeObject-inl.h"
26
27 using namespace js;
28
29 using mozilla::AssertedCast;
30
31 const JSClassOps PluralRulesObject::classOps_ = {
32 nullptr, // addProperty
33 nullptr, // delProperty
34 nullptr, // enumerate
35 nullptr, // newEnumerate
36 nullptr, // resolve
37 nullptr, // mayResolve
38 PluralRulesObject::finalize, // finalize
39 nullptr, // call
40 nullptr, // construct
41 nullptr, // trace
42 };
43
44 const JSClass PluralRulesObject::class_ = {
45 "Intl.PluralRules",
46 JSCLASS_HAS_RESERVED_SLOTS(PluralRulesObject::SLOT_COUNT) |
47 JSCLASS_HAS_CACHED_PROTO(JSProto_PluralRules) |
48 JSCLASS_FOREGROUND_FINALIZE,
49 &PluralRulesObject::classOps_,
50 &PluralRulesObject::classSpec_,
51 };
52
53 const JSClass& PluralRulesObject::protoClass_ = PlainObject::class_;
54
55 static bool pluralRules_toSource(JSContext* cx, unsigned argc, Value* vp) {
56 CallArgs args = CallArgsFromVp(argc, vp);
57 args.rval().setString(cx->names().PluralRules);
58 return true;
59 }
60
61 static const JSFunctionSpec pluralRules_static_methods[] = {
62 JS_SELF_HOSTED_FN("supportedLocalesOf",
63 "Intl_PluralRules_supportedLocalesOf", 1, 0),
64 JS_FS_END,
65 };
66
67 static const JSFunctionSpec pluralRules_methods[] = {
68 JS_SELF_HOSTED_FN("resolvedOptions", "Intl_PluralRules_resolvedOptions", 0,
69 0),
70 JS_SELF_HOSTED_FN("select", "Intl_PluralRules_select", 1, 0),
71 JS_SELF_HOSTED_FN("selectRange", "Intl_PluralRules_selectRange", 2, 0),
72 JS_FN("toSource", pluralRules_toSource, 0, 0),
73 JS_FS_END,
74 };
75
76 static const JSPropertySpec pluralRules_properties[] = {
77 JS_STRING_SYM_PS(toStringTag, "Intl.PluralRules", JSPROP_READONLY),
78 JS_PS_END,
79 };
80
81 static bool PluralRules(JSContext* cx, unsigned argc, Value* vp);
82
83 const ClassSpec PluralRulesObject::classSpec_ = {
84 GenericCreateConstructor<PluralRules, 0, gc::AllocKind::FUNCTION>,
85 GenericCreatePrototype<PluralRulesObject>,
86 pluralRules_static_methods,
87 nullptr,
88 pluralRules_methods,
89 pluralRules_properties,
90 nullptr,
91 ClassSpec::DontDefineConstructor,
92 };
93
94 /**
95 * 16.1.1 Intl.PluralRules ( [ locales [ , options ] ] )
96 *
97 * ES2024 Intl draft rev 74ca7099f103d143431b2ea422ae640c6f43e3e6
98 */
99 static bool PluralRules(JSContext* cx, unsigned argc, Value* vp) {
100 CallArgs args = CallArgsFromVp(argc, vp);
101
102 // Step 1.
103 if (!ThrowIfNotConstructing(cx, args, "Intl.PluralRules")) {
104 return false;
105 }
106
107 // Step 2 (Inlined 9.1.14, OrdinaryCreateFromConstructor).
108 RootedObject proto(cx);
109 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_PluralRules,
110 &proto)) {
111 return false;
112 }
113
114 Rooted<PluralRulesObject*> pluralRules(cx);
115 pluralRules = NewObjectWithClassProto<PluralRulesObject>(cx, proto);
116 if (!pluralRules) {
117 return false;
118 }
119
120 HandleValue locales = args.get(0);
121 HandleValue options = args.get(1);
122
123 // Step 3.
124 if (!intl::InitializeObject(cx, pluralRules,
125 cx->names().InitializePluralRules, locales,
126 options)) {
127 return false;
128 }
129
130 args.rval().setObject(*pluralRules);
131 return true;
132 }
133
134 void js::PluralRulesObject::finalize(JS::GCContext* gcx, JSObject* obj) {
135 MOZ_ASSERT(gcx->onMainThread());
136
137 auto* pluralRules = &obj->as<PluralRulesObject>();
138 if (mozilla::intl::PluralRules* pr = pluralRules->getPluralRules()) {
139 intl::RemoveICUCellMemory(
140 gcx, obj, PluralRulesObject::UPluralRulesEstimatedMemoryUse);
141 delete pr;
142 }
143 }
144
145 static JSString* KeywordToString(mozilla::intl::PluralRules::Keyword keyword,
146 JSContext* cx) {
147 using Keyword = mozilla::intl::PluralRules::Keyword;
148 switch (keyword) {
149 case Keyword::Zero: {
150 return cx->names().zero;
151 }
152 case Keyword::One: {
153 return cx->names().one;
154 }
155 case Keyword::Two: {
156 return cx->names().two;
157 }
158 case Keyword::Few: {
159 return cx->names().few;
160 }
161 case Keyword::Many: {
162 return cx->names().many;
163 }
164 case Keyword::Other: {
165 return cx->names().other;
166 }
167 }
168 MOZ_CRASH("Unexpected PluralRules keyword");
169 }
170
171 /**
172 * Returns a new intl::PluralRules with the locale and type options of the given
173 * PluralRules.
174 */
175 static mozilla::intl::PluralRules* NewPluralRules(
176 JSContext* cx, Handle<PluralRulesObject*> pluralRules) {
177 RootedObject internals(cx, intl::GetInternalsObject(cx, pluralRules));
178 if (!internals) {
179 return nullptr;
180 }
181
182 RootedValue value(cx);
183
184 if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) {
185 return nullptr;
186 }
187 UniqueChars locale = intl::EncodeLocale(cx, value.toString());
188 if (!locale) {
189 return nullptr;
190 }
191
192 using PluralRules = mozilla::intl::PluralRules;
193 mozilla::intl::PluralRulesOptions options;
194
195 if (!GetProperty(cx, internals, internals, cx->names().type, &value)) {
196 return nullptr;
197 }
198
199 {
200 JSLinearString* type = value.toString()->ensureLinear(cx);
201 if (!type) {
202 return nullptr;
203 }
204
205 if (StringEqualsLiteral(type, "ordinal")) {
206 options.mPluralType = PluralRules::Type::Ordinal;
207 } else {
208 MOZ_ASSERT(StringEqualsLiteral(type, "cardinal"));
209 options.mPluralType = PluralRules::Type::Cardinal;
210 }
211 }
212
213 bool hasMinimumSignificantDigits;
214 if (!HasProperty(cx, internals, cx->names().minimumSignificantDigits,
215 &hasMinimumSignificantDigits)) {
216 return nullptr;
217 }
218
219 if (hasMinimumSignificantDigits) {
220 if (!GetProperty(cx, internals, internals,
221 cx->names().minimumSignificantDigits, &value)) {
222 return nullptr;
223 }
224 uint32_t minimumSignificantDigits = AssertedCast<uint32_t>(value.toInt32());
225
226 if (!GetProperty(cx, internals, internals,
227 cx->names().maximumSignificantDigits, &value)) {
228 return nullptr;
229 }
230 uint32_t maximumSignificantDigits = AssertedCast<uint32_t>(value.toInt32());
231
232 options.mSignificantDigits = mozilla::Some(
233 std::make_pair(minimumSignificantDigits, maximumSignificantDigits));
234 }
235
236 bool hasMinimumFractionDigits;
237 if (!HasProperty(cx, internals, cx->names().minimumFractionDigits,
238 &hasMinimumFractionDigits)) {
239 return nullptr;
240 }
241
242 if (hasMinimumFractionDigits) {
243 if (!GetProperty(cx, internals, internals,
244 cx->names().minimumFractionDigits, &value)) {
245 return nullptr;
246 }
247 uint32_t minimumFractionDigits = AssertedCast<uint32_t>(value.toInt32());
248
249 if (!GetProperty(cx, internals, internals,
250 cx->names().maximumFractionDigits, &value)) {
251 return nullptr;
252 }
253 uint32_t maximumFractionDigits = AssertedCast<uint32_t>(value.toInt32());
254
255 options.mFractionDigits = mozilla::Some(
256 std::make_pair(minimumFractionDigits, maximumFractionDigits));
257 }
258
259 if (!GetProperty(cx, internals, internals, cx->names().roundingPriority,
260 &value)) {
261 return nullptr;
262 }
263
264 {
265 JSLinearString* roundingPriority = value.toString()->ensureLinear(cx);
266 if (!roundingPriority) {
267 return nullptr;
268 }
269
270 using RoundingPriority =
271 mozilla::intl::PluralRulesOptions::RoundingPriority;
272
273 RoundingPriority priority;
274 if (StringEqualsLiteral(roundingPriority, "auto")) {
275 priority = RoundingPriority::Auto;
276 } else if (StringEqualsLiteral(roundingPriority, "morePrecision")) {
277 priority = RoundingPriority::MorePrecision;
278 } else {
279 MOZ_ASSERT(StringEqualsLiteral(roundingPriority, "lessPrecision"));
280 priority = RoundingPriority::LessPrecision;
281 }
282
283 options.mRoundingPriority = priority;
284 }
285
286 if (!GetProperty(cx, internals, internals, cx->names().minimumIntegerDigits,
287 &value)) {
288 return nullptr;
289 }
290 options.mMinIntegerDigits =
291 mozilla::Some(AssertedCast<uint32_t>(value.toInt32()));
292
293 if (!GetProperty(cx, internals, internals, cx->names().roundingIncrement,
294 &value)) {
295 return nullptr;
296 }
297 options.mRoundingIncrement = AssertedCast<uint32_t>(value.toInt32());
298
299 if (!GetProperty(cx, internals, internals, cx->names().roundingMode,
300 &value)) {
301 return nullptr;
302 }
303
304 {
305 JSLinearString* roundingMode = value.toString()->ensureLinear(cx);
306 if (!roundingMode) {
307 return nullptr;
308 }
309
310 using RoundingMode = mozilla::intl::PluralRulesOptions::RoundingMode;
311
312 RoundingMode rounding;
313 if (StringEqualsLiteral(roundingMode, "halfExpand")) {
314 // "halfExpand" is the default mode, so we handle it first.
315 rounding = RoundingMode::HalfExpand;
316 } else if (StringEqualsLiteral(roundingMode, "ceil")) {
317 rounding = RoundingMode::Ceil;
318 } else if (StringEqualsLiteral(roundingMode, "floor")) {
319 rounding = RoundingMode::Floor;
320 } else if (StringEqualsLiteral(roundingMode, "expand")) {
321 rounding = RoundingMode::Expand;
322 } else if (StringEqualsLiteral(roundingMode, "trunc")) {
323 rounding = RoundingMode::Trunc;
324 } else if (StringEqualsLiteral(roundingMode, "halfCeil")) {
325 rounding = RoundingMode::HalfCeil;
326 } else if (StringEqualsLiteral(roundingMode, "halfFloor")) {
327 rounding = RoundingMode::HalfFloor;
328 } else if (StringEqualsLiteral(roundingMode, "halfTrunc")) {
329 rounding = RoundingMode::HalfTrunc;
330 } else {
331 MOZ_ASSERT(StringEqualsLiteral(roundingMode, "halfEven"));
332 rounding = RoundingMode::HalfEven;
333 }
334
335 options.mRoundingMode = rounding;
336 }
337
338 if (!GetProperty(cx, internals, internals, cx->names().trailingZeroDisplay,
339 &value)) {
340 return nullptr;
341 }
342
343 {
344 JSLinearString* trailingZeroDisplay = value.toString()->ensureLinear(cx);
345 if (!trailingZeroDisplay) {
346 return nullptr;
347 }
348
349 if (StringEqualsLiteral(trailingZeroDisplay, "auto")) {
350 options.mStripTrailingZero = false;
351 } else {
352 MOZ_ASSERT(StringEqualsLiteral(trailingZeroDisplay, "stripIfInteger"));
353 options.mStripTrailingZero = true;
354 }
355 }
356
357 auto result = PluralRules::TryCreate(locale.get(), options);
358 if (result.isErr()) {
359 intl::ReportInternalError(cx, result.unwrapErr());
360 return nullptr;
361 }
362
363 return result.unwrap().release();
364 }
365
366 static mozilla::intl::PluralRules* GetOrCreatePluralRules(
367 JSContext* cx, Handle<PluralRulesObject*> pluralRules) {
368 // Obtain a cached PluralRules object.
369 mozilla::intl::PluralRules* pr = pluralRules->getPluralRules();
370 if (pr) {
371 return pr;
372 }
373
374 pr = NewPluralRules(cx, pluralRules);
375 if (!pr) {
376 return nullptr;
377 }
378 pluralRules->setPluralRules(pr);
379
380 intl::AddICUCellMemory(pluralRules,
381 PluralRulesObject::UPluralRulesEstimatedMemoryUse);
382 return pr;
383 }
384
385 /**
386 * 16.5.3 ResolvePlural ( pluralRules, n )
387 * 16.5.2 PluralRuleSelect ( locale, type, n, operands )
388 *
389 * ES2024 Intl draft rev 74ca7099f103d143431b2ea422ae640c6f43e3e6
390 */
391 bool js::intl_SelectPluralRule(JSContext* cx, unsigned argc, Value* vp) {
392 CallArgs args = CallArgsFromVp(argc, vp);
393 MOZ_ASSERT(args.length() == 2);
394
395 // Steps 1-2.
396 Rooted<PluralRulesObject*> pluralRules(
397 cx, &args[0].toObject().as<PluralRulesObject>());
398
399 // Step 3.
400 double x = args[1].toNumber();
401
402 // Steps 4-11.
403 using PluralRules = mozilla::intl::PluralRules;
404 PluralRules* pr = GetOrCreatePluralRules(cx, pluralRules);
405 if (!pr) {
406 return false;
407 }
408
409 auto keywordResult = pr->Select(x);
410 if (keywordResult.isErr()) {
411 intl::ReportInternalError(cx, keywordResult.unwrapErr());
412 return false;
413 }
414
415 JSString* str = KeywordToString(keywordResult.unwrap(), cx);
416 MOZ_ASSERT(str);
417
418 args.rval().setString(str);
419 return true;
420 }
421
422 /**
423 * 16.5.5 ResolvePluralRange ( pluralRules, x, y )
424 * 16.5.4 PluralRuleSelectRange ( locale, type, xp, yp )
425 *
426 * ES2024 Intl draft rev 74ca7099f103d143431b2ea422ae640c6f43e3e6
427 */
428 bool js::intl_SelectPluralRuleRange(JSContext* cx, unsigned argc, Value* vp) {
429 CallArgs args = CallArgsFromVp(argc, vp);
430 MOZ_ASSERT(args.length() == 3);
431
432 // Steps 1-2.
433 Rooted<PluralRulesObject*> pluralRules(
434 cx, &args[0].toObject().as<PluralRulesObject>());
435
436 // Steps 3-4.
437 double x = args[1].toNumber();
438 double y = args[2].toNumber();
439
440 // Step 5.
441 if (std::isnan(x)) {
442 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
443 JSMSG_NAN_NUMBER_RANGE, "start", "PluralRules",
444 "selectRange");
445 return false;
446 }
447 if (std::isnan(y)) {
448 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
449 JSMSG_NAN_NUMBER_RANGE, "end", "PluralRules",
450 "selectRange");
451 return false;
452 }
453
454 using PluralRules = mozilla::intl::PluralRules;
455 PluralRules* pr = GetOrCreatePluralRules(cx, pluralRules);
456 if (!pr) {
457 return false;
458 }
459
460 // Steps 6-11.
461 auto keywordResult = pr->SelectRange(x, y);
462 if (keywordResult.isErr()) {
463 intl::ReportInternalError(cx, keywordResult.unwrapErr());
464 return false;
465 }
466
467 JSString* str = KeywordToString(keywordResult.unwrap(), cx);
468 MOZ_ASSERT(str);
469
470 args.rval().setString(str);
471 return true;
472 }
473
474 bool js::intl_GetPluralCategories(JSContext* cx, unsigned argc, Value* vp) {
475 CallArgs args = CallArgsFromVp(argc, vp);
476 MOZ_ASSERT(args.length() == 1);
477
478 Rooted<PluralRulesObject*> pluralRules(
479 cx, &args[0].toObject().as<PluralRulesObject>());
480
481 using PluralRules = mozilla::intl::PluralRules;
482 PluralRules* pr = GetOrCreatePluralRules(cx, pluralRules);
483 if (!pr) {
484 return false;
485 }
486
487 auto categoriesResult = pr->Categories();
488 if (categoriesResult.isErr()) {
489 intl::ReportInternalError(cx, categoriesResult.unwrapErr());
490 return false;
491 }
492 auto categories = categoriesResult.unwrap();
493
494 ArrayObject* res = NewDenseFullyAllocatedArray(cx, categories.size());
495 if (!res) {
496 return false;
497 }
498 res->setDenseInitializedLength(categories.size());
499
500 size_t index = 0;
501 for (auto keyword : {
502 PluralRules::Keyword::Zero,
503 PluralRules::Keyword::One,
504 PluralRules::Keyword::Two,
505 PluralRules::Keyword::Few,
506 PluralRules::Keyword::Many,
507 PluralRules::Keyword::Other,
508 }) {
509 if (categories.contains(keyword)) {
510 JSString* str = KeywordToString(keyword, cx);
511 MOZ_ASSERT(str);
512
513 res->initDenseElement(index++, StringValue(str));
514 }
515 }
516 MOZ_ASSERT(index == categories.size());
517
518 args.rval().setObject(*res);
519 return true;
520 }