Debian Codegraph @

js/src/builtin/intl/DisplayNames.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 /* Intl.DisplayNames implementation. */
8
9 #include "builtin/intl/DisplayNames.h"
10
11 #include "mozilla/Assertions.h"
12 #include "mozilla/intl/DisplayNames.h"
13 #include "mozilla/PodOperations.h"
14 #include "mozilla/Span.h"
15
16 #include <algorithm>
17
18 #include "jsnum.h"
19 #include "jspubtd.h"
20
21 #include "builtin/intl/CommonFunctions.h"
22 #include "builtin/intl/FormatBuffer.h"
23 #include "gc/AllocKind.h"
24 #include "gc/GCContext.h"
25 #include "js/CallArgs.h"
26 #include "js/Class.h"
27 #include "js/experimental/Intl.h" // JS::AddMozDisplayNamesConstructor
28 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
29 #include "js/Printer.h"
30 #include "js/PropertyAndElement.h" // JS_DefineFunctions, JS_DefineProperties
31 #include "js/PropertyDescriptor.h"
32 #include "js/PropertySpec.h"
33 #include "js/RootingAPI.h"
34 #include "js/TypeDecls.h"
35 #include "js/Utility.h"
36 #include "vm/GlobalObject.h"
37 #include "vm/JSContext.h"
38 #include "vm/JSObject.h"
39 #include "vm/Runtime.h"
40 #include "vm/SelfHosting.h"
41 #include "vm/Stack.h"
42 #include "vm/StringType.h"
43
44 #include "vm/JSObject-inl.h"
45 #include "vm/NativeObject-inl.h"
46
47 using namespace js;
48
49 const JSClassOps DisplayNamesObject::classOps_ = {
50 nullptr, /* addProperty */
51 nullptr, /* delProperty */
52 nullptr, /* enumerate */
53 nullptr, /* newEnumerate */
54 nullptr, /* resolve */
55 nullptr, /* mayResolve */
56 DisplayNamesObject::finalize,
57 };
58
59 const JSClass DisplayNamesObject::class_ = {
60 "Intl.DisplayNames",
61 JSCLASS_HAS_RESERVED_SLOTS(DisplayNamesObject::SLOT_COUNT) |
62 JSCLASS_HAS_CACHED_PROTO(JSProto_DisplayNames) |
63 JSCLASS_FOREGROUND_FINALIZE,
64 &DisplayNamesObject::classOps_,
65 &DisplayNamesObject::classSpec_,
66 };
67
68 const JSClass& DisplayNamesObject::protoClass_ = PlainObject::class_;
69
70 static bool displayNames_toSource(JSContext* cx, unsigned argc, Value* vp) {
71 CallArgs args = CallArgsFromVp(argc, vp);
72 args.rval().setString(cx->names().DisplayNames);
73 return true;
74 }
75
76 static const JSFunctionSpec displayNames_static_methods[] = {
77 JS_SELF_HOSTED_FN("supportedLocalesOf",
78 "Intl_DisplayNames_supportedLocalesOf", 1, 0),
79 JS_FS_END,
80 };
81
82 static const JSFunctionSpec displayNames_methods[] = {
83 JS_SELF_HOSTED_FN("of", "Intl_DisplayNames_of", 1, 0),
84 JS_SELF_HOSTED_FN("resolvedOptions", "Intl_DisplayNames_resolvedOptions", 0,
85 0),
86 JS_FN("toSource", displayNames_toSource, 0, 0),
87 JS_FS_END,
88 };
89
90 static const JSPropertySpec displayNames_properties[] = {
91 JS_STRING_SYM_PS(toStringTag, "Intl.DisplayNames", JSPROP_READONLY),
92 JS_PS_END,
93 };
94
95 static bool DisplayNames(JSContext* cx, unsigned argc, Value* vp);
96
97 const ClassSpec DisplayNamesObject::classSpec_ = {
98 GenericCreateConstructor<DisplayNames, 2, gc::AllocKind::FUNCTION>,
99 GenericCreatePrototype<DisplayNamesObject>,
100 displayNames_static_methods,
101 nullptr,
102 displayNames_methods,
103 displayNames_properties,
104 nullptr,
105 ClassSpec::DontDefineConstructor,
106 };
107
108 enum class DisplayNamesOptions {
109 Standard,
110
111 // Calendar display names are no longer available with the current spec
112 // proposal text, but may be re-enabled in the future. For our internal use
113 // we still need to have them present, so use a feature guard for now.
114 EnableMozExtensions,
115 };
116
117 /**
118 * Initialize a new Intl.DisplayNames object using the named self-hosted
119 * function.
120 */
121 static bool InitializeDisplayNamesObject(JSContext* cx, HandleObject obj,
122 Handle<PropertyName*> initializer,
123 HandleValue locales,
124 HandleValue options,
125 DisplayNamesOptions dnoptions) {
126 FixedInvokeArgs<4> args(cx);
127
128 args[0].setObject(*obj);
129 args[1].set(locales);
130 args[2].set(options);
131 args[3].setBoolean(dnoptions == DisplayNamesOptions::EnableMozExtensions);
132
133 RootedValue ignored(cx);
134 if (!CallSelfHostedFunction(cx, initializer, NullHandleValue, args,
135 &ignored)) {
136 return false;
137 }
138
139 MOZ_ASSERT(ignored.isUndefined(),
140 "Unexpected return value from non-legacy Intl object initializer");
141 return true;
142 }
143
144 /**
145 * Intl.DisplayNames ([ locales [ , options ]])
146 */
147 static bool DisplayNames(JSContext* cx, const CallArgs& args,
148 DisplayNamesOptions dnoptions) {
149 // Step 1.
150 if (!ThrowIfNotConstructing(cx, args, "Intl.DisplayNames")) {
151 return false;
152 }
153
154 // Step 2 (Inlined 9.1.14, OrdinaryCreateFromConstructor).
155 RootedObject proto(cx);
156 if (dnoptions == DisplayNamesOptions::Standard) {
157 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_DisplayNames,
158 &proto)) {
159 return false;
160 }
161 } else {
162 RootedObject newTarget(cx, &args.newTarget().toObject());
163 if (!GetPrototypeFromConstructor(cx, newTarget, JSProto_Null, &proto)) {
164 return false;
165 }
166 }
167
168 Rooted<DisplayNamesObject*> displayNames(cx);
169 displayNames = NewObjectWithClassProto<DisplayNamesObject>(cx, proto);
170 if (!displayNames) {
171 return false;
172 }
173
174 HandleValue locales = args.get(0);
175 HandleValue options = args.get(1);
176
177 // Steps 3-26.
178 if (!InitializeDisplayNamesObject(cx, displayNames,
179 cx->names().InitializeDisplayNames, locales,
180 options, dnoptions)) {
181 return false;
182 }
183
184 // Step 27.
185 args.rval().setObject(*displayNames);
186 return true;
187 }
188
189 static bool DisplayNames(JSContext* cx, unsigned argc, Value* vp) {
190 CallArgs args = CallArgsFromVp(argc, vp);
191 return DisplayNames(cx, args, DisplayNamesOptions::Standard);
192 }
193
194 static bool MozDisplayNames(JSContext* cx, unsigned argc, Value* vp) {
195 CallArgs args = CallArgsFromVp(argc, vp);
196 return DisplayNames(cx, args, DisplayNamesOptions::EnableMozExtensions);
197 }
198
199 void js::DisplayNamesObject::finalize(JS::GCContext* gcx, JSObject* obj) {
200 MOZ_ASSERT(gcx->onMainThread());
201
202 if (mozilla::intl::DisplayNames* displayNames =
203 obj->as<DisplayNamesObject>().getDisplayNames()) {
204 intl::RemoveICUCellMemory(gcx, obj, DisplayNamesObject::EstimatedMemoryUse);
205 delete displayNames;
206 }
207 }
208
209 bool JS::AddMozDisplayNamesConstructor(JSContext* cx, HandleObject intl) {
210 RootedObject ctor(cx, GlobalObject::createConstructor(
211 cx, MozDisplayNames, cx->names().DisplayNames, 2));
212 if (!ctor) {
213 return false;
214 }
215
216 RootedObject proto(
217 cx, GlobalObject::createBlankPrototype<PlainObject>(cx, cx->global()));
218 if (!proto) {
219 return false;
220 }
221
222 if (!LinkConstructorAndPrototype(cx, ctor, proto)) {
223 return false;
224 }
225
226 if (!JS_DefineFunctions(cx, ctor, displayNames_static_methods)) {
227 return false;
228 }
229
230 if (!JS_DefineFunctions(cx, proto, displayNames_methods)) {
231 return false;
232 }
233
234 if (!JS_DefineProperties(cx, proto, displayNames_properties)) {
235 return false;
236 }
237
238 RootedValue ctorValue(cx, ObjectValue(*ctor));
239 return DefineDataProperty(cx, intl, cx->names().DisplayNames, ctorValue, 0);
240 }
241
242 static mozilla::intl::DisplayNames* NewDisplayNames(
243 JSContext* cx, const char* locale,
244 mozilla::intl::DisplayNames::Options& options) {
245 auto result = mozilla::intl::DisplayNames::TryCreate(locale, options);
246 if (result.isErr()) {
247 intl::ReportInternalError(cx, result.unwrapErr());
248 return nullptr;
249 }
250 return result.unwrap().release();
251 }
252
253 static mozilla::intl::DisplayNames* GetOrCreateDisplayNames(
254 JSContext* cx, Handle<DisplayNamesObject*> displayNames, const char* locale,
255 mozilla::intl::DisplayNames::Options& options) {
256 // Obtain a cached mozilla::intl::DisplayNames object.
257 mozilla::intl::DisplayNames* dn = displayNames->getDisplayNames();
258 if (!dn) {
259 dn = NewDisplayNames(cx, locale, options);
260 if (!dn) {
261 return nullptr;
262 }
263 displayNames->setDisplayNames(dn);
264
265 intl::AddICUCellMemory(displayNames,
266 DisplayNamesObject::EstimatedMemoryUse);
267 }
268 return dn;
269 }
270
271 static void ReportInvalidOptionError(JSContext* cx, HandleString type,
272 HandleString option) {
273 if (UniqueChars optionStr = QuoteString(cx, option, '"')) {
274 if (UniqueChars typeStr = QuoteString(cx, type)) {
275 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
276 JSMSG_INVALID_OPTION_VALUE, typeStr.get(),
277 optionStr.get());
278 }
279 }
280 }
281
282 static void ReportInvalidOptionError(JSContext* cx, const char* type,
283 HandleString option) {
284 if (UniqueChars str = QuoteString(cx, option, '"')) {
285 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
286 JSMSG_INVALID_OPTION_VALUE, type, str.get());
287 }
288 }
289
290 static void ReportInvalidOptionError(JSContext* cx, const char* type,
291 double option) {
292 ToCStringBuf cbuf;
293 const char* str = NumberToCString(&cbuf, option);
294 MOZ_ASSERT(str);
295 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
296 JSMSG_INVALID_DIGITS_VALUE, str);
297 }
298
299 /**
300 * intl_ComputeDisplayName(displayNames, locale, calendar, style,
301 * languageDisplay, fallback, type, code)
302 */
303 bool js::intl_ComputeDisplayName(JSContext* cx, unsigned argc, Value* vp) {
304 CallArgs args = CallArgsFromVp(argc, vp);
305 MOZ_ASSERT(args.length() == 8);
306
307 Rooted<DisplayNamesObject*> displayNames(
308 cx, &args[0].toObject().as<DisplayNamesObject>());
309
310 UniqueChars locale = intl::EncodeLocale(cx, args[1].toString());
311 if (!locale) {
312 return false;
313 }
314
315 Rooted<JSLinearString*> calendar(cx, args[2].toString()->ensureLinear(cx));
316 if (!calendar) {
317 return false;
318 }
319
320 Rooted<JSLinearString*> code(cx, args[7].toString()->ensureLinear(cx));
321 if (!code) {
322 return false;
323 }
324
325 mozilla::intl::DisplayNames::Style style;
326 {
327 JSLinearString* styleStr = args[3].toString()->ensureLinear(cx);
328 if (!styleStr) {
329 return false;
330 }
331
332 if (StringEqualsLiteral(styleStr, "long")) {
333 style = mozilla::intl::DisplayNames::Style::Long;
334 } else if (StringEqualsLiteral(styleStr, "short")) {
335 style = mozilla::intl::DisplayNames::Style::Short;
336 } else if (StringEqualsLiteral(styleStr, "narrow")) {
337 style = mozilla::intl::DisplayNames::Style::Narrow;
338 } else {
339 MOZ_ASSERT(StringEqualsLiteral(styleStr, "abbreviated"));
340 style = mozilla::intl::DisplayNames::Style::Abbreviated;
341 }
342 }
343
344 mozilla::intl::DisplayNames::LanguageDisplay languageDisplay;
345 {
346 JSLinearString* language = args[4].toString()->ensureLinear(cx);
347 if (!language) {
348 return false;
349 }
350
351 if (StringEqualsLiteral(language, "dialect")) {
352 languageDisplay = mozilla::intl::DisplayNames::LanguageDisplay::Dialect;
353 } else {
354 MOZ_ASSERT(language->empty() ||
355 StringEqualsLiteral(language, "standard"));
356 languageDisplay = mozilla::intl::DisplayNames::LanguageDisplay::Standard;
357 }
358 }
359
360 mozilla::intl::DisplayNames::Fallback fallback;
361 {
362 JSLinearString* fallbackStr = args[5].toString()->ensureLinear(cx);
363 if (!fallbackStr) {
364 return false;
365 }
366
367 if (StringEqualsLiteral(fallbackStr, "none")) {
368 fallback = mozilla::intl::DisplayNames::Fallback::None;
369 } else {
370 MOZ_ASSERT(StringEqualsLiteral(fallbackStr, "code"));
371 fallback = mozilla::intl::DisplayNames::Fallback::Code;
372 }
373 }
374
375 Rooted<JSLinearString*> type(cx, args[6].toString()->ensureLinear(cx));
376 if (!type) {
377 return false;
378 }
379
380 mozilla::intl::DisplayNames::Options options{
381 style,
382 languageDisplay,
383 };
384
385 // If a calendar exists, set it as an option.
386 JS::UniqueChars calendarChars = nullptr;
387 if (!calendar->empty()) {
388 calendarChars = JS_EncodeStringToUTF8(cx, calendar);
389 if (!calendarChars) {
390 return false;
391 }
392 }
393
394 mozilla::intl::DisplayNames* dn =
395 GetOrCreateDisplayNames(cx, displayNames, locale.get(), options);
396 if (!dn) {
397 return false;
398 }
399
400 // The "code" is usually a small ASCII string, so try to avoid an allocation
401 // by copying it to the stack. Unfortunately we can't pass a string span of
402 // the JSString directly to the unified DisplayNames API, as the
403 // intl::FormatBuffer will be written to. This writing can trigger a GC and
404 // invalidate the span, creating a nogc rooting hazard.
405 JS::UniqueChars utf8 = nullptr;
406 unsigned char ascii[32];
407 mozilla::Span<const char> codeSpan = nullptr;
408 if (code->length() < 32 && code->hasLatin1Chars() && StringIsAscii(code)) {
409 JS::AutoCheckCannotGC nogc;
410 mozilla::PodCopy(ascii, code->latin1Chars(nogc), code->length());
411 codeSpan =
412 mozilla::Span(reinterpret_cast<const char*>(ascii), code->length());
413 } else {
414 utf8 = JS_EncodeStringToUTF8(cx, code);
415 if (!utf8) {
416 return false;
417 }
418 codeSpan = mozilla::MakeStringSpan(utf8.get());
419 }
420
421 intl::FormatBuffer<char16_t, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
422 mozilla::Result<mozilla::Ok, mozilla::intl::DisplayNamesError> result =
423 mozilla::Ok{};
424
425 if (StringEqualsLiteral(type, "language")) {
426 result = dn->GetLanguage(buffer, codeSpan, fallback);
427 } else if (StringEqualsLiteral(type, "script")) {
428 result = dn->GetScript(buffer, codeSpan, fallback);
429 } else if (StringEqualsLiteral(type, "region")) {
430 result = dn->GetRegion(buffer, codeSpan, fallback);
431 } else if (StringEqualsLiteral(type, "currency")) {
432 result = dn->GetCurrency(buffer, codeSpan, fallback);
433 } else if (StringEqualsLiteral(type, "calendar")) {
434 result = dn->GetCalendar(buffer, codeSpan, fallback);
435 } else if (StringEqualsLiteral(type, "weekday")) {
436 double d = LinearStringToNumber(code);
437 if (!IsInteger(d) || d < 1 || d > 7) {
438 ReportInvalidOptionError(cx, "weekday", d);
439 return false;
440 }
441 result =
442 dn->GetWeekday(buffer, static_cast<mozilla::intl::Weekday>(d),
443 mozilla::MakeStringSpan(calendarChars.get()), fallback);
444 } else if (StringEqualsLiteral(type, "month")) {
445 double d = LinearStringToNumber(code);
446 if (!IsInteger(d) || d < 1 || d > 13) {
447 ReportInvalidOptionError(cx, "month", d);
448 return false;
449 }
450
451 result =
452 dn->GetMonth(buffer, static_cast<mozilla::intl::Month>(d),
453 mozilla::MakeStringSpan(calendarChars.get()), fallback);
454
455 } else if (StringEqualsLiteral(type, "quarter")) {
456 double d = LinearStringToNumber(code);
457
458 // Inlined implementation of `IsValidQuarterCode ( quarter )`.
459 if (!IsInteger(d) || d < 1 || d > 4) {
460 ReportInvalidOptionError(cx, "quarter", d);
461 return false;
462 }
463
464 result =
465 dn->GetQuarter(buffer, static_cast<mozilla::intl::Quarter>(d),
466 mozilla::MakeStringSpan(calendarChars.get()), fallback);
467
468 } else if (StringEqualsLiteral(type, "dayPeriod")) {
469 mozilla::intl::DayPeriod dayPeriod;
470 if (StringEqualsLiteral(code, "am")) {
471 dayPeriod = mozilla::intl::DayPeriod::AM;
472 } else if (StringEqualsLiteral(code, "pm")) {
473 dayPeriod = mozilla::intl::DayPeriod::PM;
474 } else {
475 ReportInvalidOptionError(cx, "dayPeriod", code);
476 return false;
477 }
478 result = dn->GetDayPeriod(buffer, dayPeriod,
479 mozilla::MakeStringSpan(calendarChars.get()),
480 fallback);
481
482 } else {
483 MOZ_ASSERT(StringEqualsLiteral(type, "dateTimeField"));
484 mozilla::intl::DateTimeField field;
485 if (StringEqualsLiteral(code, "era")) {
486 field = mozilla::intl::DateTimeField::Era;
487 } else if (StringEqualsLiteral(code, "year")) {
488 field = mozilla::intl::DateTimeField::Year;
489 } else if (StringEqualsLiteral(code, "quarter")) {
490 field = mozilla::intl::DateTimeField::Quarter;
491 } else if (StringEqualsLiteral(code, "month")) {
492 field = mozilla::intl::DateTimeField::Month;
493 } else if (StringEqualsLiteral(code, "weekOfYear")) {
494 field = mozilla::intl::DateTimeField::WeekOfYear;
495 } else if (StringEqualsLiteral(code, "weekday")) {
496 field = mozilla::intl::DateTimeField::Weekday;
497 } else if (StringEqualsLiteral(code, "day")) {
498 field = mozilla::intl::DateTimeField::Day;
499 } else if (StringEqualsLiteral(code, "dayPeriod")) {
500 field = mozilla::intl::DateTimeField::DayPeriod;
501 } else if (StringEqualsLiteral(code, "hour")) {
502 field = mozilla::intl::DateTimeField::Hour;
503 } else if (StringEqualsLiteral(code, "minute")) {
504 field = mozilla::intl::DateTimeField::Minute;
505 } else if (StringEqualsLiteral(code, "second")) {
506 field = mozilla::intl::DateTimeField::Second;
507 } else if (StringEqualsLiteral(code, "timeZoneName")) {
508 field = mozilla::intl::DateTimeField::TimeZoneName;
509 } else {
510 ReportInvalidOptionError(cx, "dateTimeField", code);
511 return false;
512 }
513
514 intl::SharedIntlData& sharedIntlData = cx->runtime()->sharedIntlData.ref();
515 mozilla::intl::DateTimePatternGenerator* dtpgen =
516 sharedIntlData.getDateTimePatternGenerator(cx, locale.get());
517 if (!dtpgen) {
518 return false;
519 }
520
521 result = dn->GetDateTimeField(buffer, field, *dtpgen, fallback);
522 }
523
524 if (result.isErr()) {
525 switch (result.unwrapErr()) {
526 case mozilla::intl::DisplayNamesError::InternalError:
527 intl::ReportInternalError(cx);
528 break;
529 case mozilla::intl::DisplayNamesError::OutOfMemory:
530 ReportOutOfMemory(cx);
531 break;
532 case mozilla::intl::DisplayNamesError::InvalidOption:
533 ReportInvalidOptionError(cx, type, code);
534 break;
535 case mozilla::intl::DisplayNamesError::DuplicateVariantSubtag:
536 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
537 JSMSG_DUPLICATE_VARIANT_SUBTAG);
538 break;
539 case mozilla::intl::DisplayNamesError::InvalidLanguageTag:
540 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
541 JSMSG_INVALID_LANGUAGE_TAG);
542 break;
543 }
544 return false;
545 }
546
547 JSString* str = buffer.toString(cx);
548 if (!str) {
549 return false;
550 }
551
552 if (str->empty()) {
553 args.rval().setUndefined();
554 } else {
555 args.rval().setString(str);
556 }
557
558 return true;
559 }