Debian Codegraph @

js/src/jsnum.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 /*
8 * JS number type and wrapper class.
9 */
10
11 #include "jsnum.h"
12
13 #include "mozilla/Casting.h"
14 #include "mozilla/FloatingPoint.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/RangedPtr.h"
17 #include "mozilla/TextUtils.h"
18 #include "mozilla/Utf8.h"
19
20 #include <algorithm>
21 #include <charconv>
22 #include <iterator>
23 #include <limits>
24 #ifdef HAVE_LOCALECONV
25 # include <locale.h>
26 #endif
27 #include <math.h>
28 #include <string.h> // memmove
29 #include <string_view>
30
31 #include "jstypes.h"
32
33 #include "builtin/String.h"
34 #include "double-conversion/double-conversion.h"
35 #include "frontend/ParserAtom.h" // frontend::{ParserAtomsTable, TaggedParserAtomIndex}
36 #include "jit/InlinableNatives.h"
37 #include "js/CharacterEncoding.h"
38 #include "js/Conversions.h"
39 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
40 #include "js/GCAPI.h"
41 #if !JS_HAS_INTL_API
42 # include "js/LocaleSensitive.h"
43 #endif
44 #include "js/PropertyAndElement.h" // JS_DefineFunctions
45 #include "js/PropertySpec.h"
46 #include "util/DoubleToString.h"
47 #include "util/Memory.h"
48 #include "util/StringBuilder.h"
49 #include "vm/BigIntType.h"
50 #include "vm/GlobalObject.h"
51 #include "vm/JSAtomUtils.h" // Atomize, AtomizeString
52 #include "vm/JSContext.h"
53 #include "vm/JSObject.h"
54 #include "vm/StaticStrings.h"
55
56 #include "vm/Compartment-inl.h" // For js::UnwrapAndTypeCheckThis
57 #include "vm/GeckoProfiler-inl.h"
58 #include "vm/NativeObject-inl.h"
59 #include "vm/NumberObject-inl.h"
60 #include "vm/StringType-inl.h"
61
62 using namespace js;
63
64 using mozilla::Abs;
65 using mozilla::AsciiAlphanumericToNumber;
66 using mozilla::IsAsciiAlphanumeric;
67 using mozilla::IsAsciiDigit;
68 using mozilla::MaxNumberValue;
69 using mozilla::Maybe;
70 using mozilla::MinNumberValue;
71 using mozilla::NegativeInfinity;
72 using mozilla::NumberEqualsInt32;
73 using mozilla::PositiveInfinity;
74 using mozilla::RangedPtr;
75 using mozilla::Utf8AsUnsignedChars;
76 using mozilla::Utf8Unit;
77
78 using JS::AutoCheckCannotGC;
79 using JS::GenericNaN;
80 using JS::ToInt16;
81 using JS::ToInt32;
82 using JS::ToInt64;
83 using JS::ToInt8;
84 using JS::ToUint16;
85 using JS::ToUint32;
86 using JS::ToUint64;
87 using JS::ToUint8;
88
89 static bool EnsureDtoaState(JSContext* cx) {
90 if (!cx->dtoaState) {
91 cx->dtoaState = NewDtoaState();
92 if (!cx->dtoaState) {
93 return false;
94 }
95 }
96 return true;
97 }
98
99 template <typename CharT>
100 static inline void AssertWellPlacedNumericSeparator(const CharT* s,
101 const CharT* start,
102 const CharT* end) {
103 MOZ_ASSERT(start < end, "string is non-empty");
104 MOZ_ASSERT(s > start, "number can't start with a separator");
105 MOZ_ASSERT(s + 1 < end,
106 "final character in a numeric literal can't be a separator");
107 MOZ_ASSERT(*(s + 1) != '_',
108 "separator can't be followed by another separator");
109 MOZ_ASSERT(*(s - 1) != '_',
110 "separator can't be preceded by another separator");
111 }
112
113 namespace {
114
115 template <typename CharT>
116 class BinaryDigitReader {
117 const int base; /* Base of number; must be a power of 2 */
118 int digit; /* Current digit value in radix given by base */
119 int digitMask; /* Mask to extract the next bit from digit */
120 const CharT* cur; /* Pointer to the remaining digits */
121 const CharT* start; /* Pointer to the start of the string */
122 const CharT* end; /* Pointer to first non-digit */
123
124 public:
125 BinaryDigitReader(int base, const CharT* start, const CharT* end)
126 : base(base),
127 digit(0),
128 digitMask(0),
129 cur(start),
130 start(start),
131 end(end) {}
132
133 /* Return the next binary digit from the number, or -1 if done. */
134 int nextDigit() {
135 if (digitMask == 0) {
136 if (cur == end) {
137 return -1;
138 }
139
140 int c = *cur++;
141 if (c == '_') {
142 AssertWellPlacedNumericSeparator(cur - 1, start, end);
143 c = *cur++;
144 }
145
146 MOZ_ASSERT(IsAsciiAlphanumeric(c));
147 digit = AsciiAlphanumericToNumber(c);
148 digitMask = base >> 1;
149 }
150
151 int bit = (digit & digitMask) != 0;
152 digitMask >>= 1;
153 return bit;
154 }
155 };
156
157 } /* anonymous namespace */
158
159 /*
160 * The fast result might also have been inaccurate for power-of-two bases. This
161 * happens if the addition in value * 2 + digit causes a round-down to an even
162 * least significant mantissa bit when the first dropped bit is a one. If any
163 * of the following digits in the number (which haven't been added in yet) are
164 * nonzero, then the correct action would have been to round up instead of
165 * down. An example occurs when reading the number 0x1000000000000081, which
166 * rounds to 0x1000000000000000 instead of 0x1000000000000100.
167 */
168 template <typename CharT>
169 static double ComputeAccurateBinaryBaseInteger(const CharT* start,
170 const CharT* end, int base) {
171 BinaryDigitReader<CharT> bdr(base, start, end);
172
173 /* Skip leading zeroes. */
174 int bit;
175 do {
176 bit = bdr.nextDigit();
177 } while (bit == 0);
178
179 MOZ_ASSERT(bit == 1); // guaranteed by Get{Prefix,Decimal}Integer
180
181 /* Gather the 53 significant bits (including the leading 1). */
182 double value = 1.0;
183 for (int j = 52; j > 0; j--) {
184 bit = bdr.nextDigit();
185 if (bit < 0) {
186 return value;
187 }
188 value = value * 2 + bit;
189 }
190
191 /* bit2 is the 54th bit (the first dropped from the mantissa). */
192 int bit2 = bdr.nextDigit();
193 if (bit2 >= 0) {
194 double factor = 2.0;
195 int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
196 int bit3;
197
198 while ((bit3 = bdr.nextDigit()) >= 0) {
199 sticky |= bit3;
200 factor *= 2;
201 }
202 value += bit2 & (bit | sticky);
203 value *= factor;
204 }
205
206 return value;
207 }
208
209 template <typename CharT>
210 double js::ParseDecimalNumber(const mozilla::Range<const CharT> chars) {
211 MOZ_ASSERT(chars.length() > 0);
212 uint64_t dec = 0;
213 RangedPtr<const CharT> s = chars.begin(), end = chars.end();
214 do {
215 CharT c = *s;
216 MOZ_ASSERT('0' <= c && c <= '9');
217 uint8_t digit = c - '0';
218 uint64_t next = dec * 10 + digit;
219 MOZ_ASSERT(next < DOUBLE_INTEGRAL_PRECISION_LIMIT,
220 "next value won't be an integrally-precise double");
221 dec = next;
222 } while (++s < end);
223 return static_cast<double>(dec);
224 }
225
226 template double js::ParseDecimalNumber(
227 const mozilla::Range<const Latin1Char> chars);
228
229 template double js::ParseDecimalNumber(
230 const mozilla::Range<const char16_t> chars);
231
232 template <typename CharT>
233 static bool GetPrefixIntegerImpl(const CharT* start, const CharT* end, int base,
234 IntegerSeparatorHandling separatorHandling,
235 const CharT** endp, double* dp) {
236 MOZ_ASSERT(start <= end);
237 MOZ_ASSERT(2 <= base && base <= 36);
238
239 const CharT* s = start;
240 double d = 0.0;
241 for (; s < end; s++) {
242 CharT c = *s;
243 if (!IsAsciiAlphanumeric(c)) {
244 if (c == '_' &&
245 separatorHandling == IntegerSeparatorHandling::SkipUnderscore) {
246 AssertWellPlacedNumericSeparator(s, start, end);
247 continue;
248 }
249 break;
250 }
251
252 uint8_t digit = AsciiAlphanumericToNumber(c);
253 if (digit >= base) {
254 break;
255 }
256
257 d = d * base + digit;
258 }
259
260 *endp = s;
261 *dp = d;
262
263 /* If we haven't reached the limit of integer precision, we're done. */
264 if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT) {
265 return true;
266 }
267
268 /*
269 * Otherwise compute the correct integer from the prefix of valid digits
270 * if we're computing for base ten or a power of two. Don't worry about
271 * other bases; see ES2018, 18.2.5 `parseInt(string, radix)`, step 13.
272 */
273 if (base == 10) {
274 return false;
275 }
276
277 if ((base & (base - 1)) == 0) {
278 *dp = ComputeAccurateBinaryBaseInteger(start, s, base);
279 }
280
281 return true;
282 }
283
284 template <typename CharT>
285 bool js::GetPrefixInteger(const CharT* start, const CharT* end, int base,
286 IntegerSeparatorHandling separatorHandling,
287 const CharT** endp, double* dp) {
288 if (GetPrefixIntegerImpl(start, end, base, separatorHandling, endp, dp)) {
289 return true;
290 }
291
292 // Can only fail for base 10.
293 MOZ_ASSERT(base == 10);
294
295 // If we're accumulating a decimal number and the number is >= 2^53, then the
296 // fast result from the loop in GetPrefixIntegerImpl may be inaccurate. Call
297 // GetDecimal to get the correct answer.
298 return GetDecimal(start, *endp, dp);
299 }
300
301 namespace js {
302
303 template bool GetPrefixInteger(const char16_t* start, const char16_t* end,
304 int base,
305 IntegerSeparatorHandling separatorHandling,
306 const char16_t** endp, double* dp);
307
308 template bool GetPrefixInteger(const Latin1Char* start, const Latin1Char* end,
309 int base,
310 IntegerSeparatorHandling separatorHandling,
311 const Latin1Char** endp, double* dp);
312
313 } // namespace js
314
315 template <typename CharT>
316 bool js::GetDecimalInteger(const CharT* start, const CharT* end, double* dp) {
317 MOZ_ASSERT(start <= end);
318
319 double d = 0.0;
320 for (const CharT* s = start; s < end; s++) {
321 CharT c = *s;
322 if (c == '_') {
323 AssertWellPlacedNumericSeparator(s, start, end);
324 continue;
325 }
326 MOZ_ASSERT(IsAsciiDigit(c));
327 int digit = c - '0';
328 d = d * 10 + digit;
329 }
330
331 // If we haven't reached the limit of integer precision, we're done.
332 if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT) {
333 *dp = d;
334 return true;
335 }
336
337 // Otherwise compute the correct integer using GetDecimal.
338 return GetDecimal(start, end, dp);
339 }
340
341 namespace js {
342
343 template bool GetDecimalInteger(const char16_t* start, const char16_t* end,
344 double* dp);
345
346 template bool GetDecimalInteger(const Latin1Char* start, const Latin1Char* end,
347 double* dp);
348
349 template <>
350 bool GetDecimalInteger<Utf8Unit>(const Utf8Unit* start, const Utf8Unit* end,
351 double* dp) {
352 return GetDecimalInteger(Utf8AsUnsignedChars(start), Utf8AsUnsignedChars(end),
353 dp);
354 }
355
356 } // namespace js
357
358 template <typename CharT>
359 bool js::GetDecimal(const CharT* start, const CharT* end, double* dp) {
360 MOZ_ASSERT(start <= end);
361
362 size_t length = end - start;
363
364 auto convert = [](auto* chars, size_t length) -> double {
365 using SToDConverter = double_conversion::StringToDoubleConverter;
366 SToDConverter converter(/* flags = */ 0, /* empty_string_value = */ 0.0,
367 /* junk_string_value = */ 0.0,
368 /* infinity_symbol = */ nullptr,
369 /* nan_symbol = */ nullptr);
370 int lengthInt = mozilla::AssertedCast<int>(length);
371 int processed = 0;
372 double d = converter.StringToDouble(chars, lengthInt, &processed);
373 MOZ_ASSERT(processed >= 0);
374 MOZ_ASSERT(size_t(processed) == length);
375 return d;
376 };
377
378 // If there are no underscores, we don't need to copy the chars.
379 bool hasUnderscore = std::any_of(start, end, [](auto c) { return c == '_'; });
380 if (!hasUnderscore) {
381 if constexpr (std::is_same_v<CharT, char16_t>) {
382 *dp = convert(reinterpret_cast<const uc16*>(start), length);
383 } else {
384 static_assert(std::is_same_v<CharT, Latin1Char>);
385 *dp = convert(reinterpret_cast<const char*>(start), length);
386 }
387 return true;
388 }
389
390 Vector<char, 32, SystemAllocPolicy> chars;
391 if (!chars.growByUninitialized(length)) {
392 return false;
393 }
394
395 const CharT* s = start;
396 size_t i = 0;
397 for (; s < end; s++) {
398 CharT c = *s;
399 if (c == '_') {
400 AssertWellPlacedNumericSeparator(s, start, end);
401 continue;
402 }
403 MOZ_ASSERT(IsAsciiDigit(c) || c == '.' || c == 'e' || c == 'E' ||
404 c == '+' || c == '-');
405 chars[i++] = char(c);
406 }
407
408 *dp = convert(chars.begin(), i);
409 return true;
410 }
411
412 namespace js {
413
414 template bool GetDecimal(const char16_t* start, const char16_t* end,
415 double* dp);
416
417 template bool GetDecimal(const Latin1Char* start, const Latin1Char* end,
418 double* dp);
419
420 template <>
421 bool GetDecimal<Utf8Unit>(const Utf8Unit* start, const Utf8Unit* end,
422 double* dp) {
423 return GetDecimal(Utf8AsUnsignedChars(start), Utf8AsUnsignedChars(end), dp);
424 }
425
426 } // namespace js
427
428 static bool num_parseFloat(JSContext* cx, unsigned argc, Value* vp) {
429 CallArgs args = CallArgsFromVp(argc, vp);
430
431 if (args.length() == 0) {
432 args.rval().setNaN();
433 return true;
434 }
435
436 if (args[0].isNumber()) {
437 // ToString(-0) is "0", handle it accordingly.
438 if (args[0].isDouble() && args[0].toDouble() == 0.0) {
439 args.rval().setInt32(0);
440 } else {
441 args.rval().set(args[0]);
442 }
443 return true;
444 }
445
446 JSString* str = ToString<CanGC>(cx, args[0]);
447 if (!str) {
448 return false;
449 }
450
451 if (str->hasIndexValue()) {
452 args.rval().setNumber(str->getIndexValue());
453 return true;
454 }
455
456 JSLinearString* linear = str->ensureLinear(cx);
457 if (!linear) {
458 return false;
459 }
460
461 double d;
462 AutoCheckCannotGC nogc;
463 if (linear->hasLatin1Chars()) {
464 const Latin1Char* begin = linear->latin1Chars(nogc);
465 const Latin1Char* end;
466 d = js_strtod(begin, begin + linear->length(), &end);
467 if (end == begin) {
468 d = GenericNaN();
469 }
470 } else {
471 const char16_t* begin = linear->twoByteChars(nogc);
472 const char16_t* end;
473 d = js_strtod(begin, begin + linear->length(), &end);
474 if (end == begin) {
475 d = GenericNaN();
476 }
477 }
478
479 args.rval().setDouble(d);
480 return true;
481 }
482
483 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
484 // 19.2.5 parseInt ( string, radix )
485 template <typename CharT>
486 static bool ParseIntImpl(JSContext* cx, const CharT* chars, size_t length,
487 bool stripPrefix, int32_t radix, double* res) {
488 // Step 2.
489 const CharT* end = chars + length;
490 const CharT* s = SkipSpace(chars, end);
491
492 MOZ_ASSERT(chars <= s);
493 MOZ_ASSERT(s <= end);
494
495 // Steps 3-4.
496 bool negative = (s != end && s[0] == '-');
497
498 // Step 5. */
499 if (s != end && (s[0] == '-' || s[0] == '+')) {
500 s++;
501 }
502
503 // Step 10.
504 if (stripPrefix) {
505 if (end - s >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
506 s += 2;
507 radix = 16;
508 }
509 }
510
511 // Steps 11-15.
512 const CharT* actualEnd;
513 double d;
514 if (!js::GetPrefixInteger(s, end, radix, IntegerSeparatorHandling::None,
515 &actualEnd, &d)) {
516 ReportOutOfMemory(cx);
517 return false;
518 }
519
520 if (s == actualEnd) {
521 *res = GenericNaN();
522 } else {
523 *res = negative ? -d : d;
524 }
525 return true;
526 }
527
528 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
529 // 19.2.5 parseInt ( string, radix )
530 bool js::NumberParseInt(JSContext* cx, HandleString str, int32_t radix,
531 MutableHandleValue result) {
532 // Step 7.
533 bool stripPrefix = true;
534
535 // Steps 8-9.
536 if (radix != 0) {
537 if (radix < 2 || radix > 36) {
538 result.setNaN();
539 return true;
540 }
541
542 if (radix != 16) {
543 stripPrefix = false;
544 }
545 } else {
546 radix = 10;
547 }
548 MOZ_ASSERT(2 <= radix && radix <= 36);
549
550 JSLinearString* linear = str->ensureLinear(cx);
551 if (!linear) {
552 return false;
553 }
554
555 // Steps 2-5, 10-16.
556 AutoCheckCannotGC nogc;
557 size_t length = linear->length();
558 double number;
559 if (linear->hasLatin1Chars()) {
560 if (!ParseIntImpl(cx, linear->latin1Chars(nogc), length, stripPrefix, radix,
561 &number)) {
562 return false;
563 }
564 } else {
565 if (!ParseIntImpl(cx, linear->twoByteChars(nogc), length, stripPrefix,
566 radix, &number)) {
567 return false;
568 }
569 }
570
571 result.setNumber(number);
572 return true;
573 }
574
575 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
576 // 19.2.5 parseInt ( string, radix )
577 static bool num_parseInt(JSContext* cx, unsigned argc, Value* vp) {
578 CallArgs args = CallArgsFromVp(argc, vp);
579
580 /* Fast paths and exceptional cases. */
581 if (args.length() == 0) {
582 args.rval().setNaN();
583 return true;
584 }
585
586 if (args.length() == 1 || (args[1].isInt32() && (args[1].toInt32() == 0 ||
587 args[1].toInt32() == 10))) {
588 if (args[0].isInt32()) {
589 args.rval().set(args[0]);
590 return true;
591 }
592
593 /*
594 * Step 1 is |inputString = ToString(string)|. When string >=
595 * 1e21, ToString(string) is in the form "NeM". 'e' marks the end of
596 * the word, which would mean the result of parseInt(string) should be |N|.
597 *
598 * To preserve this behaviour, we can't use the fast-path when string >=
599 * 1e21, or else the result would be |NeM|.
600 *
601 * The same goes for values smaller than 1.0e-6, because the string would be
602 * in the form of "Ne-M".
603 */
604 if (args[0].isDouble()) {
605 double d = args[0].toDouble();
606 if (DOUBLE_DECIMAL_IN_SHORTEST_LOW <= d &&
607 d < DOUBLE_DECIMAL_IN_SHORTEST_HIGH) {
608 args.rval().setNumber(floor(d));
609 return true;
610 }
611 if (-DOUBLE_DECIMAL_IN_SHORTEST_HIGH < d &&
612 d <= -DOUBLE_DECIMAL_IN_SHORTEST_LOW) {
613 args.rval().setNumber(-floor(-d));
614 return true;
615 }
616 if (d == 0.0) {
617 args.rval().setInt32(0);
618 return true;
619 }
620 }
621
622 if (args[0].isString()) {
623 JSString* str = args[0].toString();
624 if (str->hasIndexValue()) {
625 args.rval().setNumber(str->getIndexValue());
626 return true;
627 }
628 }
629 }
630
631 // Step 1.
632 RootedString inputString(cx, ToString<CanGC>(cx, args[0]));
633 if (!inputString) {
634 return false;
635 }
636
637 // Step 6.
638 int32_t radix = 0;
639 if (args.hasDefined(1)) {
640 if (!ToInt32(cx, args[1], &radix)) {
641 return false;
642 }
643 }
644
645 // Steps 2-5, 7-16.
646 return NumberParseInt(cx, inputString, radix, args.rval());
647 }
648
649 static constexpr JSFunctionSpec number_functions[] = {
650 JS_SELF_HOSTED_FN("isNaN", "Global_isNaN", 1, JSPROP_RESOLVING),
651 JS_SELF_HOSTED_FN("isFinite", "Global_isFinite", 1, JSPROP_RESOLVING),
652 JS_FS_END,
653 };
654
655 const JSClass NumberObject::class_ = {
656 "Number",
657 JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number),
658 JS_NULL_CLASS_OPS,
659 &NumberObject::classSpec_,
660 };
661
662 static bool Number(JSContext* cx, unsigned argc, Value* vp) {
663 CallArgs args = CallArgsFromVp(argc, vp);
664
665 if (args.length() > 0) {
666 // BigInt proposal section 6.2, steps 2a-c.
667 if (!ToNumeric(cx, args[0])) {
668 return false;
669 }
670 if (args[0].isBigInt()) {
671 args[0].setNumber(BigInt::numberValue(args[0].toBigInt()));
672 }
673 MOZ_ASSERT(args[0].isNumber());
674 }
675
676 if (!args.isConstructing()) {
677 if (args.length() > 0) {
678 args.rval().set(args[0]);
679 } else {
680 args.rval().setInt32(0);
681 }
682 return true;
683 }
684
685 RootedObject proto(cx);
686 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Number, &proto)) {
687 return false;
688 }
689
690 double d = args.length() > 0 ? args[0].toNumber() : 0;
691 JSObject* obj = NumberObject::create(cx, d, proto);
692 if (!obj) {
693 return false;
694 }
695 args.rval().setObject(*obj);
696 return true;
697 }
698
699 // ES2020 draft rev e08b018785606bc6465a0456a79604b149007932
700 // 20.1.3 Properties of the Number Prototype Object, thisNumberValue.
701 MOZ_ALWAYS_INLINE
702 static bool ThisNumberValue(JSContext* cx, const CallArgs& args,
703 const char* methodName, double* number) {
704 HandleValue thisv = args.thisv();
705
706 // Step 1.
707 if (thisv.isNumber()) {
708 *number = thisv.toNumber();
709 return true;
710 }
711
712 // Steps 2-3.
713 auto* obj = UnwrapAndTypeCheckThis<NumberObject>(cx, args, methodName);
714 if (!obj) {
715 return false;
716 }
717
718 *number = obj->unbox();
719 return true;
720 }
721
722 // On-off helper function for the self-hosted Number_toLocaleString method.
723 // This only exists to produce an error message with the right method name.
724 bool js::ThisNumberValueForToLocaleString(JSContext* cx, unsigned argc,
725 Value* vp) {
726 CallArgs args = CallArgsFromVp(argc, vp);
727
728 double d;
729 if (!ThisNumberValue(cx, args, "toLocaleString", &d)) {
730 return false;
731 }
732
733 args.rval().setNumber(d);
734 return true;
735 }
736
737 static bool num_toSource(JSContext* cx, unsigned argc, Value* vp) {
738 CallArgs args = CallArgsFromVp(argc, vp);
739
740 double d;
741 if (!ThisNumberValue(cx, args, "toSource", &d)) {
742 return false;
743 }
744
745 JSStringBuilder sb(cx);
746 if (!sb.append("(new Number(") ||
747 !NumberValueToStringBuilder(NumberValue(d), sb) || !sb.append("))")) {
748 return false;
749 }
750
751 JSString* str = sb.finishString();
752 if (!str) {
753 return false;
754 }
755 args.rval().setString(str);
756 return true;
757 }
758
759 // Subtract one from DTOSTR_STANDARD_BUFFER_SIZE to exclude the null-character.
760 static_assert(
761 double_conversion::DoubleToStringConverter::kMaxCharsEcmaScriptShortest ==
762 DTOSTR_STANDARD_BUFFER_SIZE - 1,
763 "double_conversion and dtoa both agree how large the longest string "
764 "can be");
765
766 static_assert(DTOSTR_STANDARD_BUFFER_SIZE <= JS::MaximumNumberToStringLength,
767 "MaximumNumberToStringLength is large enough to hold the longest "
768 "string produced by a conversion");
769
770 MOZ_ALWAYS_INLINE
771 static JSLinearString* LookupInt32ToString(JSContext* cx, int32_t si) {
772 if (StaticStrings::hasInt(si)) {
773 return cx->staticStrings().getInt(si);
774 }
775 return cx->realm()->dtoaCache.lookup(10, si);
776 }
777
778 template <AllowGC allowGC>
779 JSLinearString* js::Int32ToString(JSContext* cx, int32_t si) {
780 return js::Int32ToStringWithHeap<allowGC>(cx, si, gc::Heap::Default);
781 }
782 template JSLinearString* js::Int32ToString<CanGC>(JSContext* cx, int32_t si);
783 template JSLinearString* js::Int32ToString<NoGC>(JSContext* cx, int32_t si);
784
785 template <AllowGC allowGC>
786 JSLinearString* js::Int32ToStringWithHeap(JSContext* cx, int32_t si,
787 gc::Heap heap) {
788 if (JSLinearString* str = LookupInt32ToString(cx, si)) {
789 return str;
790 }
791
792 char buffer[JSFatInlineString::MAX_LENGTH_LATIN1];
793
794 auto result = std::to_chars(buffer, std::end(buffer), si, 10);
795 MOZ_ASSERT(result.ec == std::errc());
796
797 size_t length = result.ptr - buffer;
798 const auto& latin1Chars =
799 reinterpret_cast<const JS::Latin1Char(&)[std::size(buffer)]>(buffer);
800 JSInlineString* str = NewInlineString<allowGC>(cx, latin1Chars, length, heap);
801 if (!str) {
802 return nullptr;
803 }
804 if (si >= 0) {
805 str->maybeInitializeIndexValue(si);
806 }
807
808 cx->realm()->dtoaCache.cache(10, si, str);
809 return str;
810 }
811 template JSLinearString* js::Int32ToStringWithHeap<CanGC>(JSContext* cx,
812 int32_t si,
813 gc::Heap heap);
814 template JSLinearString* js::Int32ToStringWithHeap<NoGC>(JSContext* cx,
815 int32_t si,
816 gc::Heap heap);
817
818 JSLinearString* js::Int32ToStringPure(JSContext* cx, int32_t si) {
819 AutoUnsafeCallWithABI unsafe;
820 return Int32ToString<NoGC>(cx, si);
821 }
822
823 JSAtom* js::Int32ToAtom(JSContext* cx, int32_t si) {
824 if (JSLinearString* str = LookupInt32ToString(cx, si)) {
825 return js::AtomizeString(cx, str);
826 }
827
828 Int32ToCStringBuf cbuf;
829 auto result = std::to_chars(cbuf.sbuf, std::end(cbuf.sbuf), si, 10);
830 MOZ_ASSERT(result.ec == std::errc());
831
832 Maybe<uint32_t> indexValue;
833 if (si >= 0) {
834 indexValue.emplace(si);
835 }
836
837 size_t length = result.ptr - cbuf.sbuf;
838 JSAtom* atom = Atomize(cx, cbuf.sbuf, length, indexValue);
839 if (!atom) {
840 return nullptr;
841 }
842
843 cx->realm()->dtoaCache.cache(10, si, atom);
844 return atom;
845 }
846
847 frontend::TaggedParserAtomIndex js::Int32ToParserAtom(
848 FrontendContext* fc, frontend::ParserAtomsTable& parserAtoms, int32_t si) {
849 Int32ToCStringBuf cbuf;
850 auto result = std::to_chars(cbuf.sbuf, std::end(cbuf.sbuf), si, 10);
851 MOZ_ASSERT(result.ec == std::errc());
852
853 size_t length = result.ptr - cbuf.sbuf;
854 return parserAtoms.internAscii(fc, cbuf.sbuf, length);
855 }
856
857 /* Returns the number of digits written. */
858 template <typename T, size_t Base, size_t Length>
859 static size_t Int32ToCString(char (&out)[Length], T i) {
860 // The buffer needs to be large enough to hold the largest number, including
861 // the sign and the terminating null-character.
862 if constexpr (Base == 10) {
863 static_assert(std::numeric_limits<T>::digits10 + 1 + std::is_signed_v<T> <
864 Length);
865 } else {
866 // Compute digits16 analog to std::numeric_limits::digits10, which is
867 // defined as |std::numeric_limits::digits * std::log10(2)| for integer
868 // types.
869 // Note: log16(2) is 1/4.
870 static_assert(Base == 16);
871 static_assert(((std::numeric_limits<T>::digits + std::is_signed_v<T>) / 4 +
872 std::is_signed_v<T>) < Length);
873 }
874
875 // -1 to leave space for the terminating null-character.
876 auto result = std::to_chars(out, std::end(out) - 1, i, Base);
877 MOZ_ASSERT(result.ec == std::errc());
878
879 // Null-terminate the result.
880 *result.ptr = '\0';
881
882 return result.ptr - out;
883 }
884
885 /* Returns the number of digits written. */
886 template <typename T, size_t Base = 10>
887 static size_t Int32ToCString(ToCStringBuf* cbuf, T i) {
888 return Int32ToCString<T, Base>(cbuf->sbuf, i);
889 }
890
891 /* Returns the number of digits written. */
892 template <typename T, size_t Base = 10>
893 static size_t Int32ToCString(Int32ToCStringBuf* cbuf, T i) {
894 return Int32ToCString<T, Base>(cbuf->sbuf, i);
895 }
896
897 template <AllowGC allowGC>
898 static JSString* NumberToStringWithBase(JSContext* cx, double d, int32_t base);
899
900 static bool num_toString(JSContext* cx, unsigned argc, Value* vp) {
901 CallArgs args = CallArgsFromVp(argc, vp);
902
903 double d;
904 if (!ThisNumberValue(cx, args, "toString", &d)) {
905 return false;
906 }
907
908 int32_t base = 10;
909 if (args.hasDefined(0)) {
910 double d2;
911 if (!ToInteger(cx, args[0], &d2)) {
912 return false;
913 }
914
915 if (d2 < 2 || d2 > 36) {
916 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_RADIX);
917 return false;
918 }
919
920 base = int32_t(d2);
921 }
922 JSString* str = NumberToStringWithBase<CanGC>(cx, d, base);
923 if (!str) {
924 return false;
925 }
926 args.rval().setString(str);
927 return true;
928 }
929
930 #if !JS_HAS_INTL_API
931 static bool num_toLocaleString(JSContext* cx, unsigned argc, Value* vp) {
932 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype",
933 "toLocaleString");
934 CallArgs args = CallArgsFromVp(argc, vp);
935
936 double d;
937 if (!ThisNumberValue(cx, args, "toLocaleString", &d)) {
938 return false;
939 }
940
941 RootedString str(cx, NumberToStringWithBase<CanGC>(cx, d, 10));
942 if (!str) {
943 return false;
944 }
945
946 /*
947 * Create the string, move back to bytes to make string twiddling
948 * a bit easier and so we can insert platform charset seperators.
949 */
950 UniqueChars numBytes = EncodeAscii(cx, str);
951 if (!numBytes) {
952 return false;
953 }
954 const char* num = numBytes.get();
955 if (!num) {
956 return false;
957 }
958
959 /*
960 * Find the first non-integer value, whether it be a letter as in
961 * 'Infinity', a decimal point, or an 'e' from exponential notation.
962 */
963 const char* nint = num;
964 if (*nint == '-') {
965 nint++;
966 }
967 while (*nint >= '0' && *nint <= '9') {
968 nint++;
969 }
970 int digits = nint - num;
971 const char* end = num + digits;
972 if (!digits) {
973 args.rval().setString(str);
974 return true;
975 }
976
977 JSRuntime* rt = cx->runtime();
978 size_t thousandsLength = strlen(rt->thousandsSeparator);
979 size_t decimalLength = strlen(rt->decimalSeparator);
980
981 /* Figure out how long resulting string will be. */
982 int buflen = strlen(num);
983 if (*nint == '.') {
984 buflen += decimalLength - 1; /* -1 to account for existing '.' */
985 }
986
987 const char* numGrouping;
988 const char* tmpGroup;
989 numGrouping = tmpGroup = rt->numGrouping;
990 int remainder = digits;
991 if (*num == '-') {
992 remainder--;
993 }
994
995 while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
996 if (*tmpGroup >= remainder) {
997 break;
998 }
999 buflen += thousandsLength;
1000 remainder -= *tmpGroup;
1001 tmpGroup++;
1002 }
1003
1004 int nrepeat;
1005 if (*tmpGroup == '\0' && *numGrouping != '\0') {
1006 nrepeat = (remainder - 1) / tmpGroup[-1];
1007 buflen += thousandsLength * nrepeat;
1008 remainder -= nrepeat * tmpGroup[-1];
1009 } else {
1010 nrepeat = 0;
1011 }
1012 tmpGroup--;
1013
1014 char* buf = cx->pod_malloc<char>(buflen + 1);
1015 if (!buf) {
1016 return false;
1017 }
1018
1019 char* tmpDest = buf;
1020 const char* tmpSrc = num;
1021
1022 while (*tmpSrc == '-' || remainder--) {
1023 MOZ_ASSERT(tmpDest - buf < buflen);
1024 *tmpDest++ = *tmpSrc++;
1025 }
1026 while (tmpSrc < end) {
1027 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(thousandsLength) <= buflen);
1028 strcpy(tmpDest, rt->thousandsSeparator);
1029 tmpDest += thousandsLength;
1030 MOZ_ASSERT(tmpDest - buf + *tmpGroup <= buflen);
1031 js_memcpy(tmpDest, tmpSrc, *tmpGroup);
1032 tmpDest += *tmpGroup;
1033 tmpSrc += *tmpGroup;
1034 if (--nrepeat < 0) {
1035 tmpGroup--;
1036 }
1037 }
1038
1039 if (*nint == '.') {
1040 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(decimalLength) <= buflen);
1041 strcpy(tmpDest, rt->decimalSeparator);
1042 tmpDest += decimalLength;
1043 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint + 1)) <= buflen);
1044 strcpy(tmpDest, nint + 1);
1045 } else {
1046 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint)) <= buflen);
1047 strcpy(tmpDest, nint);
1048 }
1049
1050 if (cx->runtime()->localeCallbacks &&
1051 cx->runtime()->localeCallbacks->localeToUnicode) {
1052 Rooted<Value> v(cx, StringValue(str));
1053 bool ok = !!cx->runtime()->localeCallbacks->localeToUnicode(cx, buf, &v);
1054 if (ok) {
1055 args.rval().set(v);
1056 }
1057 js_free(buf);
1058 return ok;
1059 }
1060
1061 str = NewStringCopyN<CanGC>(cx, buf, buflen);
1062 js_free(buf);
1063 if (!str) {
1064 return false;
1065 }
1066
1067 args.rval().setString(str);
1068 return true;
1069 }
1070 #endif /* !JS_HAS_INTL_API */
1071
1072 bool js::num_valueOf(JSContext* cx, unsigned argc, Value* vp) {
1073 CallArgs args = CallArgsFromVp(argc, vp);
1074
1075 double d;
1076 if (!ThisNumberValue(cx, args, "valueOf", &d)) {
1077 return false;
1078 }
1079
1080 args.rval().setNumber(d);
1081 return true;
1082 }
1083
1084 static const unsigned MAX_PRECISION = 100;
1085
1086 static bool ComputePrecisionInRange(JSContext* cx, int minPrecision,
1087 int maxPrecision, double prec,
1088 int* precision) {
1089 if (minPrecision <= prec && prec <= maxPrecision) {
1090 *precision = int(prec);
1091 return true;
1092 }
1093
1094 ToCStringBuf cbuf;
1095 char* numStr = NumberToCString(&cbuf, prec);
1096 MOZ_ASSERT(numStr);
1097 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_PRECISION_RANGE,
1098 numStr);
1099 return false;
1100 }
1101
1102 static constexpr size_t DoubleToStrResultBufSize = 128;
1103
1104 template <typename Op>
1105 [[nodiscard]] static bool DoubleToStrResult(JSContext* cx, const CallArgs& args,
1106 Op op) {
1107 char buf[DoubleToStrResultBufSize];
1108
1109 const auto& converter =
1110 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1111 double_conversion::StringBuilder builder(buf, sizeof(buf));
1112
1113 bool ok = op(converter, builder);
1114 MOZ_RELEASE_ASSERT(ok);
1115
1116 size_t numStrLen = builder.position();
1117 const char* numStr = builder.Finalize();
1118 MOZ_ASSERT(numStr == buf);
1119 MOZ_ASSERT(numStrLen == strlen(numStr));
1120
1121 JSString* str = NewStringCopyN<CanGC>(cx, numStr, numStrLen);
1122 if (!str) {
1123 return false;
1124 }
1125
1126 args.rval().setString(str);
1127 return true;
1128 }
1129
1130 // ES 2021 draft 21.1.3.3.
1131 static bool num_toFixed(JSContext* cx, unsigned argc, Value* vp) {
1132 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype", "toFixed");
1133 CallArgs args = CallArgsFromVp(argc, vp);
1134
1135 // Step 1.
1136 double d;
1137 if (!ThisNumberValue(cx, args, "toFixed", &d)) {
1138 return false;
1139 }
1140
1141 // Steps 2-5.
1142 int precision;
1143 if (args.length() == 0) {
1144 precision = 0;
1145 } else {
1146 double prec = 0;
1147 if (!ToInteger(cx, args[0], &prec)) {
1148 return false;
1149 }
1150
1151 if (!ComputePrecisionInRange(cx, 0, MAX_PRECISION, prec, &precision)) {
1152 return false;
1153 }
1154 }
1155
1156 // Step 6.
1157 if (std::isnan(d)) {
1158 args.rval().setString(cx->names().NaN);
1159 return true;
1160 }
1161 if (std::isinf(d)) {
1162 if (d > 0) {
1163 args.rval().setString(cx->names().Infinity);
1164 return true;
1165 }
1166
1167 args.rval().setString(cx->names().NegativeInfinity_);
1168 return true;
1169 }
1170
1171 // Steps 7-10 for very large numbers.
1172 if (d <= -1e21 || d >= 1e+21) {
1173 JSString* s = NumberToString<CanGC>(cx, d);
1174 if (!s) {
1175 return false;
1176 }
1177
1178 args.rval().setString(s);
1179 return true;
1180 }
1181
1182 // Steps 7-12.
1183
1184 // DoubleToStringConverter::ToFixed is documented as requiring a buffer size
1185 // of:
1186 //
1187 // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint + 1
1188 // (one additional character for the sign, one for the decimal point,
1189 // and one for the null terminator)
1190 //
1191 // We already ensured there are at most 21 digits before the point, and
1192 // MAX_PRECISION digits after the point.
1193 static_assert(1 + 21 + 1 + MAX_PRECISION + 1 <= DoubleToStrResultBufSize);
1194
1195 // The double-conversion library by default has a kMaxFixedDigitsAfterPoint of
1196 // 60. Assert our modified version supports at least MAX_PRECISION (100).
1197 using DToSConverter = double_conversion::DoubleToStringConverter;
1198 static_assert(DToSConverter::kMaxFixedDigitsAfterPoint >= MAX_PRECISION);
1199
1200 return DoubleToStrResult(cx, args, [&](auto& converter, auto& builder) {
1201 return converter.ToFixed(d, precision, &builder);
1202 });
1203 }
1204
1205 // ES 2021 draft 21.1.3.2.
1206 static bool num_toExponential(JSContext* cx, unsigned argc, Value* vp) {
1207 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype",
1208 "toExponential");
1209 CallArgs args = CallArgsFromVp(argc, vp);
1210
1211 // Step 1.
1212 double d;
1213 if (!ThisNumberValue(cx, args, "toExponential", &d)) {
1214 return false;
1215 }
1216
1217 // Step 2.
1218 double prec = 0;
1219 if (args.hasDefined(0)) {
1220 if (!ToInteger(cx, args[0], &prec)) {
1221 return false;
1222 }
1223 }
1224
1225 // Step 3.
1226 MOZ_ASSERT_IF(!args.hasDefined(0), prec == 0);
1227
1228 // Step 4.
1229 if (std::isnan(d)) {
1230 args.rval().setString(cx->names().NaN);
1231 return true;
1232 }
1233 if (std::isinf(d)) {
1234 if (d > 0) {
1235 args.rval().setString(cx->names().Infinity);
1236 return true;
1237 }
1238
1239 args.rval().setString(cx->names().NegativeInfinity_);
1240 return true;
1241 }
1242
1243 // Step 5.
1244 int precision = 0;
1245 if (!ComputePrecisionInRange(cx, 0, MAX_PRECISION, prec, &precision)) {
1246 return false;
1247 }
1248
1249 // Steps 6-15.
1250
1251 // DoubleToStringConverter::ToExponential is documented as adding at most 8
1252 // characters on top of the requested digits: "the sign, the digit before the
1253 // decimal point, the decimal point, the exponent character, the exponent's
1254 // sign, and at most 3 exponent digits". In addition, the buffer must be able
1255 // to hold the trailing '\0' character.
1256 static_assert(MAX_PRECISION + 8 + 1 <= DoubleToStrResultBufSize);
1257
1258 return DoubleToStrResult(cx, args, [&](auto& converter, auto& builder) {
1259 int requestedDigits = args.hasDefined(0) ? precision : -1;
1260 return converter.ToExponential(d, requestedDigits, &builder);
1261 });
1262 }
1263
1264 // ES 2021 draft 21.1.3.5.
1265 static bool num_toPrecision(JSContext* cx, unsigned argc, Value* vp) {
1266 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype", "toPrecision");
1267 CallArgs args = CallArgsFromVp(argc, vp);
1268
1269 // Step 1.
1270 double d;
1271 if (!ThisNumberValue(cx, args, "toPrecision", &d)) {
1272 return false;
1273 }
1274
1275 // Step 2.
1276 if (!args.hasDefined(0)) {
1277 JSString* str = NumberToStringWithBase<CanGC>(cx, d, 10);
1278 if (!str) {
1279 return false;
1280 }
1281 args.rval().setString(str);
1282 return true;
1283 }
1284
1285 // Step 3.
1286 double prec = 0;
1287 if (!ToInteger(cx, args[0], &prec)) {
1288 return false;
1289 }
1290
1291 // Step 4.
1292 if (std::isnan(d)) {
1293 args.rval().setString(cx->names().NaN);
1294 return true;
1295 }
1296 if (std::isinf(d)) {
1297 if (d > 0) {
1298 args.rval().setString(cx->names().Infinity);
1299 return true;
1300 }
1301
1302 args.rval().setString(cx->names().NegativeInfinity_);
1303 return true;
1304 }
1305
1306 // Step 5.
1307 int precision = 0;
1308 if (!ComputePrecisionInRange(cx, 1, MAX_PRECISION, prec, &precision)) {
1309 return false;
1310 }
1311
1312 // Steps 6-14.
1313
1314 // DoubleToStringConverter::ToPrecision is documented as adding at most 7
1315 // characters on top of the requested digits: "the sign, the decimal point,
1316 // the exponent character, the exponent's sign, and at most 3 exponent
1317 // digits". In addition, the buffer must be able to hold the trailing '\0'
1318 // character.
1319 static_assert(MAX_PRECISION + 7 + 1 <= DoubleToStrResultBufSize);
1320
1321 return DoubleToStrResult(cx, args, [&](auto& converter, auto& builder) {
1322 return converter.ToPrecision(d, precision, &builder);
1323 });
1324 }
1325
1326 static constexpr JSFunctionSpec number_methods[] = {
1327 JS_FN("toSource", num_toSource, 0, 0),
1328 JS_INLINABLE_FN("toString", num_toString, 1, 0, NumberToString),
1329 #if JS_HAS_INTL_API
1330 JS_SELF_HOSTED_FN("toLocaleString", "Number_toLocaleString", 0, 0),
1331 #else
1332 JS_FN("toLocaleString", num_toLocaleString, 0, 0),
1333 #endif
1334 JS_FN("valueOf", num_valueOf, 0, 0),
1335 JS_FN("toFixed", num_toFixed, 1, 0),
1336 JS_FN("toExponential", num_toExponential, 1, 0),
1337 JS_FN("toPrecision", num_toPrecision, 1, 0),
1338 JS_FS_END,
1339 };
1340
1341 bool js::IsInteger(double d) {
1342 return std::isfinite(d) && JS::ToInteger(d) == d;
1343 }
1344
1345 static constexpr JSFunctionSpec number_static_methods[] = {
1346 JS_SELF_HOSTED_FN("isFinite", "Number_isFinite", 1, 0),
1347 JS_SELF_HOSTED_FN("isInteger", "Number_isInteger", 1, 0),
1348 JS_SELF_HOSTED_FN("isNaN", "Number_isNaN", 1, 0),
1349 JS_SELF_HOSTED_FN("isSafeInteger", "Number_isSafeInteger", 1, 0),
1350 JS_FS_END,
1351 };
1352
1353 static constexpr JSPropertySpec number_static_properties[] = {
1354 JS_DOUBLE_PS("POSITIVE_INFINITY", mozilla::PositiveInfinity<double>(),
1355 JSPROP_READONLY | JSPROP_PERMANENT),
1356 JS_DOUBLE_PS("NEGATIVE_INFINITY", mozilla::NegativeInfinity<double>(),
1357 JSPROP_READONLY | JSPROP_PERMANENT),
1358 JS_DOUBLE_PS("MAX_VALUE", MaxNumberValue<double>(),
1359 JSPROP_READONLY | JSPROP_PERMANENT),
1360 JS_DOUBLE_PS("MIN_VALUE", MinNumberValue<double>(),
1361 JSPROP_READONLY | JSPROP_PERMANENT),
1362 /* ES6 (April 2014 draft) 20.1.2.6 */
1363 JS_DOUBLE_PS("MAX_SAFE_INTEGER", 9007199254740991,
1364 JSPROP_READONLY | JSPROP_PERMANENT),
1365 /* ES6 (April 2014 draft) 20.1.2.10 */
1366 JS_DOUBLE_PS("MIN_SAFE_INTEGER", -9007199254740991,
1367 JSPROP_READONLY | JSPROP_PERMANENT),
1368 /* ES6 (May 2013 draft) 15.7.3.7 */
1369 JS_DOUBLE_PS("EPSILON", 2.2204460492503130808472633361816e-16,
1370 JSPROP_READONLY | JSPROP_PERMANENT),
1371 JS_PS_END,
1372 };
1373
1374 bool js::InitRuntimeNumberState(JSRuntime* rt) {
1375 // XXX If JS_HAS_INTL_API becomes true all the time at some point,
1376 // js::InitRuntimeNumberState is no longer fallible, and we should
1377 // change its return type.
1378 #if !JS_HAS_INTL_API
1379 /* Copy locale-specific separators into the runtime strings. */
1380 const char* thousandsSeparator;
1381 const char* decimalPoint;
1382 const char* grouping;
1383 # ifdef HAVE_LOCALECONV
1384 struct lconv* locale = localeconv();
1385 thousandsSeparator = locale->thousands_sep;
1386 decimalPoint = locale->decimal_point;
1387 grouping = locale->grouping;
1388 # else
1389 thousandsSeparator = getenv("LOCALE_THOUSANDS_SEP");
1390 decimalPoint = getenv("LOCALE_DECIMAL_POINT");
1391 grouping = getenv("LOCALE_GROUPING");
1392 # endif
1393 if (!thousandsSeparator) {
1394 thousandsSeparator = "'";
1395 }
1396 if (!decimalPoint) {
1397 decimalPoint = ".";
1398 }
1399 if (!grouping) {
1400 grouping = "\3\0";
1401 }
1402
1403 /*
1404 * We use single malloc to get the memory for all separator and grouping
1405 * strings.
1406 */
1407 size_t thousandsSeparatorSize = strlen(thousandsSeparator) + 1;
1408 size_t decimalPointSize = strlen(decimalPoint) + 1;
1409 size_t groupingSize = strlen(grouping) + 1;
1410
1411 char* storage = js_pod_malloc<char>(thousandsSeparatorSize +
1412 decimalPointSize + groupingSize);
1413 if (!storage) {
1414 return false;
1415 }
1416
1417 js_memcpy(storage, thousandsSeparator, thousandsSeparatorSize);
1418 rt->thousandsSeparator = storage;
1419 storage += thousandsSeparatorSize;
1420
1421 js_memcpy(storage, decimalPoint, decimalPointSize);
1422 rt->decimalSeparator = storage;
1423 storage += decimalPointSize;
1424
1425 js_memcpy(storage, grouping, groupingSize);
1426 rt->numGrouping = grouping;
1427 #endif /* !JS_HAS_INTL_API */
1428 return true;
1429 }
1430
1431 void js::FinishRuntimeNumberState(JSRuntime* rt) {
1432 #if !JS_HAS_INTL_API
1433 /*
1434 * The free also releases the memory for decimalSeparator and numGrouping
1435 * strings.
1436 */
1437 char* storage = const_cast<char*>(rt->thousandsSeparator.ref());
1438 js_free(storage);
1439 #endif // !JS_HAS_INTL_API
1440 }
1441
1442 JSObject* NumberObject::createPrototype(JSContext* cx, JSProtoKey key) {
1443 NumberObject* numberProto =
1444 GlobalObject::createBlankPrototype<NumberObject>(cx, cx->global());
1445 if (!numberProto) {
1446 return nullptr;
1447 }
1448 numberProto->setPrimitiveValue(0);
1449 return numberProto;
1450 }
1451
1452 static bool NumberClassFinish(JSContext* cx, HandleObject ctor,
1453 HandleObject proto) {
1454 Handle<GlobalObject*> global = cx->global();
1455
1456 if (!JS_DefineFunctions(cx, global, number_functions)) {
1457 return false;
1458 }
1459
1460 // Number.parseInt should be the same function object as global parseInt.
1461 RootedId parseIntId(cx, NameToId(cx->names().parseInt));
1462 JSFunction* parseInt =
1463 DefineFunction(cx, global, parseIntId, num_parseInt, 2, JSPROP_RESOLVING);
1464 if (!parseInt) {
1465 return false;
1466 }
1467 parseInt->setJitInfo(&jit::JitInfo_NumberParseInt);
1468
1469 RootedValue parseIntValue(cx, ObjectValue(*parseInt));
1470 if (!DefineDataProperty(cx, ctor, parseIntId, parseIntValue, 0)) {
1471 return false;
1472 }
1473
1474 // Number.parseFloat should be the same function object as global
1475 // parseFloat.
1476 RootedId parseFloatId(cx, NameToId(cx->names().parseFloat));
1477 JSFunction* parseFloat = DefineFunction(cx, global, parseFloatId,
1478 num_parseFloat, 1, JSPROP_RESOLVING);
1479 if (!parseFloat) {
1480 return false;
1481 }
1482 RootedValue parseFloatValue(cx, ObjectValue(*parseFloat));
1483 if (!DefineDataProperty(cx, ctor, parseFloatId, parseFloatValue, 0)) {
1484 return false;
1485 }
1486
1487 RootedValue valueNaN(cx, JS::NaNValue());
1488 RootedValue valueInfinity(cx, JS::InfinityValue());
1489
1490 if (!DefineDataProperty(
1491 cx, ctor, cx->names().NaN, valueNaN,
1492 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING)) {
1493 return false;
1494 }
1495
1496 // ES5 15.1.1.1, 15.1.1.2
1497 if (!NativeDefineDataProperty(
1498 cx, global, cx->names().NaN, valueNaN,
1499 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING) ||
1500 !NativeDefineDataProperty(
1501 cx, global, cx->names().Infinity, valueInfinity,
1502 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING)) {
1503 return false;
1504 }
1505
1506 return true;
1507 }
1508
1509 const ClassSpec NumberObject::classSpec_ = {
1510 GenericCreateConstructor<Number, 1, gc::AllocKind::FUNCTION,
1511 &jit::JitInfo_Number>,
1512 NumberObject::createPrototype,
1513 number_static_methods,
1514 number_static_properties,
1515 number_methods,
1516 nullptr,
1517 NumberClassFinish,
1518 };
1519
1520 static size_t FracNumberToCString(ToCStringBuf* cbuf, double d) {
1521 #ifdef DEBUG
1522 {
1523 int32_t _;
1524 MOZ_ASSERT(!NumberEqualsInt32(d, &_));
1525 }
1526 #endif
1527
1528 /*
1529 * This is V8's implementation of the algorithm described in the
1530 * following paper:
1531 *
1532 * Printing floating-point numbers quickly and accurately with integers.
1533 * Florian Loitsch, PLDI 2010.
1534 */
1535 const double_conversion::DoubleToStringConverter& converter =
1536 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1537 double_conversion::StringBuilder builder(cbuf->sbuf, std::size(cbuf->sbuf));
1538 MOZ_ALWAYS_TRUE(converter.ToShortest(d, &builder));
1539
1540 size_t len = builder.position();
1541 #ifdef DEBUG
1542 char* result =
1543 #endif
1544 builder.Finalize();
1545 MOZ_ASSERT(cbuf->sbuf == result);
1546 return len;
1547 }
1548
1549 void JS::NumberToString(double d, char (&out)[MaximumNumberToStringLength]) {
1550 int32_t i;
1551 if (NumberEqualsInt32(d, &i)) {
1552 Int32ToCStringBuf cbuf;
1553 size_t len = ::Int32ToCString(&cbuf, i);
1554 memmove(out, cbuf.sbuf, len);
1555 out[len] = '\0';
1556 } else {
1557 const double_conversion::DoubleToStringConverter& converter =
1558 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1559
1560 double_conversion::StringBuilder builder(out, sizeof(out));
1561 MOZ_ALWAYS_TRUE(converter.ToShortest(d, &builder));
1562
1563 #ifdef DEBUG
1564 char* result =
1565 #endif
1566 builder.Finalize();
1567 MOZ_ASSERT(out == result);
1568 }
1569 }
1570
1571 char* js::NumberToCString(ToCStringBuf* cbuf, double d, size_t* length) {
1572 int32_t i;
1573 size_t len = NumberEqualsInt32(d, &i) ? ::Int32ToCString(cbuf, i)
1574 : FracNumberToCString(cbuf, d);
1575 if (length) {
1576 *length = len;
1577 }
1578 return cbuf->sbuf;
1579 }
1580
1581 char* js::Int32ToCString(Int32ToCStringBuf* cbuf, int32_t value,
1582 size_t* length) {
1583 size_t len = ::Int32ToCString(cbuf, value);
1584 if (length) {
1585 *length = len;
1586 }
1587 return cbuf->sbuf;
1588 }
1589
1590 char* js::Uint32ToCString(Int32ToCStringBuf* cbuf, uint32_t value,
1591 size_t* length) {
1592 size_t len = ::Int32ToCString(cbuf, value);
1593 if (length) {
1594 *length = len;
1595 }
1596 return cbuf->sbuf;
1597 }
1598
1599 char* js::Uint32ToHexCString(Int32ToCStringBuf* cbuf, uint32_t value,
1600 size_t* length) {
1601 size_t len = ::Int32ToCString<uint32_t, 16>(cbuf, value);
1602 if (length) {
1603 *length = len;
1604 }
1605 return cbuf->sbuf;
1606 }
1607
1608 template <AllowGC allowGC>
1609 static JSLinearString* Int32ToStringWithBase(JSContext* cx, int32_t i,
1610 int32_t base) {
1611 MOZ_ASSERT(2 <= base && base <= 36);
1612
1613 bool isBase10Int = (base == 10);
1614 if (isBase10Int) {
1615 static_assert(StaticStrings::INT_STATIC_LIMIT > 10 * 10);
1616 if (StaticStrings::hasInt(i)) {
1617 return cx->staticStrings().getInt(i);
1618 }
1619 } else if (unsigned(i) < unsigned(base)) {
1620 if (i < 10) {
1621 return cx->staticStrings().getInt(i);
1622 }
1623 char16_t c = 'a' + i - 10;
1624 MOZ_ASSERT(StaticStrings::hasUnit(c));
1625 return cx->staticStrings().getUnit(c);
1626 } else if (unsigned(i) < unsigned(base * base)) {
1627 static constexpr char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1628 char chars[] = {digits[i / base], digits[i % base]};
1629 JSLinearString* str = cx->staticStrings().lookup(chars, 2);
1630 MOZ_ASSERT(str);
1631 return str;
1632 }
1633
1634 auto& dtoaCache = cx->realm()->dtoaCache;
1635 double d = i;
1636 if (JSLinearString* str = dtoaCache.lookup(base, d)) {
1637 return str;
1638 }
1639
1640 // Plus two to include the largest number and the sign.
1641 constexpr size_t MaximumLength = std::numeric_limits<int32_t>::digits + 2;
1642
1643 char buf[MaximumLength] = {};
1644
1645 // Use explicit cases for base 10 and base 16 to make it more likely the
1646 // compiler will generate optimized code for these two common bases.
1647 std::to_chars_result result;
1648 switch (base) {
1649 case 10: {
1650 result = std::to_chars(buf, std::end(buf), i, 10);
1651 break;
1652 }
1653 case 16: {
1654 result = std::to_chars(buf, std::end(buf), i, 16);
1655 break;
1656 }
1657 default: {
1658 MOZ_ASSERT(base >= 2 && base <= 36);
1659 result = std::to_chars(buf, std::end(buf), i, base);
1660 break;
1661 }
1662 }
1663 MOZ_ASSERT(result.ec == std::errc());
1664
1665 size_t length = result.ptr - buf;
1666 MOZ_ASSERT(i < 0 || length > 2, "small static strings are handled above");
1667
1668 auto* latin1Chars = reinterpret_cast<JS::Latin1Char*>(buf);
1669 JSLinearString* s = NewStringCopyNDontDeflateNonStaticValidLength<allowGC>(
1670 cx, latin1Chars, length);
1671 if (!s) {
1672 return nullptr;
1673 }
1674
1675 if (isBase10Int && i >= 0) {
1676 s->maybeInitializeIndexValue(i);
1677 }
1678
1679 dtoaCache.cache(base, d, s);
1680 return s;
1681 }
1682
1683 template <AllowGC allowGC>
1684 static JSString* NumberToStringWithBase(JSContext* cx, double d, int32_t base) {
1685 MOZ_ASSERT(2 <= base && base <= 36);
1686
1687 int32_t i;
1688 if (NumberEqualsInt32(d, &i)) {
1689 return ::Int32ToStringWithBase<allowGC>(cx, i, base);
1690 }
1691
1692 auto& dtoaCache = cx->realm()->dtoaCache;
1693 if (JSLinearString* str = dtoaCache.lookup(base, d)) {
1694 return str;
1695 }
1696
1697 JSLinearString* s;
1698 if (base == 10) {
1699 // We use a faster algorithm for base 10.
1700 ToCStringBuf cbuf;
1701 size_t numStrLen = FracNumberToCString(&cbuf, d);
1702 MOZ_ASSERT(numStrLen == strlen(cbuf.sbuf));
1703
1704 s = NewStringCopyN<allowGC>(cx, cbuf.sbuf, numStrLen);
1705 if (!s) {
1706 return nullptr;
1707 }
1708 } else {
1709 if (!EnsureDtoaState(cx)) {
1710 if constexpr (allowGC) {
1711 ReportOutOfMemory(cx);
1712 }
1713 return nullptr;
1714 }
1715
1716 UniqueChars numStr(js_dtobasestr(cx->dtoaState, base, d));
1717 if (!numStr) {
1718 if constexpr (allowGC) {
1719 ReportOutOfMemory(cx);
1720 }
1721 return nullptr;
1722 }
1723
1724 s = NewStringCopyZ<allowGC>(cx, numStr.get());
1725 if (!s) {
1726 return nullptr;
1727 }
1728 }
1729
1730 dtoaCache.cache(base, d, s);
1731 return s;
1732 }
1733
1734 template <AllowGC allowGC>
1735 JSString* js::NumberToString(JSContext* cx, double d) {
1736 return NumberToStringWithBase<allowGC>(cx, d, 10);
1737 }
1738
1739 template JSString* js::NumberToString<CanGC>(JSContext* cx, double d);
1740
1741 template JSString* js::NumberToString<NoGC>(JSContext* cx, double d);
1742
1743 JSString* js::NumberToStringPure(JSContext* cx, double d) {
1744 AutoUnsafeCallWithABI unsafe;
1745 return NumberToString<NoGC>(cx, d);
1746 }
1747
1748 JSAtom* js::NumberToAtom(JSContext* cx, double d) {
1749 int32_t si;
1750 if (NumberEqualsInt32(d, &si)) {
1751 return Int32ToAtom(cx, si);
1752 }
1753
1754 auto& dtoaCache = cx->realm()->dtoaCache;
1755 if (JSLinearString* str = dtoaCache.lookup(10, d)) {
1756 return AtomizeString(cx, str);
1757 }
1758
1759 ToCStringBuf cbuf;
1760 size_t length = FracNumberToCString(&cbuf, d);
1761 MOZ_ASSERT(length == strlen(cbuf.sbuf));
1762
1763 JSAtom* atom = Atomize(cx, cbuf.sbuf, length);
1764 if (!atom) {
1765 return nullptr;
1766 }
1767
1768 dtoaCache.cache(10, d, atom);
1769 return atom;
1770 }
1771
1772 frontend::TaggedParserAtomIndex js::NumberToParserAtom(
1773 FrontendContext* fc, frontend::ParserAtomsTable& parserAtoms, double d) {
1774 int32_t si;
1775 if (NumberEqualsInt32(d, &si)) {
1776 return Int32ToParserAtom(fc, parserAtoms, si);
1777 }
1778
1779 ToCStringBuf cbuf;
1780 size_t length = FracNumberToCString(&cbuf, d);
1781 MOZ_ASSERT(length == strlen(cbuf.sbuf));
1782
1783 return parserAtoms.internAscii(fc, cbuf.sbuf, length);
1784 }
1785
1786 JSLinearString* js::IndexToString(JSContext* cx, uint32_t index) {
1787 if (StaticStrings::hasUint(index)) {
1788 return cx->staticStrings().getUint(index);
1789 }
1790
1791 char buffer[JSFatInlineString::MAX_LENGTH_LATIN1];
1792
1793 auto result = std::to_chars(buffer, std::end(buffer), index, 10);
1794 MOZ_ASSERT(result.ec == std::errc());
1795
1796 size_t length = result.ptr - buffer;
1797 const auto& latin1Chars =
1798 reinterpret_cast<const JS::Latin1Char(&)[std::size(buffer)]>(buffer);
1799 return NewInlineString<CanGC>(cx, latin1Chars, length);
1800 }
1801
1802 template <AllowGC allowGC>
1803 JSLinearString* js::Int32ToStringWithBase(JSContext* cx, int32_t i,
1804 int32_t base, bool lowerCase) {
1805 JSLinearString* str = ::Int32ToStringWithBase<allowGC>(cx, i, base);
1806 if (!str) {
1807 return nullptr;
1808 }
1809
1810 if constexpr (allowGC == NoGC) {
1811 MOZ_ASSERT(lowerCase, "upper case conversion not allowed for NoGC");
1812 return str;
1813 } else {
1814 if (lowerCase) {
1815 return str;
1816 }
1817 return StringToUpperCase(cx, str);
1818 }
1819 }
1820 template JSLinearString* js::Int32ToStringWithBase<CanGC>(JSContext* cx,
1821 int32_t i,
1822 int32_t base,
1823 bool lowerCase);
1824 template JSLinearString* js::Int32ToStringWithBase<NoGC>(JSContext* cx,
1825 int32_t i,
1826 int32_t base,
1827 bool lowerCase);
1828
1829 bool js::NumberValueToStringBuilder(const Value& v, StringBuilder& sb) {
1830 /* Convert to C-string. */
1831 ToCStringBuf cbuf;
1832 const char* cstr;
1833 size_t cstrlen;
1834 if (v.isInt32()) {
1835 cstrlen = ::Int32ToCString(&cbuf, v.toInt32());
1836 cstr = cbuf.sbuf;
1837 } else {
1838 cstr = NumberToCString(&cbuf, v.toDouble(), &cstrlen);
1839 }
1840 MOZ_ASSERT(cstr);
1841 MOZ_ASSERT(cstrlen == strlen(cstr));
1842
1843 MOZ_ASSERT(cstrlen < std::size(cbuf.sbuf));
1844 return sb.append(cstr, cstrlen);
1845 }
1846
1847 template <typename CharT>
1848 inline double CharToNumber(CharT c) {
1849 if ('0' <= c && c <= '9') {
1850 return c - '0';
1851 }
1852 if (unicode::IsSpace(c)) {
1853 return 0.0;
1854 }
1855 return GenericNaN();
1856 }
1857
1858 template <typename CharT>
1859 inline bool CharsToNonDecimalNumber(const CharT* start, const CharT* end,
1860 double* result) {
1861 MOZ_ASSERT(end - start >= 2);
1862 MOZ_ASSERT(start[0] == '0');
1863
1864 int radix = 0;
1865 if (start[1] == 'b' || start[1] == 'B') {
1866 radix = 2;
1867 } else if (start[1] == 'o' || start[1] == 'O') {
1868 radix = 8;
1869 } else if (start[1] == 'x' || start[1] == 'X') {
1870 radix = 16;
1871 } else {
1872 return false;
1873 }
1874
1875 // It's probably a non-decimal number. Accept if there's at least one digit
1876 // after the 0b|0o|0x, and if no non-whitespace characters follow all the
1877 // digits.
1878 const CharT* endptr;
1879 double d;
1880 MOZ_ALWAYS_TRUE(GetPrefixIntegerImpl(
1881 start + 2, end, radix, IntegerSeparatorHandling::None, &endptr, &d));
1882 if (endptr == start + 2 || SkipSpace(endptr, end) != end) {
1883 *result = GenericNaN();
1884 } else {
1885 *result = d;
1886 }
1887 return true;
1888 }
1889
1890 template <typename CharT>
1891 double js::CharsToNumber(const CharT* chars, size_t length) {
1892 if (length == 1) {
1893 return CharToNumber(chars[0]);
1894 }
1895
1896 const CharT* end = chars + length;
1897 const CharT* start = SkipSpace(chars, end);
1898
1899 // ECMA doesn't allow signed non-decimal numbers (bug 273467).
1900 if (end - start >= 2 && start[0] == '0') {
1901 double d;
1902 if (CharsToNonDecimalNumber(start, end, &d)) {
1903 return d;
1904 }
1905 }
1906
1907 /*
1908 * Note that ECMA doesn't treat a string beginning with a '0' as
1909 * an octal number here. This works because all such numbers will
1910 * be interpreted as decimal by js_strtod. Also, any hex numbers
1911 * that have made it here (which can only be negative ones) will
1912 * be treated as 0 without consuming the 'x' by js_strtod.
1913 */
1914 const CharT* ep;
1915 double d = js_strtod(start, end, &ep);
1916 if (SkipSpace(ep, end) != end) {
1917 return GenericNaN();
1918 }
1919 return d;
1920 }
1921
1922 template double js::CharsToNumber(const Latin1Char* chars, size_t length);
1923
1924 template double js::CharsToNumber(const char16_t* chars, size_t length);
1925
1926 double js::LinearStringToNumber(const JSLinearString* str) {
1927 if (str->hasIndexValue()) {
1928 return str->getIndexValue();
1929 }
1930
1931 AutoCheckCannotGC nogc;
1932 return str->hasLatin1Chars()
1933 ? CharsToNumber(str->latin1Chars(nogc), str->length())
1934 : CharsToNumber(str->twoByteChars(nogc), str->length());
1935 }
1936
1937 bool js::StringToNumber(JSContext* cx, JSString* str, double* result) {
1938 JSLinearString* linearStr = str->ensureLinear(cx);
1939 if (!linearStr) {
1940 return false;
1941 }
1942
1943 *result = LinearStringToNumber(linearStr);
1944 return true;
1945 }
1946
1947 bool js::StringToNumberPure(JSContext* cx, JSString* str, double* result) {
1948 // IC Code calls this directly.
1949 AutoUnsafeCallWithABI unsafe;
1950
1951 if (!StringToNumber(cx, str, result)) {
1952 cx->recoverFromOutOfMemory();
1953 return false;
1954 }
1955 return true;
1956 }
1957
1958 JS_PUBLIC_API bool js::ToNumberSlow(JSContext* cx, HandleValue v_,
1959 double* out) {
1960 RootedValue v(cx, v_);
1961 MOZ_ASSERT(!v.isNumber());
1962
1963 if (!v.isPrimitive()) {
1964 if (!ToPrimitive(cx, JSTYPE_NUMBER, &v)) {
1965 return false;
1966 }
1967
1968 if (v.isNumber()) {
1969 *out = v.toNumber();
1970 return true;
1971 }
1972 }
1973 if (v.isString()) {
1974 return StringToNumber(cx, v.toString(), out);
1975 }
1976 if (v.isBoolean()) {
1977 *out = v.toBoolean() ? 1.0 : 0.0;
1978 return true;
1979 }
1980 if (v.isNull()) {
1981 *out = 0.0;
1982 return true;
1983 }
1984 if (v.isUndefined()) {
1985 *out = GenericNaN();
1986 return true;
1987 }
1988
1989 MOZ_ASSERT(v.isSymbol() || v.isBigInt());
1990 unsigned errnum = JSMSG_SYMBOL_TO_NUMBER;
1991 if (v.isBigInt()) {
1992 errnum = JSMSG_BIGINT_TO_NUMBER;
1993 }
1994 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errnum);
1995 return false;
1996 }
1997
1998 // BigInt proposal section 3.1.6
1999 bool js::ToNumericSlow(JSContext* cx, MutableHandleValue vp) {
2000 MOZ_ASSERT(!vp.isNumeric());
2001
2002 // Step 1.
2003 if (!vp.isPrimitive()) {
2004 if (!ToPrimitive(cx, JSTYPE_NUMBER, vp)) {
2005 return false;
2006 }
2007 }
2008
2009 // Step 2.
2010 if (vp.isBigInt()) {
2011 return true;
2012 }
2013
2014 // Step 3.
2015 return ToNumber(cx, vp);
2016 }
2017
2018 /*
2019 * Convert a value to an int8_t, according to the WebIDL rules for byte
2020 * conversion. Return converted value in *out on success, false on failure.
2021 */
2022 JS_PUBLIC_API bool js::ToInt8Slow(JSContext* cx, const HandleValue v,
2023 int8_t* out) {
2024 MOZ_ASSERT(!v.isInt32());
2025 double d;
2026 if (v.isDouble()) {
2027 d = v.toDouble();
2028 } else {
2029 if (!ToNumberSlow(cx, v, &d)) {
2030 return false;
2031 }
2032 }
2033 *out = ToInt8(d);
2034 return true;
2035 }
2036
2037 /*
2038 * Convert a value to an uint8_t, according to the ToUInt8() function in ES6
2039 * ECMA-262, 7.1.10. Return converted value in *out on success, false on
2040 * failure.
2041 */
2042 JS_PUBLIC_API bool js::ToUint8Slow(JSContext* cx, const HandleValue v,
2043 uint8_t* out) {
2044 MOZ_ASSERT(!v.isInt32());
2045 double d;
2046 if (v.isDouble()) {
2047 d = v.toDouble();
2048 } else {
2049 if (!ToNumberSlow(cx, v, &d)) {
2050 return false;
2051 }
2052 }
2053 *out = ToUint8(d);
2054 return true;
2055 }
2056
2057 /*
2058 * Convert a value to an int16_t, according to the WebIDL rules for short
2059 * conversion. Return converted value in *out on success, false on failure.
2060 */
2061 JS_PUBLIC_API bool js::ToInt16Slow(JSContext* cx, const HandleValue v,
2062 int16_t* out) {
2063 MOZ_ASSERT(!v.isInt32());
2064 double d;
2065 if (v.isDouble()) {
2066 d = v.toDouble();
2067 } else {
2068 if (!ToNumberSlow(cx, v, &d)) {
2069 return false;
2070 }
2071 }
2072 *out = ToInt16(d);
2073 return true;
2074 }
2075
2076 /*
2077 * Convert a value to an int64_t, according to the WebIDL rules for long long
2078 * conversion. Return converted value in *out on success, false on failure.
2079 */
2080 JS_PUBLIC_API bool js::ToInt64Slow(JSContext* cx, const HandleValue v,
2081 int64_t* out) {
2082 MOZ_ASSERT(!v.isInt32());
2083 double d;
2084 if (v.isDouble()) {
2085 d = v.toDouble();
2086 } else {
2087 if (!ToNumberSlow(cx, v, &d)) {
2088 return false;
2089 }
2090 }
2091 *out = ToInt64(d);
2092 return true;
2093 }
2094
2095 /*
2096 * Convert a value to an uint64_t, according to the WebIDL rules for unsigned
2097 * long long conversion. Return converted value in *out on success, false on
2098 * failure.
2099 */
2100 JS_PUBLIC_API bool js::ToUint64Slow(JSContext* cx, const HandleValue v,
2101 uint64_t* out) {
2102 MOZ_ASSERT(!v.isInt32());
2103 double d;
2104 if (v.isDouble()) {
2105 d = v.toDouble();
2106 } else {
2107 if (!ToNumberSlow(cx, v, &d)) {
2108 return false;
2109 }
2110 }
2111 *out = ToUint64(d);
2112 return true;
2113 }
2114
2115 JS_PUBLIC_API bool js::ToInt32Slow(JSContext* cx, const HandleValue v,
2116 int32_t* out) {
2117 MOZ_ASSERT(!v.isInt32());
2118 double d;
2119 if (v.isDouble()) {
2120 d = v.toDouble();
2121 } else {
2122 if (!ToNumberSlow(cx, v, &d)) {
2123 return false;
2124 }
2125 }
2126 *out = ToInt32(d);
2127 return true;
2128 }
2129
2130 bool js::ToInt32OrBigIntSlow(JSContext* cx, MutableHandleValue vp) {
2131 MOZ_ASSERT(!vp.isInt32());
2132 if (vp.isDouble()) {
2133 vp.setInt32(ToInt32(vp.toDouble()));
2134 return true;
2135 }
2136
2137 if (!ToNumeric(cx, vp)) {
2138 return false;
2139 }
2140
2141 if (vp.isBigInt()) {
2142 return true;
2143 }
2144
2145 vp.setInt32(ToInt32(vp.toNumber()));
2146 return true;
2147 }
2148
2149 JS_PUBLIC_API bool js::ToUint32Slow(JSContext* cx, const HandleValue v,
2150 uint32_t* out) {
2151 MOZ_ASSERT(!v.isInt32());
2152 double d;
2153 if (v.isDouble()) {
2154 d = v.toDouble();
2155 } else {
2156 if (!ToNumberSlow(cx, v, &d)) {
2157 return false;
2158 }
2159 }
2160 *out = ToUint32(d);
2161 return true;
2162 }
2163
2164 JS_PUBLIC_API bool js::ToUint16Slow(JSContext* cx, const HandleValue v,
2165 uint16_t* out) {
2166 MOZ_ASSERT(!v.isInt32());
2167 double d;
2168 if (v.isDouble()) {
2169 d = v.toDouble();
2170 } else if (!ToNumberSlow(cx, v, &d)) {
2171 return false;
2172 }
2173 *out = ToUint16(d);
2174 return true;
2175 }
2176
2177 // ES2017 draft 7.1.17 ToIndex
2178 bool js::ToIndexSlow(JSContext* cx, JS::HandleValue v,
2179 const unsigned errorNumber, uint64_t* index) {
2180 MOZ_ASSERT_IF(v.isInt32(), v.toInt32() < 0);
2181
2182 // Step 1.
2183 if (v.isUndefined()) {
2184 *index = 0;
2185 return true;
2186 }
2187
2188 // Step 2.a.
2189 double integerIndex;
2190 if (!ToInteger(cx, v, &integerIndex)) {
2191 return false;
2192 }
2193
2194 // Inlined version of ToLength.
2195 // 1. Already an integer.
2196 // 2. Step eliminates < 0, +0 == -0 with SameValueZero.
2197 // 3/4. Limit to <= 2^53-1, so everything above should fail.
2198 if (integerIndex < 0 || integerIndex >= DOUBLE_INTEGRAL_PRECISION_LIMIT) {
2199 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNumber);
2200 return false;
2201 }
2202
2203 // Step 3.
2204 *index = uint64_t(integerIndex);
2205 return true;
2206 }
2207
2208 /**
2209 * Convert |value| to an integer and clamp it to a valid integer index within
2210 * the range `[0..length]`.
2211 */
2212 template <typename ArrayLength>
2213 bool js::ToIntegerIndexSlow(JSContext* cx, Handle<Value> value,
2214 ArrayLength length, ArrayLength* result) {
2215 MOZ_ASSERT(!value.isInt32());
2216
2217 double relative;
2218 if (!ToInteger(cx, value, &relative)) {
2219 return false;
2220 }
2221
2222 if (relative >= 0) {
2223 *result = ArrayLength(std::min(relative, double(length)));
2224 } else {
2225 *result = ArrayLength(std::max(relative + double(length), 0.0));
2226 }
2227 return true;
2228 }
2229
2230 // Dummy type used when `size_t` is the same type as `uint64_t`. Implements
2231 // constructor and conversion methods called in ToIntegerIndexSlow.
2232 struct Dummy {
2233 explicit Dummy(double) {}
2234 explicit operator double() { return 0; }
2235 };
2236
2237 // Instantiate ToIntegerIndexSlow for `size_t` and `uint64_t`, but avoid a
2238 // duplicate instantiation error for the case when `size_t` is the same type as
2239 // `uint64_t`.
2240
2241 using Uint64OrDummy =
2242 std::conditional_t<!std::is_same_v<uint64_t, size_t>, uint64_t, Dummy>;
2243
2244 template bool js::ToIntegerIndexSlow<size_t>(JSContext*, Handle<Value>, size_t,
2245 size_t*);
2246
2247 template bool js::ToIntegerIndexSlow<Uint64OrDummy>(JSContext*, Handle<Value>,
2248 Uint64OrDummy,
2249 Uint64OrDummy*);
2250
2251 template <typename CharT>
2252 double js_strtod(const CharT* begin, const CharT* end, const CharT** dEnd) {
2253 const CharT* s = SkipSpace(begin, end);
2254 size_t length = end - s;
2255
2256 {
2257 // StringToDouble can make indirect calls but can't trigger a GC.
2258 JS::AutoSuppressGCAnalysis nogc;
2259
2260 using SToDConverter = double_conversion::StringToDoubleConverter;
2261 SToDConverter converter(SToDConverter::ALLOW_TRAILING_JUNK,
2262 /* empty_string_value = */ 0.0,
2263 /* junk_string_value = */ GenericNaN(),
2264 /* infinity_symbol = */ nullptr,
2265 /* nan_symbol = */ nullptr);
2266 int lengthInt = mozilla::AssertedCast<int>(length);
2267 double d;
2268 int processed = 0;
2269 if constexpr (std::is_same_v<CharT, char16_t>) {
2270 d = converter.StringToDouble(reinterpret_cast<const uc16*>(s), lengthInt,
2271 &processed);
2272 } else {
2273 static_assert(std::is_same_v<CharT, Latin1Char>);
2274 d = converter.StringToDouble(reinterpret_cast<const char*>(s), lengthInt,
2275 &processed);
2276 }
2277 MOZ_ASSERT(processed >= 0);
2278 MOZ_ASSERT(processed <= lengthInt);
2279
2280 if (processed > 0) {
2281 *dEnd = s + processed;
2282 return d;
2283 }
2284 }
2285
2286 // Try to parse +Infinity, -Infinity or Infinity. Note that we do this here
2287 // instead of using StringToDoubleConverter's infinity_symbol because it's
2288 // faster: the code below is less generic and not on the fast path for regular
2289 // doubles.
2290 static constexpr std::string_view Infinity = "Infinity";
2291 if (length >= Infinity.length()) {
2292 const CharT* afterSign = s;
2293 bool negative = (*afterSign == '-');
2294 if (negative || *afterSign == '+') {
2295 afterSign++;
2296 }
2297 MOZ_ASSERT(afterSign < end);
2298 if (*afterSign == 'I' && size_t(end - afterSign) >= Infinity.length() &&
2299 EqualChars(afterSign, Infinity.data(), Infinity.length())) {
2300 *dEnd = afterSign + Infinity.length();
2301 return negative ? NegativeInfinity<double>() : PositiveInfinity<double>();
2302 }
2303 }
2304
2305 *dEnd = begin;
2306 return 0.0;
2307 }
2308
2309 template double js_strtod(const char16_t* begin, const char16_t* end,
2310 const char16_t** dEnd);
2311
2312 template double js_strtod(const Latin1Char* begin, const Latin1Char* end,
2313 const Latin1Char** dEnd);