Debian Codegraph @

js/src/builtin/temporal/ToString.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/temporal/ToString.h"
8
9 #include "mozilla/Assertions.h"
10
11 #include <cstdlib>
12 #include <stddef.h>
13 #include <stdint.h>
14 #include <string_view>
15
16 #include "builtin/temporal/Calendar.h"
17 #include "builtin/temporal/Crash.h"
18 #include "builtin/temporal/Instant.h"
19 #include "builtin/temporal/PlainDate.h"
20 #include "builtin/temporal/PlainDateTime.h"
21 #include "builtin/temporal/PlainMonthDay.h"
22 #include "builtin/temporal/PlainYearMonth.h"
23 #include "builtin/temporal/Temporal.h"
24 #include "builtin/temporal/TemporalTypes.h"
25 #include "builtin/temporal/TemporalUnit.h"
26 #include "builtin/temporal/TimeZone.h"
27 #include "builtin/temporal/ZonedDateTime.h"
28 #include "js/RootingAPI.h"
29 #include "util/StringBuilder.h"
30 #include "vm/StringType.h"
31
32 using namespace js;
33 using namespace js::temporal;
34
35 enum class TemporalStringFormat {
36 None,
37 Date,
38 Time,
39 DateTime,
40 YearMonth,
41 MonthDay,
42 ZonedDateTime,
43 Instant,
44 };
45
46 enum class Critical : bool { No, Yes };
47
48 class TemporalStringBuilder {
49 JSStringBuilder sb_;
50
51 TemporalStringFormat kind_ = TemporalStringFormat::None;
52
53 #ifdef DEBUG
54 bool reserved_ = false;
55 #endif
56
57 static constexpr size_t reserveAmount(TemporalStringFormat format) {
58 // Note: This doesn't reserve too much space, because the string builder
59 // already internally reserves space for 64 characters.
60
61 constexpr size_t datePart = 1 + 6 + 1 + 2 + 1 + 2; // 13
62 constexpr size_t timePart = 2 + 1 + 2 + 1 + 2 + 1 + 9; // 18
63 constexpr size_t dateTimePart = datePart + 1 + timePart; // including 'T'
64 constexpr size_t timeZoneOffsetPart = 1 + 2 + 1 + 2; // 6
65
66 switch (format) {
67 case TemporalStringFormat::Date:
68 case TemporalStringFormat::YearMonth:
69 case TemporalStringFormat::MonthDay:
70 return datePart;
71 case TemporalStringFormat::Time:
72 return timePart;
73 case TemporalStringFormat::DateTime:
74 return dateTimePart;
75 case TemporalStringFormat::ZonedDateTime:
76 return dateTimePart + timeZoneOffsetPart;
77 case TemporalStringFormat::Instant:
78 return dateTimePart + timeZoneOffsetPart;
79 case TemporalStringFormat::None:
80 break;
81 }
82 JS_CONSTEXPR_CRASH("invalid reserve amount");
83 }
84
85 public:
86 TemporalStringBuilder(JSContext* cx, TemporalStringFormat kind)
87 : sb_(cx), kind_(kind) {
88 MOZ_ASSERT(kind != TemporalStringFormat::None);
89 }
90
91 bool reserve() {
92 MOZ_ASSERT(!reserved_);
93
94 if (!sb_.reserve(reserveAmount(kind_))) {
95 return false;
96 }
97
98 #ifdef DEBUG
99 reserved_ = true;
100 #endif
101 return true;
102 }
103
104 void append(char value) {
105 MOZ_ASSERT(reserved_);
106 sb_.infallibleAppend(value);
107 }
108
109 void appendTwoDigit(int32_t value) {
110 MOZ_ASSERT(0 <= value && value <= 99);
111 MOZ_ASSERT(reserved_);
112
113 sb_.infallibleAppend(char('0' + (value / 10)));
114 sb_.infallibleAppend(char('0' + (value % 10)));
115 }
116
117 void appendFourDigit(int32_t value) {
118 MOZ_ASSERT(0 <= value && value <= 9999);
119 MOZ_ASSERT(reserved_);
120
121 sb_.infallibleAppend(char('0' + (value / 1000)));
122 sb_.infallibleAppend(char('0' + (value % 1000) / 100));
123 sb_.infallibleAppend(char('0' + (value % 100) / 10));
124 sb_.infallibleAppend(char('0' + (value % 10)));
125 }
126
127 void appendSixDigit(int32_t value) {
128 MOZ_ASSERT(0 <= value && value <= 999999);
129 MOZ_ASSERT(reserved_);
130
131 sb_.infallibleAppend(char('0' + (value / 100000)));
132 sb_.infallibleAppend(char('0' + (value % 100000) / 10000));
133 sb_.infallibleAppend(char('0' + (value % 10000) / 1000));
134 sb_.infallibleAppend(char('0' + (value % 1000) / 100));
135 sb_.infallibleAppend(char('0' + (value % 100) / 10));
136 sb_.infallibleAppend(char('0' + (value % 10)));
137 }
138
139 void appendYear(int32_t year) {
140 if (0 <= year && year <= 9999) {
141 appendFourDigit(year);
142 } else {
143 append(year < 0 ? '-' : '+');
144 appendSixDigit(std::abs(year));
145 }
146 }
147
148 bool appendCalendarAnnnotation(std::string_view id, Critical critical) {
149 std::string_view start = bool(critical) ? "[!u-ca=" : "[u-ca=";
150 return sb_.append(start.data(), start.length()) &&
151 sb_.append(id.data(), id.length()) && sb_.append(']');
152 }
153
154 bool appendTimeZoneAnnnotation(const JSLinearString* id, Critical critical) {
155 std::string_view start = bool(critical) ? "[!" : "[";
156 return sb_.append(start.data(), start.length()) && sb_.append(id) &&
157 sb_.append(']');
158 }
159
160 auto* finishString() { return sb_.finishString(); }
161 };
162
163 /**
164 * FormatFractionalSeconds ( subSecondNanoseconds, precision )
165 */
166 static void FormatFractionalSeconds(TemporalStringBuilder& result,
167 int32_t subSecondNanoseconds,
168 Precision precision) {
169 MOZ_ASSERT(0 <= subSecondNanoseconds && subSecondNanoseconds < 1'000'000'000);
170 MOZ_ASSERT(precision != Precision::Minute());
171
172 // Steps 1-2.
173 if (precision == Precision::Auto()) {
174 // Step 1.a.
175 if (subSecondNanoseconds == 0) {
176 return;
177 }
178
179 // Step 3. (Reordered)
180 result.append('.');
181
182 // Steps 1.b-c.
183 int32_t k = 100'000'000;
184 do {
185 result.append(char('0' + (subSecondNanoseconds / k)));
186 subSecondNanoseconds %= k;
187 k /= 10;
188 } while (subSecondNanoseconds);
189 } else {
190 // Step 2.a.
191 uint8_t p = precision.value();
192 if (p == 0) {
193 return;
194 }
195
196 // Step 3. (Reordered)
197 result.append('.');
198
199 // Steps 2.b-c.
200 int32_t k = 100'000'000;
201 for (uint8_t i = 0; i < p; i++) {
202 result.append(char('0' + (subSecondNanoseconds / k)));
203 subSecondNanoseconds %= k;
204 k /= 10;
205 }
206 }
207 }
208
209 /**
210 * FormatTimeString ( hour, minute, second, subSecondNanoseconds, precision )
211 */
212 static void FormatTimeString(TemporalStringBuilder& result, const Time& time,
213 Precision precision) {
214 // Step 1.
215 result.appendTwoDigit(time.hour);
216
217 // Step 2.
218 result.append(':');
219 result.appendTwoDigit(time.minute);
220
221 // Steps 4-7.
222 if (precision != Precision::Minute()) {
223 result.append(':');
224 result.appendTwoDigit(time.second);
225
226 int32_t subSecondNanoseconds = time.millisecond * 1'000'000 +
227 time.microsecond * 1'000 + time.nanosecond;
228 FormatFractionalSeconds(result, subSecondNanoseconds, precision);
229 }
230 }
231
232 static void FormatDateString(TemporalStringBuilder& result,
233 const ISODate& date) {
234 result.appendYear(date.year);
235 result.append('-');
236 result.appendTwoDigit(date.month);
237 result.append('-');
238 result.appendTwoDigit(date.day);
239 }
240
241 static void FormatDateTimeString(TemporalStringBuilder& result,
242 const ISODateTime& dateTime,
243 Precision precision) {
244 FormatDateString(result, dateTime.date);
245 result.append('T');
246 FormatTimeString(result, dateTime.time, precision);
247 }
248
249 /**
250 * FormatOffsetTimeZoneIdentifier ( offsetMinutes [ , style ] )
251 */
252 static void FormatOffsetTimeZoneIdentifier(TemporalStringBuilder& result,
253 int32_t offsetMinutes) {
254 MOZ_ASSERT(std::abs(offsetMinutes) < UnitsPerDay(TemporalUnit::Minute),
255 "time zone offset mustn't exceed 24-hours");
256
257 // Step 1.
258 char sign = offsetMinutes >= 0 ? '+' : '-';
259
260 // Step 2.
261 int32_t absoluteMinutes = std::abs(offsetMinutes);
262
263 // Step 3.
264 int32_t hours = absoluteMinutes / 60;
265
266 // Step 4.
267 int32_t minutes = absoluteMinutes % 60;
268
269 // Steps 5-6. (Inlined FormatTimeString)
270 result.append(sign);
271 result.appendTwoDigit(hours);
272 result.append(':');
273 result.appendTwoDigit(minutes);
274 }
275
276 // Returns |RoundNumberToIncrement(offsetNanoseconds, 60 × 10^9, "halfExpand")|
277 // divided by |60 × 10^9|.
278 static int32_t RoundNanosecondsToMinutes(int64_t offsetNanoseconds) {
279 MOZ_ASSERT(std::abs(offsetNanoseconds) < ToNanoseconds(TemporalUnit::Day));
280
281 constexpr int64_t increment = ToNanoseconds(TemporalUnit::Minute);
282
283 int64_t quotient = offsetNanoseconds / increment;
284 int64_t remainder = offsetNanoseconds % increment;
285 if (std::abs(remainder * 2) >= increment) {
286 quotient += (offsetNanoseconds > 0 ? 1 : -1);
287 }
288 return int32_t(quotient);
289 }
290
291 /**
292 * FormatDateTimeUTCOffsetRounded ( offsetNanoseconds )
293 */
294 static void FormatDateTimeUTCOffsetRounded(TemporalStringBuilder& result,
295 int64_t offsetNanoseconds) {
296 MOZ_ASSERT(std::abs(offsetNanoseconds) < ToNanoseconds(TemporalUnit::Day));
297
298 // Steps 1-3.
299 int32_t offsetMinutes = RoundNanosecondsToMinutes(offsetNanoseconds);
300
301 // Step 4.
302 FormatOffsetTimeZoneIdentifier(result, offsetMinutes);
303 }
304
305 /**
306 * FormatCalendarAnnotation ( id, showCalendar )
307 */
308 static bool FormatCalendarAnnotation(TemporalStringBuilder& result,
309 const CalendarValue& calendar,
310 ShowCalendar showCalendar) {
311 switch (showCalendar) {
312 case ShowCalendar::Never:
313 return true;
314
315 case ShowCalendar::Auto: {
316 if (calendar.identifier() == CalendarId::ISO8601) {
317 return true;
318 }
319 [[fallthrough]];
320 }
321
322 case ShowCalendar::Always: {
323 auto id = CalendarIdentifier(calendar);
324 return result.appendCalendarAnnnotation(id, Critical::No);
325 }
326
327 case ShowCalendar::Critical: {
328 auto id = CalendarIdentifier(calendar);
329 return result.appendCalendarAnnnotation(id, Critical::Yes);
330 }
331 }
332 MOZ_CRASH("bad calendar option");
333 }
334
335 static bool FormatTimeZoneAnnotation(TemporalStringBuilder& result,
336 const TimeZoneValue& timeZone,
337 ShowTimeZoneName showTimeZone) {
338 switch (showTimeZone) {
339 case ShowTimeZoneName::Never:
340 return true;
341
342 case ShowTimeZoneName::Auto:
343 return result.appendTimeZoneAnnnotation(timeZone.identifier(),
344 Critical::No);
345
346 case ShowTimeZoneName::Critical:
347 return result.appendTimeZoneAnnnotation(timeZone.identifier(),
348 Critical::Yes);
349 }
350 MOZ_CRASH("bad time zone option");
351 }
352
353 /**
354 * TemporalInstantToString ( instant, timeZone, precision )
355 */
356 JSString* js::temporal::TemporalInstantToString(JSContext* cx,
357 const EpochNanoseconds& epochNs,
358 Handle<TimeZoneValue> timeZone,
359 Precision precision) {
360 TemporalStringBuilder result(cx, TemporalStringFormat::Instant);
361 if (!result.reserve()) {
362 return nullptr;
363 }
364
365 // Steps 1-2.
366 int64_t offsetNanoseconds = 0;
367 if (timeZone) {
368 if (!GetOffsetNanosecondsFor(cx, timeZone, epochNs, &offsetNanoseconds)) {
369 return nullptr;
370 }
371 MOZ_ASSERT(std::abs(offsetNanoseconds) < ToNanoseconds(TemporalUnit::Day));
372 }
373
374 // Step 3. (Not applicable in our implementation.)
375
376 // Step 4.
377 auto dateTime = GetISODateTimeFor(epochNs, offsetNanoseconds);
378
379 // Step 5. (Inlined ISODateTimeToString)
380 FormatDateTimeString(result, dateTime, precision);
381
382 // Steps 6-7.
383 Rooted<JSString*> timeZoneString(cx);
384 if (!timeZone) {
385 result.append('Z');
386 } else {
387 FormatDateTimeUTCOffsetRounded(result, offsetNanoseconds);
388 }
389
390 // Step 8.
391 return result.finishString();
392 }
393
394 /**
395 * TemporalDateToString ( temporalDate, showCalendar )
396 */
397 JSString* js::temporal::TemporalDateToString(
398 JSContext* cx, Handle<PlainDateObject*> temporalDate,
399 ShowCalendar showCalendar) {
400 auto date = temporalDate->date();
401
402 TemporalStringBuilder result(cx, TemporalStringFormat::Date);
403 if (!result.reserve()) {
404 return nullptr;
405 }
406
407 // Steps 1-3.
408 FormatDateString(result, date);
409
410 // Step 4.
411 if (!FormatCalendarAnnotation(result, temporalDate->calendar(),
412 showCalendar)) {
413 return nullptr;
414 }
415
416 // Step 5.
417 return result.finishString();
418 }
419
420 /**
421 * ISODateTimeToString ( isoDateTime, calendar, precision, showCalendar )
422 */
423 JSString* js::temporal::ISODateTimeToString(JSContext* cx,
424 const ISODateTime& isoDateTime,
425 Handle<CalendarValue> calendar,
426 Precision precision,
427 ShowCalendar showCalendar) {
428 MOZ_ASSERT(IsValidISODateTime(isoDateTime));
429
430 TemporalStringBuilder result(cx, TemporalStringFormat::DateTime);
431 if (!result.reserve()) {
432 return nullptr;
433 }
434
435 // Steps 1-5.
436 FormatDateTimeString(result, isoDateTime, precision);
437
438 // Step 6.
439 if (!FormatCalendarAnnotation(result, calendar, showCalendar)) {
440 return nullptr;
441 }
442
443 // Step 7.
444 return result.finishString();
445 }
446
447 /**
448 * TimeRecordToString ( time, precision )
449 */
450 JSString* js::temporal::TimeRecordToString(JSContext* cx, const Time& time,
451 Precision precision) {
452 TemporalStringBuilder result(cx, TemporalStringFormat::Time);
453 if (!result.reserve()) {
454 return nullptr;
455 }
456
457 // Steps 1-2.
458 FormatTimeString(result, time, precision);
459
460 return result.finishString();
461 }
462
463 /**
464 * TemporalMonthDayToString ( monthDay, showCalendar )
465 */
466 JSString* js::temporal::TemporalMonthDayToString(
467 JSContext* cx, Handle<PlainMonthDayObject*> monthDay,
468 ShowCalendar showCalendar) {
469 TemporalStringBuilder result(cx, TemporalStringFormat::MonthDay);
470 if (!result.reserve()) {
471 return nullptr;
472 }
473
474 // Steps 1-4.
475 auto date = monthDay->date();
476 if (showCalendar == ShowCalendar::Always ||
477 showCalendar == ShowCalendar::Critical ||
478 monthDay->calendar().identifier() != CalendarId::ISO8601) {
479 FormatDateString(result, date);
480 } else {
481 result.appendTwoDigit(date.month);
482 result.append('-');
483 result.appendTwoDigit(date.day);
484 }
485
486 // Steps 5-6.
487 if (!FormatCalendarAnnotation(result, monthDay->calendar(), showCalendar)) {
488 return nullptr;
489 }
490
491 // Step 7.
492 return result.finishString();
493 }
494
495 /**
496 * TemporalYearMonthToString ( yearMonth, showCalendar )
497 */
498 JSString* js::temporal::TemporalYearMonthToString(
499 JSContext* cx, Handle<PlainYearMonthObject*> yearMonth,
500 ShowCalendar showCalendar) {
501 TemporalStringBuilder result(cx, TemporalStringFormat::YearMonth);
502 if (!result.reserve()) {
503 return nullptr;
504 }
505
506 // Steps 1-4.
507 auto date = yearMonth->date();
508 if (showCalendar == ShowCalendar::Always ||
509 showCalendar == ShowCalendar::Critical ||
510 yearMonth->calendar().identifier() != CalendarId::ISO8601) {
511 FormatDateString(result, date);
512 } else {
513 result.appendYear(date.year);
514 result.append('-');
515 result.appendTwoDigit(date.month);
516 }
517
518 // Steps 5-6.
519 if (!FormatCalendarAnnotation(result, yearMonth->calendar(), showCalendar)) {
520 return nullptr;
521 }
522
523 // Step 7.
524 return result.finishString();
525 }
526
527 /**
528 * TemporalZonedDateTimeToString ( zonedDateTime, precision, showCalendar,
529 * showTimeZone, showOffset [ , increment, unit, roundingMode ] )
530 */
531 JSString* js::temporal::TemporalZonedDateTimeToString(
532 JSContext* cx, Handle<ZonedDateTime> zonedDateTime, Precision precision,
533 ShowCalendar showCalendar, ShowTimeZoneName showTimeZone,
534 ShowOffset showOffset, Increment increment, TemporalUnit unit,
535 TemporalRoundingMode roundingMode) {
536 TemporalStringBuilder result(cx, TemporalStringFormat::ZonedDateTime);
537 if (!result.reserve()) {
538 return nullptr;
539 }
540
541 // Steps 1-3. (Not applicable in our implementation.)
542
543 // Steps 4-5.
544 auto epochNs = RoundTemporalInstant(zonedDateTime.epochNanoseconds(),
545 increment, unit, roundingMode);
546
547 // Step 6.
548 auto timeZone = zonedDateTime.timeZone();
549
550 // Step 7.
551 int64_t offsetNanoseconds;
552 if (!GetOffsetNanosecondsFor(cx, timeZone, epochNs, &offsetNanoseconds)) {
553 return nullptr;
554 }
555 MOZ_ASSERT(std::abs(offsetNanoseconds) < ToNanoseconds(TemporalUnit::Day));
556
557 // Step 8.
558 auto isoDateTime = GetISODateTimeFor(epochNs, offsetNanoseconds);
559
560 // Step 9. (Inlined ISODateTimeToString)
561 FormatDateTimeString(result, isoDateTime, precision);
562
563 // Steps 10-11.
564 if (showOffset != ShowOffset::Never) {
565 FormatDateTimeUTCOffsetRounded(result, offsetNanoseconds);
566 }
567
568 // Steps 12-13.
569 if (!FormatTimeZoneAnnotation(result, timeZone, showTimeZone)) {
570 return nullptr;
571 }
572
573 // Step 14.
574 if (!FormatCalendarAnnotation(result, zonedDateTime.calendar(),
575 showCalendar)) {
576 return nullptr;
577 }
578
579 // Step 15.
580 return result.finishString();
581 }