Debian Codegraph @

intl/components/src/DateTimeFormat.h

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 #ifndef intl_components_DateTimeFormat_h_
5 #define intl_components_DateTimeFormat_h_
6 #include <functional>
7 #include "unicode/udat.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/intl/ICU4CGlue.h"
11 #include "mozilla/intl/ICUError.h"
12
13 #include "mozilla/intl/DateTimePart.h"
14 #include "mozilla/intl/DateTimePatternGenerator.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/Span.h"
17 #include "mozilla/Try.h"
18 #include "mozilla/UniquePtr.h"
19 #include "mozilla/Utf8.h"
20 #include "mozilla/Variant.h"
21 #include "mozilla/Vector.h"
22
23 /*
24 * To work around webcompat problems caused by Narrow No-Break Space in
25 * formatted date/time output, where existing code on the web naively
26 * assumes there will be a normal Space, we replace any occurrences of
27 * U+202F in the formatted results with U+0020.
28 *
29 * The intention is to undo this hack once other major browsers are also
30 * ready to ship with the updated (ICU72) i18n data that uses NNBSP.
31 *
32 * See https://bugzilla.mozilla.org/show_bug.cgi?id=1806042 for details,
33 * and see DateIntervalFormat.cpp for the other piece of this hack.
34 */
35 #define DATE_TIME_FORMAT_REPLACE_SPECIAL_SPACES 1
36
37 namespace mozilla::intl {
38
39 #if DATE_TIME_FORMAT_REPLACE_SPECIAL_SPACES
40 static inline bool IsSpecialSpace(char16_t c) {
41 // NARROW NO-BREAK SPACE and THIN SPACE
42 return c == 0x202F || c == 0x2009;
43 }
44 #endif
45
46 class Calendar;
47
48 /**
49 * Intro to mozilla::intl::DateTimeFormat
50 * ======================================
51 *
52 * This component is a Mozilla-focused API for the date formatting provided by
53 * ICU. The methods internally call out to ICU4C. This is responsible for and
54 * owns any resources opened through ICU, through RAII.
55 *
56 * The construction of a DateTimeFormat contains the majority of the cost
57 * of the DateTimeFormat operation. DateTimeFormat::TryFormat should be
58 * relatively inexpensive after the initial construction.
59 *
60 * This class supports creating from Styles (a fixed set of options) and from a
61 * components bag (a list of components and their lengths).
62 *
63 * This API serves to back the ECMA-402 Intl.DateTimeFormat API.
64 * https://tc39.es/ecma402/#datetimeformat-objects
65 *
66 *
67 * ECMA-402 Intl.DateTimeFormat API and implementation details with ICU
68 * skeletons and patterns.
69 * ====================================================================
70 *
71 * Different locales have different ways to display dates using the same
72 * basic components. For example, en-US might use "Sept. 24, 2012" while
73 * fr-FR might use "24 Sept. 2012". The intent of Intl.DateTimeFormat is to
74 * permit production of a format for the locale that best matches the
75 * set of date-time components and their desired representation as specified
76 * by the API client.
77 *
78 * ICU4C supports specification of date and time formats in three ways:
79 *
80 * 1) A style is just one of the identifiers FULL, LONG, MEDIUM, or SHORT.
81 * The date-time components included in each style and their representation
82 * are defined by ICU using CLDR locale data (CLDR is the Unicode
83 * Consortium's Common Locale Data Repository).
84 *
85 * 2) A skeleton is a string specifying which date-time components to include,
86 * and which representations to use for them. For example, "yyyyMMMMdd"
87 * specifies a year with at least four digits, a full month name, and a
88 * two-digit day. It does not specify in which order the components appear,
89 * how they are separated, the localized strings for textual components
90 * (such as weekday or month), whether the month is in format or
91 * stand-alone form¹, or the numbering system used for numeric components.
92 * All that information is filled in by ICU using CLDR locale data.
93 * ¹ The format form is the one used in formatted strings that include a
94 * day; the stand-alone form is used when not including days, e.g., in
95 * calendar headers. The two forms differ at least in some Slavic languages,
96 * e.g. Russian: "22 марта 2013 г." vs. "Март 2013".
97 *
98 * 3) A pattern is a string specifying which date-time components to include,
99 * in which order, with which separators, in which grammatical case. For
100 * example, "EEEE, d MMMM y" specifies the full localized weekday name,
101 * followed by comma and space, followed by the day, followed by space,
102 * followed by the full month name in format form, followed by space,
103 * followed by the full year. It
104 * still does not specify localized strings for textual components and the
105 * numbering system - these are determined by ICU using CLDR locale data or
106 * possibly API parameters.
107 *
108 * All actual formatting in ICU4C is done with patterns; styles and skeletons
109 * have to be mapped to patterns before processing.
110 *
111 * The options of Intl.DateTimeFormat most closely correspond to ICU skeletons.
112 * This implementation therefore converts DateTimeFormat options to ICU
113 * skeletons, and then lets ICU map skeletons to actual ICU patterns. The
114 * pattern may not directly correspond to what the skeleton requests, as the
115 * mapper (UDateTimePatternGenerator) is constrained by the available locale
116 * data for the locale.
117 *
118 * An ICU pattern represents the information of the following DateTimeFormat
119 * internal properties described in the specification, which therefore don't
120 * exist separately in the implementation:
121 * - [[weekday]], [[era]], [[year]], [[month]], [[day]], [[hour]], [[minute]],
122 * [[second]], [[timeZoneName]]
123 * - [[hour12]]
124 * - [[hourCycle]]
125 * - [[hourNo0]]
126 * When needed for the resolvedOptions method, the resolveICUPattern function
127 * queries the UDateFormat's internal pattern and then maps the it back to the
128 * specified properties of the object returned by resolvedOptions.
129 *
130 * ICU date-time skeletons and patterns aren't fully documented in the ICU
131 * documentation (see http://bugs.icu-project.org/trac/ticket/9627). The best
132 * documentation at this point is in UTR 35:
133 * http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
134 *
135 * Future support for ICU4X
136 * ========================
137 * This implementation exposes a components bag, and internally handles the
138 * complexity of working with skeletons and patterns to generate the correct
139 * results. In the future, if and when we switch to ICU4X, the complexities of
140 * manipulating patterns will be able to be removed, as ICU4X will directly know
141 * how to apply the components bag.
142 */
143 class DateTimeFormat final {
144 public:
145 /**
146 * The hour cycle for components.
147 */
148 enum class HourCycle {
149 H11,
150 H12,
151 H23,
152 H24,
153 };
154
155 /**
156 * The style for dates or times.
157 */
158 enum class Style {
159 Full,
160 Long,
161 Medium,
162 Short,
163 };
164
165 /**
166 * A bag of options to determine the length of the time and date styles. The
167 * hour cycle can be overridden.
168 */
169 struct StyleBag {
170 Maybe<Style> date = Nothing();
171 Maybe<Style> time = Nothing();
172 Maybe<HourCycle> hourCycle = Nothing();
173 Maybe<bool> hour12 = Nothing();
174 };
175
176 /**
177 * How to to display numeric components such as the year and the day.
178 */
179 enum class Numeric {
180 Numeric,
181 TwoDigit,
182 };
183
184 /**
185 * How to display the text components, such as the weekday or day period.
186 */
187 enum class Text {
188 Long,
189 Short,
190 Narrow,
191 };
192
193 /**
194 * How to display the month.
195 */
196 enum class Month {
197 Numeric,
198 TwoDigit,
199 Long,
200 Short,
201 Narrow,
202 };
203
204 /**
205 * How to display the time zone name.
206 */
207 enum class TimeZoneName {
208 Long,
209 Short,
210 ShortOffset,
211 LongOffset,
212 ShortGeneric,
213 LongGeneric,
214 };
215
216 /**
217 * Get static strings representing the enums. These match ECMA-402's resolved
218 * options.
219 * https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype.resolvedoptions
220 */
221 static const char* ToString(DateTimeFormat::HourCycle aHourCycle);
222 static const char* ToString(DateTimeFormat::Style aStyle);
223 static const char* ToString(DateTimeFormat::Numeric aNumeric);
224 static const char* ToString(DateTimeFormat::Text aText);
225 static const char* ToString(DateTimeFormat::Month aMonth);
226 static const char* ToString(DateTimeFormat::TimeZoneName aTimeZoneName);
227
228 /**
229 * A components bag specifies the components used to display a DateTime. Each
230 * component can be styled individually, and ICU will attempt to create a best
231 * match for a given locale.
232 */
233 struct ComponentsBag {
234 Maybe<Text> era = Nothing();
235 Maybe<Numeric> year = Nothing();
236 Maybe<Month> month = Nothing();
237 Maybe<Numeric> day = Nothing();
238 Maybe<Text> weekday = Nothing();
239 Maybe<Numeric> hour = Nothing();
240 Maybe<Numeric> minute = Nothing();
241 Maybe<Numeric> second = Nothing();
242 Maybe<TimeZoneName> timeZoneName = Nothing();
243 Maybe<bool> hour12 = Nothing();
244 Maybe<HourCycle> hourCycle = Nothing();
245 Maybe<Text> dayPeriod = Nothing();
246 Maybe<uint8_t> fractionalSecondDigits = Nothing();
247 };
248
249 // Do not allow copy as this class owns the ICU resource. Move is not
250 // currently implemented, but a custom move operator could be created if
251 // needed.
252 DateTimeFormat(const DateTimeFormat&) = delete;
253 DateTimeFormat& operator=(const DateTimeFormat&) = delete;
254
255 // mozilla::Vector can avoid heap allocations for small transient buffers.
256 using PatternVector = Vector<char16_t, 128>;
257 using SkeletonVector = Vector<char16_t, 16>;
258
259 /**
260 * Create a DateTimeFormat from styles.
261 *
262 * The "style" model uses different options for formatting a date or time
263 * based on how the result will be styled, rather than picking specific
264 * fields or lengths.
265 *
266 * Takes an optional time zone which will override the user's default
267 * time zone. This is a UTF-16 string that takes the form "GMT±hh:mm", or
268 * an IANA time zone identifier, e.g. "America/Chicago".
269 */
270 static Result<UniquePtr<DateTimeFormat>, ICUError> TryCreateFromStyle(
271 Span<const char> aLocale, const StyleBag& aStyleBag,
272 DateTimePatternGenerator* aDateTimePatternGenerator,
273 Maybe<Span<const char16_t>> aTimeZoneOverride = Nothing{});
274
275 private:
276 /**
277 * Create a DateTimeFormat from a UTF-16 skeleton.
278 *
279 * A skeleton is an unordered list of fields that are used to find an
280 * appropriate date time format pattern. Example skeletons would be "yMd",
281 * "yMMMd", "EBhm". If the skeleton includes string literals or other
282 * information, it will be discarded when matching against skeletons.
283 *
284 * Takes an optional time zone which will override the user's default
285 * time zone. This is a string that takes the form "GMT±hh:mm", or
286 * an IANA time zone identifier, e.g. "America/Chicago".
287 */
288 static Result<UniquePtr<DateTimeFormat>, ICUError> TryCreateFromSkeleton(
289 Span<const char> aLocale, Span<const char16_t> aSkeleton,
290 DateTimePatternGenerator* aDateTimePatternGenerator,
291 Maybe<DateTimeFormat::HourCycle> aHourCycle,
292 Maybe<Span<const char16_t>> aTimeZoneOverride);
293
294 public:
295 /**
296 * Create a DateTimeFormat from a ComponentsBag.
297 *
298 * See the ComponentsBag for additional documentation.
299 *
300 * Takes an optional time zone which will override the user's default
301 * time zone. This is a string that takes the form "GMT±hh:mm", or
302 * an IANA time zone identifier, e.g. "America/Chicago".
303 */
304 static Result<UniquePtr<DateTimeFormat>, ICUError> TryCreateFromComponents(
305 Span<const char> aLocale, const ComponentsBag& bag,
306 DateTimePatternGenerator* aDateTimePatternGenerator,
307 Maybe<Span<const char16_t>> aTimeZoneOverride = Nothing{});
308
309 /**
310 * Create a DateTimeFormat from a raw pattern.
311 *
312 * Warning: This method should not be added to new code. In the near future we
313 * plan to remove it.
314 */
315 static Result<UniquePtr<DateTimeFormat>, ICUError> TryCreateFromPattern(
316 Span<const char> aLocale, Span<const char16_t> aPattern,
317 Maybe<Span<const char16_t>> aTimeZoneOverride = Nothing{});
318
319 /**
320 * Use the format settings to format a date time into a string. The non-null
321 * terminated string will be placed into the provided buffer. The idea behind
322 * this API is that the constructor is expensive, and then the format
323 * operation is cheap.
324 *
325 * aUnixEpoch is the number of milliseconds since 1 January 1970, UTC.
326 */
327 template <typename B>
328 ICUResult TryFormat(double aUnixEpoch, B& aBuffer) const {
329 static_assert(
330 std::is_same_v<typename B::CharType, unsigned char> ||
331 std::is_same_v<typename B::CharType, char> ||
332 std::is_same_v<typename B::CharType, char16_t>,
333 "The only buffer CharTypes supported by DateTimeFormat are char "
334 "(for UTF-8 support) and char16_t (for UTF-16 support).");
335
336 if constexpr (std::is_same_v<typename B::CharType, char> ||
337 std::is_same_v<typename B::CharType, unsigned char>) {
338 // The output buffer is UTF-8, but ICU uses UTF-16 internally.
339
340 // Write the formatted date into the u16Buffer.
341 PatternVector u16Vec;
342
343 auto result = FillBufferWithICUCall(
344 u16Vec, [this, &aUnixEpoch](UChar* target, int32_t length,
345 UErrorCode* status) {
346 return udat_format(mDateFormat, aUnixEpoch, target, length,
347 /* UFieldPosition* */ nullptr, status);
348 });
349 if (result.isErr()) {
350 return result;
351 }
352
353 #if DATE_TIME_FORMAT_REPLACE_SPECIAL_SPACES
354 for (auto& c : u16Vec) {
355 if (IsSpecialSpace(c)) {
356 c = ' ';
357 }
358 }
359 #endif
360
361 if (!FillBuffer(u16Vec, aBuffer)) {
362 return Err(ICUError::OutOfMemory);
363 }
364 return Ok{};
365 } else {
366 static_assert(std::is_same_v<typename B::CharType, char16_t>);
367
368 // The output buffer is UTF-16. ICU can output directly into this buffer.
369 auto result = FillBufferWithICUCall(
370 aBuffer, [&](UChar* target, int32_t length, UErrorCode* status) {
371 return udat_format(mDateFormat, aUnixEpoch, target, length, nullptr,
372 status);
373 });
374 if (result.isErr()) {
375 return result;
376 }
377
378 #if DATE_TIME_FORMAT_REPLACE_SPECIAL_SPACES
379 for (auto& c : Span(aBuffer.data(), aBuffer.length())) {
380 if (IsSpecialSpace(c)) {
381 c = ' ';
382 }
383 }
384 #endif
385
386 return Ok{};
387 }
388 };
389
390 /**
391 * Format the Unix epoch time into a DateTimePartVector.
392 *
393 * The caller has to create the buffer and the vector and pass to this method.
394 * The formatted string will be stored in the buffer and formatted parts in
395 * the vector.
396 *
397 * aUnixEpoch is the number of milliseconds since 1 January 1970, UTC.
398 *
399 * See:
400 * https://tc39.es/ecma402/#sec-formatdatetimetoparts
401 */
402 template <typename B>
403 ICUResult TryFormatToParts(double aUnixEpoch, B& aBuffer,
404 DateTimePartVector& aParts) const {
405 static_assert(std::is_same_v<typename B::CharType, char16_t>,
406 "Only char16_t is supported (for UTF-16 support) now.");
407
408 UErrorCode status = U_ZERO_ERROR;
409 UFieldPositionIterator* fpositer = ufieldpositer_open(&status);
410 if (U_FAILURE(status)) {
411 return Err(ToICUError(status));
412 }
413
414 auto result = FillBufferWithICUCall(
415 aBuffer, [this, aUnixEpoch, fpositer](UChar* chars, int32_t size,
416 UErrorCode* status) {
417 return udat_formatForFields(mDateFormat, aUnixEpoch, chars, size,
418 fpositer, status);
419 });
420 if (result.isErr()) {
421 ufieldpositer_close(fpositer);
422 return result.propagateErr();
423 }
424
425 #if DATE_TIME_FORMAT_REPLACE_SPECIAL_SPACES
426 for (auto& c : Span(aBuffer.data(), aBuffer.length())) {
427 if (IsSpecialSpace(c)) {
428 c = ' ';
429 }
430 }
431 #endif
432
433 return TryFormatToParts(fpositer, aBuffer.length(), aParts);
434 }
435
436 /**
437 * Copies the pattern for the current DateTimeFormat to a buffer.
438 *
439 * Warning: This method should not be added to new code. In the near future we
440 * plan to remove it.
441 */
442 template <typename B>
443 ICUResult GetPattern(B& aBuffer) const {
444 return FillBufferWithICUCall(
445 aBuffer, [&](UChar* target, int32_t length, UErrorCode* status) {
446 return udat_toPattern(mDateFormat, /* localized*/ false, target,
447 length, status);
448 });
449 }
450
451 /**
452 * Copies the skeleton that was used to generate the current DateTimeFormat to
453 * the given buffer. If no skeleton was used, then a skeleton is generated
454 * from the resolved pattern. Note that going from skeleton -> resolved
455 * pattern -> skeleton is not a 1:1 mapping, as the resolved pattern can
456 * contain different symbols than the requested skeleton.
457 *
458 * Warning: This method should not be added to new code. In the near future we
459 * plan to remove it.
460 */
461 template <typename B>
462 ICUResult GetOriginalSkeleton(B& aBuffer) {
463 static_assert(std::is_same_v<typename B::CharType, char16_t>);
464 if (mOriginalSkeleton.length() == 0) {
465 // Generate a skeleton from the resolved pattern, there was no originally
466 // cached skeleton.
467 PatternVector pattern{};
468 VectorToBufferAdaptor buffer(pattern);
469 MOZ_TRY(GetPattern(buffer));
470
471 VectorToBufferAdaptor skeleton(mOriginalSkeleton);
472 MOZ_TRY(DateTimePatternGenerator::GetSkeleton(pattern, skeleton));
473 }
474
475 if (!FillBuffer(mOriginalSkeleton, aBuffer)) {
476 return Err(ICUError::OutOfMemory);
477 }
478 return Ok();
479 }
480
481 /**
482 * Determines the resolved components for the current DateTimeFormat.
483 *
484 * When a DateTimeFormat is created, even from a components bag, the resolved
485 * formatter may tweak the resolved components depending on the configuration
486 * and the locale.
487 *
488 * For the implementation, with ICU4C, this takes a string pattern and maps it
489 * back to a ComponentsBag.
490 */
491 Result<ComponentsBag, ICUError> ResolveComponents();
492
493 ~DateTimeFormat();
494
495 /**
496 * Clones the Calendar from a DateTimeFormat, and sets its time with the
497 * relative milliseconds since 1 January 1970, UTC.
498 */
499 Result<UniquePtr<Calendar>, ICUError> CloneCalendar(double aUnixEpoch) const;
500
501 /**
502 * Return the hour cycle used in the input pattern or Nothing if none was
503 * found.
504 */
505 static Maybe<DateTimeFormat::HourCycle> HourCycleFromPattern(
506 Span<const char16_t> aPattern);
507
508 using HourCyclesVector = Vector<HourCycle, 4>;
509
510 /**
511 * Returns the allowed hour cycles for the input locale.
512 *
513 * NOTE: This function currently takes a language subtag and an optional
514 * region subtag. This is a restriction until bug 1719746 has migrated
515 * language tag processing into the unified Intl component. After bug 1719746,
516 * this function should be changed to accept a single locale tag.
517 */
518 static Result<HourCyclesVector, ICUError> GetAllowedHourCycles(
519 Span<const char> aLanguage, Maybe<Span<const char>> aRegion);
520
521 /**
522 * Returns an iterator over all supported date-time formatter locales.
523 *
524 * The returned strings are ICU locale identifiers and NOT BCP 47 language
525 * tags.
526 *
527 * Also see <https://unicode-org.github.io/icu/userguide/locale>.
528 */
529 static auto GetAvailableLocales() {
530 return AvailableLocalesEnumeration<udat_countAvailable,
531 udat_getAvailable>();
532 }
533
534 /**
535 * Return the time separator for the given locale and numbering system.
536 */
537 template <typename B>
538 static ICUResult GetTimeSeparator(Span<const char> aLocale,
539 Span<const char> aNumberingSystem,
540 B& aBuffer) {
541 static_assert(std::is_same_v<typename B::CharType, char16_t>);
542 auto separator = GetTimeSeparator(aLocale, aNumberingSystem);
543 if (separator.isErr()) {
544 return separator.propagateErr();
545 }
546 if (!FillBuffer(separator.unwrap(), aBuffer)) {
547 return Err(ICUError::OutOfMemory);
548 }
549 return Ok();
550 }
551
552 private:
553 explicit DateTimeFormat(UDateFormat* aDateFormat);
554
555 ICUResult CacheSkeleton(Span<const char16_t> aSkeleton);
556
557 ICUResult TryFormatToParts(UFieldPositionIterator* aFieldPositionIterator,
558 size_t aSpanSize,
559 DateTimePartVector& aParts) const;
560 /**
561 * Replaces all hour pattern characters in |patternOrSkeleton| to use the
562 * matching hour representation for |hourCycle|.
563 */
564 static void ReplaceHourSymbol(Span<char16_t> aPatternOrSkeleton,
565 DateTimeFormat::HourCycle aHourCycle);
566
567 /**
568 * Find a matching pattern using the requested hour-12 options.
569 *
570 * This function is needed to work around the following two issues.
571 * - https://unicode-org.atlassian.net/browse/ICU-21023
572 * - https://unicode-org.atlassian.net/browse/CLDR-13425
573 *
574 * We're currently using a relatively simple workaround, which doesn't give
575 * the most accurate results. For example:
576 *
577 * ```
578 * var dtf = new Intl.DateTimeFormat("en", {
579 * timeZone: "UTC",
580 * dateStyle: "long",
581 * timeStyle: "long",
582 * hourCycle: "h12",
583 * });
584 * print(dtf.format(new Date("2020-01-01T00:00Z")));
585 * ```
586 *
587 * Returns the pattern "MMMM d, y 'at' h:mm:ss a z", but when going through
588 * |DateTimePatternGenerator::GetSkeleton| and then
589 * |DateTimePatternGenerator::GetBestPattern| to find an equivalent pattern
590 * for "h23", we'll end up with the pattern "MMMM d, y, HH:mm:ss z", so the
591 * combinator element " 'at' " was lost in the process.
592 */
593 static ICUResult FindPatternWithHourCycle(
594 DateTimePatternGenerator& aDateTimePatternGenerator,
595 DateTimeFormat::PatternVector& aPattern, bool aHour12,
596 DateTimeFormat::SkeletonVector& aSkeleton);
597
598 static Result<Span<const char16_t>, ICUError> GetTimeSeparator(
599 Span<const char> aLocale, Span<const char> aNumberingSystem);
600
601 UDateFormat* mDateFormat = nullptr;
602
603 SkeletonVector mOriginalSkeleton;
604 };
605
606 } // namespace mozilla::intl
607
608 #endif