Debian Codegraph @

js/src/builtin/intl/ListFormat.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 #include "builtin/intl/ListFormat.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/intl/ListFormat.h"
11
12 #include <stddef.h>
13
14 #include "builtin/Array.h"
15 #include "builtin/intl/CommonFunctions.h"
16 #include "builtin/intl/FormatBuffer.h"
17 #include "gc/GCContext.h"
18 #include "js/Utility.h"
19 #include "js/Vector.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 #include "vm/ObjectOperations-inl.h"
27
28 using namespace js;
29
30 const JSClassOps ListFormatObject::classOps_ = {
31 nullptr, // addProperty
32 nullptr, // delProperty
33 nullptr, // enumerate
34 nullptr, // newEnumerate
35 nullptr, // resolve
36 nullptr, // mayResolve
37 ListFormatObject::finalize, // finalize
38 nullptr, // call
39 nullptr, // construct
40 nullptr, // trace
41 };
42 const JSClass ListFormatObject::class_ = {
43 "Intl.ListFormat",
44 JSCLASS_HAS_RESERVED_SLOTS(ListFormatObject::SLOT_COUNT) |
45 JSCLASS_HAS_CACHED_PROTO(JSProto_ListFormat) |
46 JSCLASS_FOREGROUND_FINALIZE,
47 &ListFormatObject::classOps_,
48 &ListFormatObject::classSpec_,
49 };
50
51 const JSClass& ListFormatObject::protoClass_ = PlainObject::class_;
52
53 static bool listFormat_toSource(JSContext* cx, unsigned argc, Value* vp) {
54 CallArgs args = CallArgsFromVp(argc, vp);
55 args.rval().setString(cx->names().ListFormat);
56 return true;
57 }
58
59 static const JSFunctionSpec listFormat_static_methods[] = {
60 JS_SELF_HOSTED_FN("supportedLocalesOf",
61 "Intl_ListFormat_supportedLocalesOf", 1, 0),
62 JS_FS_END,
63 };
64
65 static const JSFunctionSpec listFormat_methods[] = {
66 JS_SELF_HOSTED_FN("resolvedOptions", "Intl_ListFormat_resolvedOptions", 0,
67 0),
68 JS_SELF_HOSTED_FN("format", "Intl_ListFormat_format", 1, 0),
69 JS_SELF_HOSTED_FN("formatToParts", "Intl_ListFormat_formatToParts", 1, 0),
70 JS_FN("toSource", listFormat_toSource, 0, 0),
71 JS_FS_END,
72 };
73
74 static const JSPropertySpec listFormat_properties[] = {
75 JS_STRING_SYM_PS(toStringTag, "Intl.ListFormat", JSPROP_READONLY),
76 JS_PS_END,
77 };
78
79 static bool ListFormat(JSContext* cx, unsigned argc, Value* vp);
80
81 const ClassSpec ListFormatObject::classSpec_ = {
82 GenericCreateConstructor<ListFormat, 0, gc::AllocKind::FUNCTION>,
83 GenericCreatePrototype<ListFormatObject>,
84 listFormat_static_methods,
85 nullptr,
86 listFormat_methods,
87 listFormat_properties,
88 nullptr,
89 ClassSpec::DontDefineConstructor,
90 };
91
92 /**
93 * Intl.ListFormat([ locales [, options]])
94 */
95 static bool ListFormat(JSContext* cx, unsigned argc, Value* vp) {
96 CallArgs args = CallArgsFromVp(argc, vp);
97
98 // Step 1.
99 if (!ThrowIfNotConstructing(cx, args, "Intl.ListFormat")) {
100 return false;
101 }
102
103 // Step 2 (Inlined 9.1.14, OrdinaryCreateFromConstructor).
104 RootedObject proto(cx);
105 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_ListFormat,
106 &proto)) {
107 return false;
108 }
109
110 Rooted<ListFormatObject*> listFormat(
111 cx, NewObjectWithClassProto<ListFormatObject>(cx, proto));
112 if (!listFormat) {
113 return false;
114 }
115
116 HandleValue locales = args.get(0);
117 HandleValue options = args.get(1);
118
119 // Step 3.
120 if (!intl::InitializeObject(cx, listFormat, cx->names().InitializeListFormat,
121 locales, options)) {
122 return false;
123 }
124
125 args.rval().setObject(*listFormat);
126 return true;
127 }
128
129 void js::ListFormatObject::finalize(JS::GCContext* gcx, JSObject* obj) {
130 MOZ_ASSERT(gcx->onMainThread());
131
132 mozilla::intl::ListFormat* lf =
133 obj->as<ListFormatObject>().getListFormatSlot();
134 if (lf) {
135 intl::RemoveICUCellMemory(gcx, obj, ListFormatObject::EstimatedMemoryUse);
136 delete lf;
137 }
138 }
139
140 /**
141 * Returns a new ListFormat with the locale and list formatting options
142 * of the given ListFormat.
143 */
144 static mozilla::intl::ListFormat* NewListFormat(
145 JSContext* cx, Handle<ListFormatObject*> listFormat) {
146 RootedObject internals(cx, intl::GetInternalsObject(cx, listFormat));
147 if (!internals) {
148 return nullptr;
149 }
150
151 RootedValue value(cx);
152
153 if (!GetProperty(cx, internals, internals, cx->names().locale, &value)) {
154 return nullptr;
155 }
156 UniqueChars locale = intl::EncodeLocale(cx, value.toString());
157 if (!locale) {
158 return nullptr;
159 }
160
161 mozilla::intl::ListFormat::Options options;
162
163 using ListFormatType = mozilla::intl::ListFormat::Type;
164 if (!GetProperty(cx, internals, internals, cx->names().type, &value)) {
165 return nullptr;
166 }
167 {
168 JSLinearString* strType = value.toString()->ensureLinear(cx);
169 if (!strType) {
170 return nullptr;
171 }
172
173 if (StringEqualsLiteral(strType, "conjunction")) {
174 options.mType = ListFormatType::Conjunction;
175 } else if (StringEqualsLiteral(strType, "disjunction")) {
176 options.mType = ListFormatType::Disjunction;
177 } else {
178 MOZ_ASSERT(StringEqualsLiteral(strType, "unit"));
179 options.mType = ListFormatType::Unit;
180 }
181 }
182
183 using ListFormatStyle = mozilla::intl::ListFormat::Style;
184 if (!GetProperty(cx, internals, internals, cx->names().style, &value)) {
185 return nullptr;
186 }
187 {
188 JSLinearString* strStyle = value.toString()->ensureLinear(cx);
189 if (!strStyle) {
190 return nullptr;
191 }
192
193 if (StringEqualsLiteral(strStyle, "long")) {
194 options.mStyle = ListFormatStyle::Long;
195 } else if (StringEqualsLiteral(strStyle, "short")) {
196 options.mStyle = ListFormatStyle::Short;
197 } else {
198 MOZ_ASSERT(StringEqualsLiteral(strStyle, "narrow"));
199 options.mStyle = ListFormatStyle::Narrow;
200 }
201 }
202
203 auto result = mozilla::intl::ListFormat::TryCreate(
204 mozilla::MakeStringSpan(locale.get()), options);
205
206 if (result.isOk()) {
207 return result.unwrap().release();
208 }
209
210 js::intl::ReportInternalError(cx, result.unwrapErr());
211 return nullptr;
212 }
213
214 static mozilla::intl::ListFormat* GetOrCreateListFormat(
215 JSContext* cx, Handle<ListFormatObject*> listFormat) {
216 // Obtain a cached mozilla::intl::ListFormat object.
217 mozilla::intl::ListFormat* lf = listFormat->getListFormatSlot();
218 if (lf) {
219 return lf;
220 }
221
222 lf = NewListFormat(cx, listFormat);
223 if (!lf) {
224 return nullptr;
225 }
226 listFormat->setListFormatSlot(lf);
227
228 intl::AddICUCellMemory(listFormat, ListFormatObject::EstimatedMemoryUse);
229 return lf;
230 }
231
232 /**
233 * FormatList ( listFormat, list )
234 */
235 static bool FormatList(JSContext* cx, mozilla::intl::ListFormat* lf,
236 const mozilla::intl::ListFormat::StringList& list,
237 MutableHandleValue result) {
238 intl::FormatBuffer<char16_t, intl::INITIAL_CHAR_BUFFER_SIZE> formatBuffer(cx);
239 auto formatResult = lf->Format(list, formatBuffer);
240 if (formatResult.isErr()) {
241 js::intl::ReportInternalError(cx, formatResult.unwrapErr());
242 return false;
243 }
244
245 JSString* str = formatBuffer.toString(cx);
246 if (!str) {
247 return false;
248 }
249 result.setString(str);
250 return true;
251 }
252
253 /**
254 * FormatListToParts ( listFormat, list )
255 */
256 static bool FormatListToParts(JSContext* cx, mozilla::intl::ListFormat* lf,
257 const mozilla::intl::ListFormat::StringList& list,
258 MutableHandleValue result) {
259 intl::FormatBuffer<char16_t, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
260 mozilla::intl::ListFormat::PartVector parts;
261 auto formatResult = lf->FormatToParts(list, buffer, parts);
262 if (formatResult.isErr()) {
263 intl::ReportInternalError(cx, formatResult.unwrapErr());
264 return false;
265 }
266
267 RootedString overallResult(cx, buffer.toString(cx));
268 if (!overallResult) {
269 return false;
270 }
271
272 Rooted<ArrayObject*> partsArray(
273 cx, NewDenseFullyAllocatedArray(cx, parts.length()));
274 if (!partsArray) {
275 return false;
276 }
277 partsArray->ensureDenseInitializedLength(0, parts.length());
278
279 RootedObject singlePart(cx);
280 RootedValue val(cx);
281
282 size_t index = 0;
283 size_t beginIndex = 0;
284 for (const mozilla::intl::ListFormat::Part& part : parts) {
285 singlePart = NewPlainObject(cx);
286 if (!singlePart) {
287 return false;
288 }
289
290 if (part.first == mozilla::intl::ListFormat::PartType::Element) {
291 val = StringValue(cx->names().element);
292 } else {
293 val = StringValue(cx->names().literal);
294 }
295
296 if (!DefineDataProperty(cx, singlePart, cx->names().type, val)) {
297 return false;
298 }
299
300 // There could be an empty string so the endIndex coule be equal to
301 // beginIndex.
302 MOZ_ASSERT(part.second >= beginIndex);
303 JSLinearString* partStr = NewDependentString(cx, overallResult, beginIndex,
304 part.second - beginIndex);
305 if (!partStr) {
306 return false;
307 }
308 val = StringValue(partStr);
309 if (!DefineDataProperty(cx, singlePart, cx->names().value, val)) {
310 return false;
311 }
312
313 beginIndex = part.second;
314 partsArray->initDenseElement(index++, ObjectValue(*singlePart));
315 }
316
317 MOZ_ASSERT(index == parts.length());
318 MOZ_ASSERT(beginIndex == buffer.length());
319 result.setObject(*partsArray);
320
321 return true;
322 }
323
324 bool js::intl_FormatList(JSContext* cx, unsigned argc, Value* vp) {
325 CallArgs args = CallArgsFromVp(argc, vp);
326 MOZ_ASSERT(args.length() == 3);
327
328 Rooted<ListFormatObject*> listFormat(
329 cx, &args[0].toObject().as<ListFormatObject>());
330
331 bool formatToParts = args[2].toBoolean();
332
333 mozilla::intl::ListFormat* lf = GetOrCreateListFormat(cx, listFormat);
334 if (!lf) {
335 return false;
336 }
337
338 // Collect all strings and their lengths.
339 //
340 // 'strings' takes the ownership of those strings, and 'list' will be passed
341 // to mozilla::intl::ListFormat as a Span.
342 Vector<UniqueTwoByteChars, mozilla::intl::DEFAULT_LIST_LENGTH> strings(cx);
343 mozilla::intl::ListFormat::StringList list;
344
345 Rooted<ArrayObject*> listObj(cx, &args[1].toObject().as<ArrayObject>());
346 RootedValue value(cx);
347 uint32_t listLen = listObj->length();
348 for (uint32_t i = 0; i < listLen; i++) {
349 if (!GetElement(cx, listObj, listObj, i, &value)) {
350 return false;
351 }
352
353 JSLinearString* linear = value.toString()->ensureLinear(cx);
354 if (!linear) {
355 return false;
356 }
357
358 size_t linearLength = linear->length();
359
360 UniqueTwoByteChars chars = cx->make_pod_array<char16_t>(linearLength);
361 if (!chars) {
362 return false;
363 }
364 CopyChars(chars.get(), *linear);
365
366 if (!strings.append(std::move(chars))) {
367 return false;
368 }
369
370 if (!list.emplaceBack(strings[i].get(), linearLength)) {
371 return false;
372 }
373 }
374
375 if (formatToParts) {
376 return FormatListToParts(cx, lf, list, args.rval());
377 }
378 return FormatList(cx, lf, list, args.rval());
379 }