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/. */
8 * JS number type and wrapper class.
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"
23 #ifdef HAVE_LOCALECONV
27 #include <string.h> // memmove
28 #include <string_view>
32 #include "double-conversion/double-conversion.h"
33 #include "frontend/ParserAtom.h" // frontend::{ParserAtomsTable, TaggedParserAtomIndex}
34 #include "jit/InlinableNatives.h"
35 #include "js/CharacterEncoding.h"
36 #include "js/Conversions.h"
37 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
40 # include "js/LocaleSensitive.h"
42 #include "js/PropertyAndElement.h" // JS_DefineFunctions
43 #include "js/PropertySpec.h"
44 #include "util/DoubleToString.h"
45 #include "util/Memory.h"
46 #include "util/StringBuffer.h"
47 #include "vm/BigIntType.h"
48 #include "vm/GlobalObject.h"
49 #include "vm/JSAtomUtils.h" // Atomize, AtomizeString
50 #include "vm/JSContext.h"
51 #include "vm/JSObject.h"
52 #include "vm/StaticStrings.h"
53 #include "vm/WellKnownAtom.h" // js_*_str
55 #include "vm/Compartment-inl.h" // For js::UnwrapAndTypeCheckThis
56 #include "vm/GeckoProfiler-inl.h"
57 #include "vm/JSAtomUtils-inl.h" // BackfillIndexInCharBuffer
58 #include "vm/NativeObject-inl.h"
59 #include "vm/NumberObject-inl.h"
60 #include "vm/StringType-inl.h"
65 using mozilla::AsciiAlphanumericToNumber
;
66 using mozilla::IsAsciiAlphanumeric
;
67 using mozilla::IsAsciiDigit
;
69 using mozilla::MinNumberValue
;
70 using mozilla::NegativeInfinity
;
71 using mozilla::NumberEqualsInt32
;
72 using mozilla::PositiveInfinity
;
73 using mozilla::RangedPtr
;
74 using mozilla::Utf8AsUnsignedChars
;
75 using mozilla::Utf8Unit
;
77 using JS::AutoCheckCannotGC
;
88 static bool EnsureDtoaState(JSContext
* cx
) {
90 cx
->dtoaState
= NewDtoaState();
98 template <typename CharT
>
99 static inline void AssertWellPlacedNumericSeparator(const CharT
* s
,
102 MOZ_ASSERT(start
< end
, "string is non-empty");
103 MOZ_ASSERT(s
> start
, "number can't start with a separator");
104 MOZ_ASSERT(s
+ 1 < end
,
105 "final character in a numeric literal can't be a separator");
106 MOZ_ASSERT(*(s
+ 1) != '_',
107 "separator can't be followed by another separator");
108 MOZ_ASSERT(*(s
- 1) != '_',
109 "separator can't be preceded by another separator");
114 template <typename CharT
>
115 class BinaryDigitReader
{
116 const int base
; /* Base of number; must be a power of 2 */
117 int digit
; /* Current digit value in radix given by base */
118 int digitMask
; /* Mask to extract the next bit from digit */
119 const CharT
* cur
; /* Pointer to the remaining digits */
120 const CharT
* start
; /* Pointer to the start of the string */
121 const CharT
* end
; /* Pointer to first non-digit */
124 BinaryDigitReader(int base
, const CharT
* start
, const CharT
* end
)
132 /* Return the next binary digit from the number, or -1 if done. */
134 if (digitMask
== 0) {
141 AssertWellPlacedNumericSeparator(cur
- 1, start
, end
);
145 MOZ_ASSERT(IsAsciiAlphanumeric(c
));
146 digit
= AsciiAlphanumericToNumber(c
);
147 digitMask
= base
>> 1;
150 int bit
= (digit
& digitMask
) != 0;
156 } /* anonymous namespace */
159 * The fast result might also have been inaccurate for power-of-two bases. This
160 * happens if the addition in value * 2 + digit causes a round-down to an even
161 * least significant mantissa bit when the first dropped bit is a one. If any
162 * of the following digits in the number (which haven't been added in yet) are
163 * nonzero, then the correct action would have been to round up instead of
164 * down. An example occurs when reading the number 0x1000000000000081, which
165 * rounds to 0x1000000000000000 instead of 0x1000000000000100.
167 template <typename CharT
>
168 static double ComputeAccurateBinaryBaseInteger(const CharT
* start
,
169 const CharT
* end
, int base
) {
170 BinaryDigitReader
<CharT
> bdr(base
, start
, end
);
172 /* Skip leading zeroes. */
175 bit
= bdr
.nextDigit();
178 MOZ_ASSERT(bit
== 1); // guaranteed by Get{Prefix,Decimal}Integer
180 /* Gather the 53 significant bits (including the leading 1). */
182 for (int j
= 52; j
> 0; j
--) {
183 bit
= bdr
.nextDigit();
187 value
= value
* 2 + bit
;
190 /* bit2 is the 54th bit (the first dropped from the mantissa). */
191 int bit2
= bdr
.nextDigit();
194 int sticky
= 0; /* sticky is 1 if any bit beyond the 54th is 1 */
197 while ((bit3
= bdr
.nextDigit()) >= 0) {
201 value
+= bit2
& (bit
| sticky
);
208 template <typename CharT
>
209 double js::ParseDecimalNumber(const mozilla::Range
<const CharT
> chars
) {
210 MOZ_ASSERT(chars
.length() > 0);
212 RangedPtr
<const CharT
> s
= chars
.begin(), end
= chars
.end();
215 MOZ_ASSERT('0' <= c
&& c
<= '9');
216 uint8_t digit
= c
- '0';
217 uint64_t next
= dec
* 10 + digit
;
218 MOZ_ASSERT(next
< DOUBLE_INTEGRAL_PRECISION_LIMIT
,
219 "next value won't be an integrally-precise double");
222 return static_cast<double>(dec
);
225 template double js::ParseDecimalNumber(
226 const mozilla::Range
<const Latin1Char
> chars
);
228 template double js::ParseDecimalNumber(
229 const mozilla::Range
<const char16_t
> chars
);
231 template <typename CharT
>
232 static bool GetPrefixIntegerImpl(const CharT
* start
, const CharT
* end
, int base
,
233 IntegerSeparatorHandling separatorHandling
,
234 const CharT
** endp
, double* dp
) {
235 MOZ_ASSERT(start
<= end
);
236 MOZ_ASSERT(2 <= base
&& base
<= 36);
238 const CharT
* s
= start
;
240 for (; s
< end
; s
++) {
242 if (!IsAsciiAlphanumeric(c
)) {
244 separatorHandling
== IntegerSeparatorHandling::SkipUnderscore
) {
245 AssertWellPlacedNumericSeparator(s
, start
, end
);
251 uint8_t digit
= AsciiAlphanumericToNumber(c
);
256 d
= d
* base
+ digit
;
262 /* If we haven't reached the limit of integer precision, we're done. */
263 if (d
< DOUBLE_INTEGRAL_PRECISION_LIMIT
) {
268 * Otherwise compute the correct integer from the prefix of valid digits
269 * if we're computing for base ten or a power of two. Don't worry about
270 * other bases; see ES2018, 18.2.5 `parseInt(string, radix)`, step 13.
276 if ((base
& (base
- 1)) == 0) {
277 *dp
= ComputeAccurateBinaryBaseInteger(start
, s
, base
);
283 template <typename CharT
>
284 bool js::GetPrefixInteger(const CharT
* start
, const CharT
* end
, int base
,
285 IntegerSeparatorHandling separatorHandling
,
286 const CharT
** endp
, double* dp
) {
287 if (GetPrefixIntegerImpl(start
, end
, base
, separatorHandling
, endp
, dp
)) {
291 // Can only fail for base 10.
292 MOZ_ASSERT(base
== 10);
294 // If we're accumulating a decimal number and the number is >= 2^53, then the
295 // fast result from the loop in GetPrefixIntegerImpl may be inaccurate. Call
296 // GetDecimal to get the correct answer.
297 return GetDecimal(start
, *endp
, dp
);
302 template bool GetPrefixInteger(const char16_t
* start
, const char16_t
* end
,
304 IntegerSeparatorHandling separatorHandling
,
305 const char16_t
** endp
, double* dp
);
307 template bool GetPrefixInteger(const Latin1Char
* start
, const Latin1Char
* end
,
309 IntegerSeparatorHandling separatorHandling
,
310 const Latin1Char
** endp
, double* dp
);
314 template <typename CharT
>
315 bool js::GetDecimalInteger(const CharT
* start
, const CharT
* end
, double* dp
) {
316 MOZ_ASSERT(start
<= end
);
319 for (const CharT
* s
= start
; s
< end
; s
++) {
322 AssertWellPlacedNumericSeparator(s
, start
, end
);
325 MOZ_ASSERT(IsAsciiDigit(c
));
330 // If we haven't reached the limit of integer precision, we're done.
331 if (d
< DOUBLE_INTEGRAL_PRECISION_LIMIT
) {
336 // Otherwise compute the correct integer using GetDecimal.
337 return GetDecimal(start
, end
, dp
);
342 template bool GetDecimalInteger(const char16_t
* start
, const char16_t
* end
,
345 template bool GetDecimalInteger(const Latin1Char
* start
, const Latin1Char
* end
,
349 bool GetDecimalInteger
<Utf8Unit
>(const Utf8Unit
* start
, const Utf8Unit
* end
,
351 return GetDecimalInteger(Utf8AsUnsignedChars(start
), Utf8AsUnsignedChars(end
),
357 template <typename CharT
>
358 bool js::GetDecimal(const CharT
* start
, const CharT
* end
, double* dp
) {
359 MOZ_ASSERT(start
<= end
);
361 size_t length
= end
- start
;
363 auto convert
= [](auto* chars
, size_t length
) -> double {
364 using SToDConverter
= double_conversion::StringToDoubleConverter
;
365 SToDConverter
converter(/* flags = */ 0, /* empty_string_value = */ 0.0,
366 /* junk_string_value = */ 0.0,
367 /* infinity_symbol = */ nullptr,
368 /* nan_symbol = */ nullptr);
369 int lengthInt
= mozilla::AssertedCast
<int>(length
);
371 double d
= converter
.StringToDouble(chars
, lengthInt
, &processed
);
372 MOZ_ASSERT(processed
>= 0);
373 MOZ_ASSERT(size_t(processed
) == length
);
377 // If there are no underscores, we don't need to copy the chars.
378 bool hasUnderscore
= std::any_of(start
, end
, [](auto c
) { return c
== '_'; });
379 if (!hasUnderscore
) {
380 if constexpr (std::is_same_v
<CharT
, char16_t
>) {
381 *dp
= convert(reinterpret_cast<const uc16
*>(start
), length
);
383 static_assert(std::is_same_v
<CharT
, Latin1Char
>);
384 *dp
= convert(reinterpret_cast<const char*>(start
), length
);
389 Vector
<char, 32, SystemAllocPolicy
> chars
;
390 if (!chars
.growByUninitialized(length
)) {
394 const CharT
* s
= start
;
396 for (; s
< end
; s
++) {
399 AssertWellPlacedNumericSeparator(s
, start
, end
);
402 MOZ_ASSERT(IsAsciiDigit(c
) || c
== '.' || c
== 'e' || c
== 'E' ||
403 c
== '+' || c
== '-');
404 chars
[i
++] = char(c
);
407 *dp
= convert(chars
.begin(), i
);
413 template bool GetDecimal(const char16_t
* start
, const char16_t
* end
,
416 template bool GetDecimal(const Latin1Char
* start
, const Latin1Char
* end
,
420 bool GetDecimal
<Utf8Unit
>(const Utf8Unit
* start
, const Utf8Unit
* end
,
422 return GetDecimal(Utf8AsUnsignedChars(start
), Utf8AsUnsignedChars(end
), dp
);
427 static bool num_parseFloat(JSContext
* cx
, unsigned argc
, Value
* vp
) {
428 CallArgs args
= CallArgsFromVp(argc
, vp
);
430 if (args
.length() == 0) {
431 args
.rval().setNaN();
435 if (args
[0].isNumber()) {
436 // ToString(-0) is "0", handle it accordingly.
437 if (args
[0].isDouble() && args
[0].toDouble() == 0.0) {
438 args
.rval().setInt32(0);
440 args
.rval().set(args
[0]);
445 JSString
* str
= ToString
<CanGC
>(cx
, args
[0]);
450 if (str
->hasIndexValue()) {
451 args
.rval().setNumber(str
->getIndexValue());
455 JSLinearString
* linear
= str
->ensureLinear(cx
);
461 AutoCheckCannotGC nogc
;
462 if (linear
->hasLatin1Chars()) {
463 const Latin1Char
* begin
= linear
->latin1Chars(nogc
);
464 const Latin1Char
* end
;
465 d
= js_strtod(begin
, begin
+ linear
->length(), &end
);
470 const char16_t
* begin
= linear
->twoByteChars(nogc
);
472 d
= js_strtod(begin
, begin
+ linear
->length(), &end
);
478 args
.rval().setDouble(d
);
482 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
483 // 19.2.5 parseInt ( string, radix )
484 template <typename CharT
>
485 static bool ParseIntImpl(JSContext
* cx
, const CharT
* chars
, size_t length
,
486 bool stripPrefix
, int32_t radix
, double* res
) {
488 const CharT
* end
= chars
+ length
;
489 const CharT
* s
= SkipSpace(chars
, end
);
491 MOZ_ASSERT(chars
<= s
);
492 MOZ_ASSERT(s
<= end
);
495 bool negative
= (s
!= end
&& s
[0] == '-');
498 if (s
!= end
&& (s
[0] == '-' || s
[0] == '+')) {
504 if (end
- s
>= 2 && s
[0] == '0' && (s
[1] == 'x' || s
[1] == 'X')) {
511 const CharT
* actualEnd
;
513 if (!js::GetPrefixInteger(s
, end
, radix
, IntegerSeparatorHandling::None
,
515 ReportOutOfMemory(cx
);
519 if (s
== actualEnd
) {
522 *res
= negative
? -d
: d
;
527 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
528 // 19.2.5 parseInt ( string, radix )
529 bool js::NumberParseInt(JSContext
* cx
, HandleString str
, int32_t radix
,
530 MutableHandleValue result
) {
532 bool stripPrefix
= true;
536 if (radix
< 2 || radix
> 36) {
547 MOZ_ASSERT(2 <= radix
&& radix
<= 36);
549 JSLinearString
* linear
= str
->ensureLinear(cx
);
555 AutoCheckCannotGC nogc
;
556 size_t length
= linear
->length();
558 if (linear
->hasLatin1Chars()) {
559 if (!ParseIntImpl(cx
, linear
->latin1Chars(nogc
), length
, stripPrefix
, radix
,
564 if (!ParseIntImpl(cx
, linear
->twoByteChars(nogc
), length
, stripPrefix
,
570 result
.setNumber(number
);
574 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
575 // 19.2.5 parseInt ( string, radix )
576 static bool num_parseInt(JSContext
* cx
, unsigned argc
, Value
* vp
) {
577 CallArgs args
= CallArgsFromVp(argc
, vp
);
579 /* Fast paths and exceptional cases. */
580 if (args
.length() == 0) {
581 args
.rval().setNaN();
585 if (args
.length() == 1 || (args
[1].isInt32() && (args
[1].toInt32() == 0 ||
586 args
[1].toInt32() == 10))) {
587 if (args
[0].isInt32()) {
588 args
.rval().set(args
[0]);
593 * Step 1 is |inputString = ToString(string)|. When string >=
594 * 1e21, ToString(string) is in the form "NeM". 'e' marks the end of
595 * the word, which would mean the result of parseInt(string) should be |N|.
597 * To preserve this behaviour, we can't use the fast-path when string >=
598 * 1e21, or else the result would be |NeM|.
600 * The same goes for values smaller than 1.0e-6, because the string would be
601 * in the form of "Ne-M".
603 if (args
[0].isDouble()) {
604 double d
= args
[0].toDouble();
605 if (DOUBLE_DECIMAL_IN_SHORTEST_LOW
<= d
&&
606 d
< DOUBLE_DECIMAL_IN_SHORTEST_HIGH
) {
607 args
.rval().setNumber(floor(d
));
610 if (-DOUBLE_DECIMAL_IN_SHORTEST_HIGH
< d
&&
611 d
<= -DOUBLE_DECIMAL_IN_SHORTEST_LOW
) {
612 args
.rval().setNumber(-floor(-d
));
616 args
.rval().setInt32(0);
621 if (args
[0].isString()) {
622 JSString
* str
= args
[0].toString();
623 if (str
->hasIndexValue()) {
624 args
.rval().setNumber(str
->getIndexValue());
631 RootedString
inputString(cx
, ToString
<CanGC
>(cx
, args
[0]));
638 if (args
.hasDefined(1)) {
639 if (!ToInt32(cx
, args
[1], &radix
)) {
645 return NumberParseInt(cx
, inputString
, radix
, args
.rval());
648 static const JSFunctionSpec number_functions
[] = {
649 JS_SELF_HOSTED_FN(js_isNaN_str
, "Global_isNaN", 1, JSPROP_RESOLVING
),
650 JS_SELF_HOSTED_FN(js_isFinite_str
, "Global_isFinite", 1, JSPROP_RESOLVING
),
653 const JSClass
NumberObject::class_
= {
655 JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number
),
656 JS_NULL_CLASS_OPS
, &NumberObject::classSpec_
};
658 static bool Number(JSContext
* cx
, unsigned argc
, Value
* vp
) {
659 CallArgs args
= CallArgsFromVp(argc
, vp
);
661 if (args
.length() > 0) {
662 // BigInt proposal section 6.2, steps 2a-c.
663 if (!ToNumeric(cx
, args
[0])) {
666 if (args
[0].isBigInt()) {
667 args
[0].setNumber(BigInt::numberValue(args
[0].toBigInt()));
669 MOZ_ASSERT(args
[0].isNumber());
672 if (!args
.isConstructing()) {
673 if (args
.length() > 0) {
674 args
.rval().set(args
[0]);
676 args
.rval().setInt32(0);
681 RootedObject
proto(cx
);
682 if (!GetPrototypeFromBuiltinConstructor(cx
, args
, JSProto_Number
, &proto
)) {
686 double d
= args
.length() > 0 ? args
[0].toNumber() : 0;
687 JSObject
* obj
= NumberObject::create(cx
, d
, proto
);
691 args
.rval().setObject(*obj
);
695 // ES2020 draft rev e08b018785606bc6465a0456a79604b149007932
696 // 20.1.3 Properties of the Number Prototype Object, thisNumberValue.
698 static bool ThisNumberValue(JSContext
* cx
, const CallArgs
& args
,
699 const char* methodName
, double* number
) {
700 HandleValue thisv
= args
.thisv();
703 if (thisv
.isNumber()) {
704 *number
= thisv
.toNumber();
709 auto* obj
= UnwrapAndTypeCheckThis
<NumberObject
>(cx
, args
, methodName
);
714 *number
= obj
->unbox();
718 // On-off helper function for the self-hosted Number_toLocaleString method.
719 // This only exists to produce an error message with the right method name.
720 bool js::ThisNumberValueForToLocaleString(JSContext
* cx
, unsigned argc
,
722 CallArgs args
= CallArgsFromVp(argc
, vp
);
725 if (!ThisNumberValue(cx
, args
, "toLocaleString", &d
)) {
729 args
.rval().setNumber(d
);
733 static bool num_toSource(JSContext
* cx
, unsigned argc
, Value
* vp
) {
734 CallArgs args
= CallArgsFromVp(argc
, vp
);
737 if (!ThisNumberValue(cx
, args
, "toSource", &d
)) {
741 JSStringBuilder
sb(cx
);
742 if (!sb
.append("(new Number(") ||
743 !NumberValueToStringBuffer(NumberValue(d
), sb
) || !sb
.append("))")) {
747 JSString
* str
= sb
.finishString();
751 args
.rval().setString(str
);
755 // Subtract one from DTOSTR_STANDARD_BUFFER_SIZE to exclude the null-character.
757 double_conversion::DoubleToStringConverter::kMaxCharsEcmaScriptShortest
==
758 DTOSTR_STANDARD_BUFFER_SIZE
- 1,
759 "double_conversion and dtoa both agree how large the longest string "
762 static_assert(DTOSTR_STANDARD_BUFFER_SIZE
<= JS::MaximumNumberToStringLength
,
763 "MaximumNumberToStringLength is large enough to hold the longest "
764 "string produced by a conversion");
767 static JSLinearString
* LookupDtoaCache(JSContext
* cx
, double d
) {
768 if (Realm
* realm
= cx
->realm()) {
769 if (JSLinearString
* str
= realm
->dtoaCache
.lookup(10, d
)) {
778 static void CacheNumber(JSContext
* cx
, double d
, JSLinearString
* str
) {
779 if (Realm
* realm
= cx
->realm()) {
780 realm
->dtoaCache
.cache(10, d
, str
);
785 static JSLinearString
* LookupInt32ToString(JSContext
* cx
, int32_t si
) {
786 if (si
>= 0 && StaticStrings::hasInt(si
)) {
787 return cx
->staticStrings().getInt(si
);
790 return LookupDtoaCache(cx
, si
);
793 template <typename T
>
794 MOZ_ALWAYS_INLINE
static T
* BackfillInt32InBuffer(int32_t si
, T
* buffer
,
795 size_t size
, size_t* length
) {
796 uint32_t ui
= Abs(si
);
797 MOZ_ASSERT_IF(si
== INT32_MIN
, ui
== uint32_t(INT32_MAX
) + 1);
799 RangedPtr
<T
> end(buffer
+ size
- 1, buffer
, size
);
801 RangedPtr
<T
> start
= BackfillIndexInCharBuffer(ui
, end
);
806 *length
= end
- start
;
810 template <AllowGC allowGC
>
811 JSLinearString
* js::Int32ToString(JSContext
* cx
, int32_t si
) {
812 if (JSLinearString
* str
= LookupInt32ToString(cx
, si
)) {
816 Latin1Char buffer
[JSFatInlineString::MAX_LENGTH_LATIN1
+ 1];
819 BackfillInt32InBuffer(si
, buffer
, std::size(buffer
), &length
);
821 mozilla::Range
<const Latin1Char
> chars(start
, length
);
822 JSInlineString
* str
=
823 NewInlineString
<allowGC
>(cx
, chars
, js::gc::Heap::Default
);
828 str
->maybeInitializeIndexValue(si
);
831 CacheNumber(cx
, si
, str
);
835 template JSLinearString
* js::Int32ToString
<CanGC
>(JSContext
* cx
, int32_t si
);
837 template JSLinearString
* js::Int32ToString
<NoGC
>(JSContext
* cx
, int32_t si
);
839 JSLinearString
* js::Int32ToStringPure(JSContext
* cx
, int32_t si
) {
840 AutoUnsafeCallWithABI unsafe
;
841 return Int32ToString
<NoGC
>(cx
, si
);
844 JSAtom
* js::Int32ToAtom(JSContext
* cx
, int32_t si
) {
845 if (JSLinearString
* str
= LookupInt32ToString(cx
, si
)) {
846 return js::AtomizeString(cx
, str
);
849 char buffer
[JSFatInlineString::MAX_LENGTH_TWO_BYTE
+ 1];
851 char* start
= BackfillInt32InBuffer(
852 si
, buffer
, JSFatInlineString::MAX_LENGTH_TWO_BYTE
+ 1, &length
);
854 Maybe
<uint32_t> indexValue
;
856 indexValue
.emplace(si
);
859 JSAtom
* atom
= Atomize(cx
, start
, length
, indexValue
);
864 CacheNumber(cx
, si
, atom
);
868 frontend::TaggedParserAtomIndex
js::Int32ToParserAtom(
869 FrontendContext
* fc
, frontend::ParserAtomsTable
& parserAtoms
, int32_t si
) {
870 char buffer
[JSFatInlineString::MAX_LENGTH_TWO_BYTE
+ 1];
872 char* start
= BackfillInt32InBuffer(
873 si
, buffer
, JSFatInlineString::MAX_LENGTH_TWO_BYTE
+ 1, &length
);
875 Maybe
<uint32_t> indexValue
;
877 indexValue
.emplace(si
);
880 return parserAtoms
.internAscii(fc
, start
, length
);
883 /* Returns a non-nullptr pointer to inside `buf`. */
884 template <typename T
>
885 static char* Int32ToCStringWithBase(mozilla::Range
<char> buf
, T i
, size_t* len
,
888 if constexpr (std::is_signed_v
<T
>) {
894 RangedPtr
<char> cp
= buf
.end() - 1;
896 char* end
= cp
.get();
899 /* Build the string from behind. */
902 cp
= BackfillIndexInCharBuffer(u
, cp
);
906 unsigned newu
= u
/ 16;
907 *--cp
= "0123456789abcdef"[u
- newu
* 16];
912 MOZ_ASSERT(base
>= 2 && base
<= 36);
914 unsigned newu
= u
/ base
;
915 *--cp
= "0123456789abcdefghijklmnopqrstuvwxyz"[u
- newu
* base
];
920 if constexpr (std::is_signed_v
<T
>) {
926 *len
= end
- cp
.get();
930 /* Returns a non-nullptr pointer to inside `out`. */
931 template <typename T
, size_t Length
>
932 static char* Int32ToCStringWithBase(char (&out
)[Length
], T i
, size_t* len
,
934 // The buffer needs to be large enough to hold the largest number, including
935 // the sign and the terminating null-character.
936 static_assert(std::numeric_limits
<T
>::digits
+ (2 * std::is_signed_v
<T
>) <
939 mozilla::Range
<char> buf(out
, Length
);
940 return Int32ToCStringWithBase(buf
, i
, len
, base
);
943 /* Returns a non-nullptr pointer to inside `out`. */
944 template <typename T
, size_t Base
, size_t Length
>
945 static char* Int32ToCString(char (&out
)[Length
], T i
, size_t* len
) {
946 // The buffer needs to be large enough to hold the largest number, including
947 // the sign and the terminating null-character.
948 if constexpr (Base
== 10) {
949 static_assert(std::numeric_limits
<T
>::digits10
+ 1 + std::is_signed_v
<T
> <
952 // Compute digits16 analog to std::numeric_limits::digits10, which is
953 // defined as |std::numeric_limits::digits * std::log10(2)| for integer
955 // Note: log16(2) is 1/4.
956 static_assert(Base
== 16);
957 static_assert(((std::numeric_limits
<T
>::digits
+ std::is_signed_v
<T
>) / 4 +
958 std::is_signed_v
<T
>) < Length
);
961 mozilla::Range
<char> buf(out
, Length
);
962 return Int32ToCStringWithBase(buf
, i
, len
, Base
);
965 /* Returns a non-nullptr pointer to inside `cbuf`. */
966 template <typename T
, size_t Base
= 10>
967 static char* Int32ToCString(ToCStringBuf
* cbuf
, T i
, size_t* len
) {
968 return Int32ToCString
<T
, Base
>(cbuf
->sbuf
, i
, len
);
971 /* Returns a non-nullptr pointer to inside `cbuf`. */
972 template <typename T
, size_t Base
= 10>
973 static char* Int32ToCString(Int32ToCStringBuf
* cbuf
, T i
, size_t* len
) {
974 return Int32ToCString
<T
, Base
>(cbuf
->sbuf
, i
, len
);
977 template <AllowGC allowGC
>
978 static JSString
* NumberToStringWithBase(JSContext
* cx
, double d
, int base
);
980 static bool num_toString(JSContext
* cx
, unsigned argc
, Value
* vp
) {
981 CallArgs args
= CallArgsFromVp(argc
, vp
);
984 if (!ThisNumberValue(cx
, args
, "toString", &d
)) {
989 if (args
.hasDefined(0)) {
991 if (!ToInteger(cx
, args
[0], &d2
)) {
995 if (d2
< 2 || d2
> 36) {
996 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, JSMSG_BAD_RADIX
);
1002 JSString
* str
= NumberToStringWithBase
<CanGC
>(cx
, d
, base
);
1006 args
.rval().setString(str
);
1010 #if !JS_HAS_INTL_API
1011 static bool num_toLocaleString(JSContext
* cx
, unsigned argc
, Value
* vp
) {
1012 AutoJSMethodProfilerEntry
pseudoFrame(cx
, "Number.prototype",
1014 CallArgs args
= CallArgsFromVp(argc
, vp
);
1017 if (!ThisNumberValue(cx
, args
, "toLocaleString", &d
)) {
1021 RootedString
str(cx
, NumberToStringWithBase
<CanGC
>(cx
, d
, 10));
1027 * Create the string, move back to bytes to make string twiddling
1028 * a bit easier and so we can insert platform charset seperators.
1030 UniqueChars numBytes
= EncodeAscii(cx
, str
);
1034 const char* num
= numBytes
.get();
1040 * Find the first non-integer value, whether it be a letter as in
1041 * 'Infinity', a decimal point, or an 'e' from exponential notation.
1043 const char* nint
= num
;
1047 while (*nint
>= '0' && *nint
<= '9') {
1050 int digits
= nint
- num
;
1051 const char* end
= num
+ digits
;
1053 args
.rval().setString(str
);
1057 JSRuntime
* rt
= cx
->runtime();
1058 size_t thousandsLength
= strlen(rt
->thousandsSeparator
);
1059 size_t decimalLength
= strlen(rt
->decimalSeparator
);
1061 /* Figure out how long resulting string will be. */
1062 int buflen
= strlen(num
);
1064 buflen
+= decimalLength
- 1; /* -1 to account for existing '.' */
1067 const char* numGrouping
;
1068 const char* tmpGroup
;
1069 numGrouping
= tmpGroup
= rt
->numGrouping
;
1070 int remainder
= digits
;
1075 while (*tmpGroup
!= CHAR_MAX
&& *tmpGroup
!= '\0') {
1076 if (*tmpGroup
>= remainder
) {
1079 buflen
+= thousandsLength
;
1080 remainder
-= *tmpGroup
;
1085 if (*tmpGroup
== '\0' && *numGrouping
!= '\0') {
1086 nrepeat
= (remainder
- 1) / tmpGroup
[-1];
1087 buflen
+= thousandsLength
* nrepeat
;
1088 remainder
-= nrepeat
* tmpGroup
[-1];
1094 char* buf
= cx
->pod_malloc
<char>(buflen
+ 1);
1099 char* tmpDest
= buf
;
1100 const char* tmpSrc
= num
;
1102 while (*tmpSrc
== '-' || remainder
--) {
1103 MOZ_ASSERT(tmpDest
- buf
< buflen
);
1104 *tmpDest
++ = *tmpSrc
++;
1106 while (tmpSrc
< end
) {
1107 MOZ_ASSERT(tmpDest
- buf
+ ptrdiff_t(thousandsLength
) <= buflen
);
1108 strcpy(tmpDest
, rt
->thousandsSeparator
);
1109 tmpDest
+= thousandsLength
;
1110 MOZ_ASSERT(tmpDest
- buf
+ *tmpGroup
<= buflen
);
1111 js_memcpy(tmpDest
, tmpSrc
, *tmpGroup
);
1112 tmpDest
+= *tmpGroup
;
1113 tmpSrc
+= *tmpGroup
;
1114 if (--nrepeat
< 0) {
1120 MOZ_ASSERT(tmpDest
- buf
+ ptrdiff_t(decimalLength
) <= buflen
);
1121 strcpy(tmpDest
, rt
->decimalSeparator
);
1122 tmpDest
+= decimalLength
;
1123 MOZ_ASSERT(tmpDest
- buf
+ ptrdiff_t(strlen(nint
+ 1)) <= buflen
);
1124 strcpy(tmpDest
, nint
+ 1);
1126 MOZ_ASSERT(tmpDest
- buf
+ ptrdiff_t(strlen(nint
)) <= buflen
);
1127 strcpy(tmpDest
, nint
);
1130 if (cx
->runtime()->localeCallbacks
&&
1131 cx
->runtime()->localeCallbacks
->localeToUnicode
) {
1132 Rooted
<Value
> v(cx
, StringValue(str
));
1133 bool ok
= !!cx
->runtime()->localeCallbacks
->localeToUnicode(cx
, buf
, &v
);
1141 str
= NewStringCopyN
<CanGC
>(cx
, buf
, buflen
);
1147 args
.rval().setString(str
);
1150 #endif /* !JS_HAS_INTL_API */
1152 bool js::num_valueOf(JSContext
* cx
, unsigned argc
, Value
* vp
) {
1153 CallArgs args
= CallArgsFromVp(argc
, vp
);
1156 if (!ThisNumberValue(cx
, args
, "valueOf", &d
)) {
1160 args
.rval().setNumber(d
);
1164 static const unsigned MAX_PRECISION
= 100;
1166 static bool ComputePrecisionInRange(JSContext
* cx
, int minPrecision
,
1167 int maxPrecision
, double prec
,
1169 if (minPrecision
<= prec
&& prec
<= maxPrecision
) {
1170 *precision
= int(prec
);
1175 char* numStr
= NumberToCString(&cbuf
, prec
);
1177 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, JSMSG_PRECISION_RANGE
,
1182 static constexpr size_t DoubleToStrResultBufSize
= 128;
1184 template <typename Op
>
1185 [[nodiscard
]] static bool DoubleToStrResult(JSContext
* cx
, const CallArgs
& args
,
1187 char buf
[DoubleToStrResultBufSize
];
1189 const auto& converter
=
1190 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1191 double_conversion::StringBuilder
builder(buf
, sizeof(buf
));
1193 bool ok
= op(converter
, builder
);
1194 MOZ_RELEASE_ASSERT(ok
);
1196 size_t numStrLen
= builder
.position();
1197 const char* numStr
= builder
.Finalize();
1198 MOZ_ASSERT(numStr
== buf
);
1199 MOZ_ASSERT(numStrLen
== strlen(numStr
));
1201 JSString
* str
= NewStringCopyN
<CanGC
>(cx
, numStr
, numStrLen
);
1206 args
.rval().setString(str
);
1210 // ES 2021 draft 21.1.3.3.
1211 static bool num_toFixed(JSContext
* cx
, unsigned argc
, Value
* vp
) {
1212 AutoJSMethodProfilerEntry
pseudoFrame(cx
, "Number.prototype", "toFixed");
1213 CallArgs args
= CallArgsFromVp(argc
, vp
);
1217 if (!ThisNumberValue(cx
, args
, "toFixed", &d
)) {
1223 if (args
.length() == 0) {
1227 if (!ToInteger(cx
, args
[0], &prec
)) {
1231 if (!ComputePrecisionInRange(cx
, 0, MAX_PRECISION
, prec
, &precision
)) {
1237 if (std::isnan(d
)) {
1238 args
.rval().setString(cx
->names().NaN
);
1241 if (std::isinf(d
)) {
1243 args
.rval().setString(cx
->names().Infinity
);
1247 args
.rval().setString(cx
->names().NegativeInfinity
);
1251 // Steps 7-10 for very large numbers.
1252 if (d
<= -1e21
|| d
>= 1e+21) {
1253 JSString
* s
= NumberToString
<CanGC
>(cx
, d
);
1258 args
.rval().setString(s
);
1264 // DoubleToStringConverter::ToFixed is documented as requiring a buffer size
1267 // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint + 1
1268 // (one additional character for the sign, one for the decimal point,
1269 // and one for the null terminator)
1271 // We already ensured there are at most 21 digits before the point, and
1272 // MAX_PRECISION digits after the point.
1273 static_assert(1 + 21 + 1 + MAX_PRECISION
+ 1 <= DoubleToStrResultBufSize
);
1275 // The double-conversion library by default has a kMaxFixedDigitsAfterPoint of
1276 // 60. Assert our modified version supports at least MAX_PRECISION (100).
1277 using DToSConverter
= double_conversion::DoubleToStringConverter
;
1278 static_assert(DToSConverter::kMaxFixedDigitsAfterPoint
>= MAX_PRECISION
);
1280 return DoubleToStrResult(cx
, args
, [&](auto& converter
, auto& builder
) {
1281 return converter
.ToFixed(d
, precision
, &builder
);
1285 // ES 2021 draft 21.1.3.2.
1286 static bool num_toExponential(JSContext
* cx
, unsigned argc
, Value
* vp
) {
1287 AutoJSMethodProfilerEntry
pseudoFrame(cx
, "Number.prototype",
1289 CallArgs args
= CallArgsFromVp(argc
, vp
);
1293 if (!ThisNumberValue(cx
, args
, "toExponential", &d
)) {
1299 if (args
.hasDefined(0)) {
1300 if (!ToInteger(cx
, args
[0], &prec
)) {
1306 MOZ_ASSERT_IF(!args
.hasDefined(0), prec
== 0);
1309 if (std::isnan(d
)) {
1310 args
.rval().setString(cx
->names().NaN
);
1313 if (std::isinf(d
)) {
1315 args
.rval().setString(cx
->names().Infinity
);
1319 args
.rval().setString(cx
->names().NegativeInfinity
);
1325 if (!ComputePrecisionInRange(cx
, 0, MAX_PRECISION
, prec
, &precision
)) {
1331 // DoubleToStringConverter::ToExponential is documented as adding at most 8
1332 // characters on top of the requested digits: "the sign, the digit before the
1333 // decimal point, the decimal point, the exponent character, the exponent's
1334 // sign, and at most 3 exponent digits". In addition, the buffer must be able
1335 // to hold the trailing '\0' character.
1336 static_assert(MAX_PRECISION
+ 8 + 1 <= DoubleToStrResultBufSize
);
1338 return DoubleToStrResult(cx
, args
, [&](auto& converter
, auto& builder
) {
1339 int requestedDigits
= args
.hasDefined(0) ? precision
: -1;
1340 return converter
.ToExponential(d
, requestedDigits
, &builder
);
1344 // ES 2021 draft 21.1.3.5.
1345 static bool num_toPrecision(JSContext
* cx
, unsigned argc
, Value
* vp
) {
1346 AutoJSMethodProfilerEntry
pseudoFrame(cx
, "Number.prototype", "toPrecision");
1347 CallArgs args
= CallArgsFromVp(argc
, vp
);
1351 if (!ThisNumberValue(cx
, args
, "toPrecision", &d
)) {
1356 if (!args
.hasDefined(0)) {
1357 JSString
* str
= NumberToStringWithBase
<CanGC
>(cx
, d
, 10);
1361 args
.rval().setString(str
);
1367 if (!ToInteger(cx
, args
[0], &prec
)) {
1372 if (std::isnan(d
)) {
1373 args
.rval().setString(cx
->names().NaN
);
1376 if (std::isinf(d
)) {
1378 args
.rval().setString(cx
->names().Infinity
);
1382 args
.rval().setString(cx
->names().NegativeInfinity
);
1388 if (!ComputePrecisionInRange(cx
, 1, MAX_PRECISION
, prec
, &precision
)) {
1394 // DoubleToStringConverter::ToPrecision is documented as adding at most 7
1395 // characters on top of the requested digits: "the sign, the decimal point,
1396 // the exponent character, the exponent's sign, and at most 3 exponent
1397 // digits". In addition, the buffer must be able to hold the trailing '\0'
1399 static_assert(MAX_PRECISION
+ 7 + 1 <= DoubleToStrResultBufSize
);
1401 return DoubleToStrResult(cx
, args
, [&](auto& converter
, auto& builder
) {
1402 return converter
.ToPrecision(d
, precision
, &builder
);
1406 static const JSFunctionSpec number_methods
[] = {
1407 JS_FN(js_toSource_str
, num_toSource
, 0, 0),
1408 JS_INLINABLE_FN(js_toString_str
, num_toString
, 1, 0, NumberToString
),
1410 JS_SELF_HOSTED_FN(js_toLocaleString_str
, "Number_toLocaleString", 0, 0),
1412 JS_FN(js_toLocaleString_str
, num_toLocaleString
, 0, 0),
1414 JS_FN(js_valueOf_str
, num_valueOf
, 0, 0),
1415 JS_FN("toFixed", num_toFixed
, 1, 0),
1416 JS_FN("toExponential", num_toExponential
, 1, 0),
1417 JS_FN("toPrecision", num_toPrecision
, 1, 0),
1420 bool js::IsInteger(double d
) {
1421 return std::isfinite(d
) && JS::ToInteger(d
) == d
;
1424 static const JSFunctionSpec number_static_methods
[] = {
1425 JS_SELF_HOSTED_FN("isFinite", "Number_isFinite", 1, 0),
1426 JS_SELF_HOSTED_FN("isInteger", "Number_isInteger", 1, 0),
1427 JS_SELF_HOSTED_FN("isNaN", "Number_isNaN", 1, 0),
1428 JS_SELF_HOSTED_FN("isSafeInteger", "Number_isSafeInteger", 1, 0),
1431 static const JSPropertySpec number_static_properties
[] = {
1432 JS_DOUBLE_PS("POSITIVE_INFINITY", mozilla::PositiveInfinity
<double>(),
1433 JSPROP_READONLY
| JSPROP_PERMANENT
),
1434 JS_DOUBLE_PS("NEGATIVE_INFINITY", mozilla::NegativeInfinity
<double>(),
1435 JSPROP_READONLY
| JSPROP_PERMANENT
),
1436 JS_DOUBLE_PS("MAX_VALUE", 1.7976931348623157E+308,
1437 JSPROP_READONLY
| JSPROP_PERMANENT
),
1438 JS_DOUBLE_PS("MIN_VALUE", MinNumberValue
<double>(),
1439 JSPROP_READONLY
| JSPROP_PERMANENT
),
1440 /* ES6 (April 2014 draft) 20.1.2.6 */
1441 JS_DOUBLE_PS("MAX_SAFE_INTEGER", 9007199254740991,
1442 JSPROP_READONLY
| JSPROP_PERMANENT
),
1443 /* ES6 (April 2014 draft) 20.1.2.10 */
1444 JS_DOUBLE_PS("MIN_SAFE_INTEGER", -9007199254740991,
1445 JSPROP_READONLY
| JSPROP_PERMANENT
),
1446 /* ES6 (May 2013 draft) 15.7.3.7 */
1447 JS_DOUBLE_PS("EPSILON", 2.2204460492503130808472633361816e-16,
1448 JSPROP_READONLY
| JSPROP_PERMANENT
),
1451 bool js::InitRuntimeNumberState(JSRuntime
* rt
) {
1452 // XXX If JS_HAS_INTL_API becomes true all the time at some point,
1453 // js::InitRuntimeNumberState is no longer fallible, and we should
1454 // change its return type.
1455 #if !JS_HAS_INTL_API
1456 /* Copy locale-specific separators into the runtime strings. */
1457 const char* thousandsSeparator
;
1458 const char* decimalPoint
;
1459 const char* grouping
;
1460 # ifdef HAVE_LOCALECONV
1461 struct lconv
* locale
= localeconv();
1462 thousandsSeparator
= locale
->thousands_sep
;
1463 decimalPoint
= locale
->decimal_point
;
1464 grouping
= locale
->grouping
;
1466 thousandsSeparator
= getenv("LOCALE_THOUSANDS_SEP");
1467 decimalPoint
= getenv("LOCALE_DECIMAL_POINT");
1468 grouping
= getenv("LOCALE_GROUPING");
1470 if (!thousandsSeparator
) {
1471 thousandsSeparator
= "'";
1473 if (!decimalPoint
) {
1481 * We use single malloc to get the memory for all separator and grouping
1484 size_t thousandsSeparatorSize
= strlen(thousandsSeparator
) + 1;
1485 size_t decimalPointSize
= strlen(decimalPoint
) + 1;
1486 size_t groupingSize
= strlen(grouping
) + 1;
1488 char* storage
= js_pod_malloc
<char>(thousandsSeparatorSize
+
1489 decimalPointSize
+ groupingSize
);
1494 js_memcpy(storage
, thousandsSeparator
, thousandsSeparatorSize
);
1495 rt
->thousandsSeparator
= storage
;
1496 storage
+= thousandsSeparatorSize
;
1498 js_memcpy(storage
, decimalPoint
, decimalPointSize
);
1499 rt
->decimalSeparator
= storage
;
1500 storage
+= decimalPointSize
;
1502 js_memcpy(storage
, grouping
, groupingSize
);
1503 rt
->numGrouping
= grouping
;
1504 #endif /* !JS_HAS_INTL_API */
1508 void js::FinishRuntimeNumberState(JSRuntime
* rt
) {
1509 #if !JS_HAS_INTL_API
1511 * The free also releases the memory for decimalSeparator and numGrouping
1514 char* storage
= const_cast<char*>(rt
->thousandsSeparator
.ref());
1516 #endif // !JS_HAS_INTL_API
1519 JSObject
* NumberObject::createPrototype(JSContext
* cx
, JSProtoKey key
) {
1520 NumberObject
* numberProto
=
1521 GlobalObject::createBlankPrototype
<NumberObject
>(cx
, cx
->global());
1525 numberProto
->setPrimitiveValue(0);
1529 static bool NumberClassFinish(JSContext
* cx
, HandleObject ctor
,
1530 HandleObject proto
) {
1531 Handle
<GlobalObject
*> global
= cx
->global();
1533 if (!JS_DefineFunctions(cx
, global
, number_functions
)) {
1537 // Number.parseInt should be the same function object as global parseInt.
1538 RootedId
parseIntId(cx
, NameToId(cx
->names().parseInt
));
1539 JSFunction
* parseInt
=
1540 DefineFunction(cx
, global
, parseIntId
, num_parseInt
, 2, JSPROP_RESOLVING
);
1544 parseInt
->setJitInfo(&jit::JitInfo_NumberParseInt
);
1546 RootedValue
parseIntValue(cx
, ObjectValue(*parseInt
));
1547 if (!DefineDataProperty(cx
, ctor
, parseIntId
, parseIntValue
, 0)) {
1551 // Number.parseFloat should be the same function object as global
1553 RootedId
parseFloatId(cx
, NameToId(cx
->names().parseFloat
));
1554 JSFunction
* parseFloat
= DefineFunction(cx
, global
, parseFloatId
,
1555 num_parseFloat
, 1, JSPROP_RESOLVING
);
1559 RootedValue
parseFloatValue(cx
, ObjectValue(*parseFloat
));
1560 if (!DefineDataProperty(cx
, ctor
, parseFloatId
, parseFloatValue
, 0)) {
1564 RootedValue
valueNaN(cx
, JS::NaNValue());
1565 RootedValue
valueInfinity(cx
, JS::InfinityValue());
1567 if (!DefineDataProperty(
1568 cx
, ctor
, cx
->names().NaN
, valueNaN
,
1569 JSPROP_PERMANENT
| JSPROP_READONLY
| JSPROP_RESOLVING
)) {
1573 // ES5 15.1.1.1, 15.1.1.2
1574 if (!NativeDefineDataProperty(
1575 cx
, global
, cx
->names().NaN
, valueNaN
,
1576 JSPROP_PERMANENT
| JSPROP_READONLY
| JSPROP_RESOLVING
) ||
1577 !NativeDefineDataProperty(
1578 cx
, global
, cx
->names().Infinity
, valueInfinity
,
1579 JSPROP_PERMANENT
| JSPROP_READONLY
| JSPROP_RESOLVING
)) {
1586 const ClassSpec
NumberObject::classSpec_
= {
1587 GenericCreateConstructor
<Number
, 1, gc::AllocKind::FUNCTION
,
1588 &jit::JitInfo_Number
>,
1589 NumberObject::createPrototype
,
1590 number_static_methods
,
1591 number_static_properties
,
1596 static char* FracNumberToCString(ToCStringBuf
* cbuf
, double d
, size_t* len
) {
1600 MOZ_ASSERT(!NumberEqualsInt32(d
, &_
));
1605 * This is V8's implementation of the algorithm described in the
1608 * Printing floating-point numbers quickly and accurately with integers.
1609 * Florian Loitsch, PLDI 2010.
1611 const double_conversion::DoubleToStringConverter
& converter
=
1612 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1613 double_conversion::StringBuilder
builder(cbuf
->sbuf
, std::size(cbuf
->sbuf
));
1614 converter
.ToShortest(d
, &builder
);
1616 *len
= builder
.position();
1617 return builder
.Finalize();
1620 void JS::NumberToString(double d
, char (&out
)[MaximumNumberToStringLength
]) {
1622 if (NumberEqualsInt32(d
, &i
)) {
1623 Int32ToCStringBuf cbuf
;
1625 char* loc
= ::Int32ToCString(&cbuf
, i
, &len
);
1626 memmove(out
, loc
, len
);
1629 const double_conversion::DoubleToStringConverter
& converter
=
1630 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1632 double_conversion::StringBuilder
builder(out
, sizeof(out
));
1633 converter
.ToShortest(d
, &builder
);
1639 MOZ_ASSERT(out
== result
);
1643 char* js::NumberToCString(ToCStringBuf
* cbuf
, double d
, size_t* length
) {
1646 char* s
= NumberEqualsInt32(d
, &i
) ? ::Int32ToCString(cbuf
, i
, &len
)
1647 : FracNumberToCString(cbuf
, d
, &len
);
1655 char* js::Int32ToCString(Int32ToCStringBuf
* cbuf
, int32_t value
,
1658 char* s
= ::Int32ToCString(cbuf
, value
, &len
);
1666 char* js::Uint32ToCString(Int32ToCStringBuf
* cbuf
, uint32_t value
,
1669 char* s
= ::Int32ToCString(cbuf
, value
, &len
);
1677 char* js::Uint32ToHexCString(Int32ToCStringBuf
* cbuf
, uint32_t value
,
1680 char* s
= ::Int32ToCString
<uint32_t, 16>(cbuf
, value
, &len
);
1688 template <AllowGC allowGC
>
1689 static JSString
* NumberToStringWithBase(JSContext
* cx
, double d
, int base
) {
1690 MOZ_ASSERT(2 <= base
&& base
<= 36);
1692 Realm
* realm
= cx
->realm();
1695 if (NumberEqualsInt32(d
, &i
)) {
1696 bool isBase10Int
= (base
== 10);
1698 static_assert(StaticStrings::INT_STATIC_LIMIT
> 10 * 10);
1699 if (StaticStrings::hasInt(i
)) {
1700 return cx
->staticStrings().getInt(i
);
1702 } else if (unsigned(i
) < unsigned(base
)) {
1704 return cx
->staticStrings().getInt(i
);
1706 char16_t c
= 'a' + i
- 10;
1707 MOZ_ASSERT(StaticStrings::hasUnit(c
));
1708 return cx
->staticStrings().getUnit(c
);
1709 } else if (unsigned(i
) < unsigned(base
* base
)) {
1710 static constexpr char digits
[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1711 char chars
[] = {digits
[i
/ base
], digits
[i
% base
]};
1712 JSString
* str
= cx
->staticStrings().lookup(chars
, 2);
1717 if (JSLinearString
* str
= realm
->dtoaCache
.lookup(base
, d
)) {
1721 // Plus three to include the largest number, the sign, and the terminating
1723 constexpr size_t MaximumLength
= std::numeric_limits
<int32_t>::digits
+ 3;
1725 char buf
[MaximumLength
] = {};
1727 char* numStr
= Int32ToCStringWithBase(buf
, i
, &numStrLen
, base
);
1728 MOZ_ASSERT(numStrLen
== strlen(numStr
));
1730 JSLinearString
* s
= NewStringCopyN
<allowGC
>(cx
, numStr
, numStrLen
);
1735 if (isBase10Int
&& i
>= 0) {
1736 s
->maybeInitializeIndexValue(i
);
1739 realm
->dtoaCache
.cache(base
, d
, s
);
1743 if (JSLinearString
* str
= realm
->dtoaCache
.lookup(base
, d
)) {
1749 // We use a faster algorithm for base 10.
1752 char* numStr
= FracNumberToCString(&cbuf
, d
, &numStrLen
);
1754 MOZ_ASSERT(numStrLen
== strlen(numStr
));
1756 s
= NewStringCopyN
<allowGC
>(cx
, numStr
, numStrLen
);
1761 if (!EnsureDtoaState(cx
)) {
1762 if constexpr (allowGC
) {
1763 ReportOutOfMemory(cx
);
1768 UniqueChars
numStr(js_dtobasestr(cx
->dtoaState
, base
, d
));
1770 if constexpr (allowGC
) {
1771 ReportOutOfMemory(cx
);
1776 s
= NewStringCopyZ
<allowGC
>(cx
, numStr
.get());
1782 realm
->dtoaCache
.cache(base
, d
, s
);
1786 template <AllowGC allowGC
>
1787 JSString
* js::NumberToString(JSContext
* cx
, double d
) {
1788 return NumberToStringWithBase
<allowGC
>(cx
, d
, 10);
1791 template JSString
* js::NumberToString
<CanGC
>(JSContext
* cx
, double d
);
1793 template JSString
* js::NumberToString
<NoGC
>(JSContext
* cx
, double d
);
1795 JSString
* js::NumberToStringPure(JSContext
* cx
, double d
) {
1796 AutoUnsafeCallWithABI unsafe
;
1797 return NumberToString
<NoGC
>(cx
, d
);
1800 JSAtom
* js::NumberToAtom(JSContext
* cx
, double d
) {
1802 if (NumberEqualsInt32(d
, &si
)) {
1803 return Int32ToAtom(cx
, si
);
1806 if (JSLinearString
* str
= LookupDtoaCache(cx
, d
)) {
1807 return AtomizeString(cx
, str
);
1812 char* numStr
= FracNumberToCString(&cbuf
, d
, &length
);
1814 MOZ_ASSERT(std::begin(cbuf
.sbuf
) <= numStr
&& numStr
< std::end(cbuf
.sbuf
));
1815 MOZ_ASSERT(length
== strlen(numStr
));
1817 JSAtom
* atom
= Atomize(cx
, numStr
, length
);
1822 CacheNumber(cx
, d
, atom
);
1827 frontend::TaggedParserAtomIndex
js::NumberToParserAtom(
1828 FrontendContext
* fc
, frontend::ParserAtomsTable
& parserAtoms
, double d
) {
1830 if (NumberEqualsInt32(d
, &si
)) {
1831 return Int32ToParserAtom(fc
, parserAtoms
, si
);
1836 char* numStr
= FracNumberToCString(&cbuf
, d
, &length
);
1838 MOZ_ASSERT(std::begin(cbuf
.sbuf
) <= numStr
&& numStr
< std::end(cbuf
.sbuf
));
1839 MOZ_ASSERT(length
== strlen(numStr
));
1841 return parserAtoms
.internAscii(fc
, numStr
, length
);
1844 JSLinearString
* js::IndexToString(JSContext
* cx
, uint32_t index
) {
1845 if (StaticStrings::hasUint(index
)) {
1846 return cx
->staticStrings().getUint(index
);
1849 Realm
* realm
= cx
->realm();
1850 if (JSLinearString
* str
= realm
->dtoaCache
.lookup(10, index
)) {
1854 Latin1Char buffer
[JSFatInlineString::MAX_LENGTH_LATIN1
+ 1];
1855 RangedPtr
<Latin1Char
> end(buffer
+ JSFatInlineString::MAX_LENGTH_LATIN1
,
1856 buffer
, JSFatInlineString::MAX_LENGTH_LATIN1
+ 1);
1858 RangedPtr
<Latin1Char
> start
= BackfillIndexInCharBuffer(index
, end
);
1860 mozilla::Range
<const Latin1Char
> chars(start
.get(), end
- start
);
1861 JSInlineString
* str
=
1862 NewInlineString
<CanGC
>(cx
, chars
, js::gc::Heap::Default
);
1867 realm
->dtoaCache
.cache(10, index
, str
);
1871 JSString
* js::Int32ToStringWithBase(JSContext
* cx
, int32_t i
, int32_t base
) {
1872 return NumberToStringWithBase
<CanGC
>(cx
, double(i
), base
);
1875 bool js::NumberValueToStringBuffer(const Value
& v
, StringBuffer
& sb
) {
1876 /* Convert to C-string. */
1881 cstr
= ::Int32ToCString(&cbuf
, v
.toInt32(), &cstrlen
);
1883 cstr
= NumberToCString(&cbuf
, v
.toDouble(), &cstrlen
);
1886 MOZ_ASSERT(cstrlen
== strlen(cstr
));
1888 MOZ_ASSERT(cstrlen
< std::size(cbuf
.sbuf
));
1889 return sb
.append(cstr
, cstrlen
);
1892 template <typename CharT
>
1893 inline double CharToNumber(CharT c
) {
1894 if ('0' <= c
&& c
<= '9') {
1897 if (unicode::IsSpace(c
)) {
1900 return GenericNaN();
1903 template <typename CharT
>
1904 inline bool CharsToNonDecimalNumber(const CharT
* start
, const CharT
* end
,
1906 MOZ_ASSERT(end
- start
>= 2);
1907 MOZ_ASSERT(start
[0] == '0');
1910 if (start
[1] == 'b' || start
[1] == 'B') {
1912 } else if (start
[1] == 'o' || start
[1] == 'O') {
1914 } else if (start
[1] == 'x' || start
[1] == 'X') {
1920 // It's probably a non-decimal number. Accept if there's at least one digit
1921 // after the 0b|0o|0x, and if no non-whitespace characters follow all the
1923 const CharT
* endptr
;
1925 MOZ_ALWAYS_TRUE(GetPrefixIntegerImpl(
1926 start
+ 2, end
, radix
, IntegerSeparatorHandling::None
, &endptr
, &d
));
1927 if (endptr
== start
+ 2 || SkipSpace(endptr
, end
) != end
) {
1928 *result
= GenericNaN();
1935 template <typename CharT
>
1936 double js::CharsToNumber(const CharT
* chars
, size_t length
) {
1938 return CharToNumber(chars
[0]);
1941 const CharT
* end
= chars
+ length
;
1942 const CharT
* start
= SkipSpace(chars
, end
);
1944 // ECMA doesn't allow signed non-decimal numbers (bug 273467).
1945 if (end
- start
>= 2 && start
[0] == '0') {
1947 if (CharsToNonDecimalNumber(start
, end
, &d
)) {
1953 * Note that ECMA doesn't treat a string beginning with a '0' as
1954 * an octal number here. This works because all such numbers will
1955 * be interpreted as decimal by js_strtod. Also, any hex numbers
1956 * that have made it here (which can only be negative ones) will
1957 * be treated as 0 without consuming the 'x' by js_strtod.
1960 double d
= js_strtod(start
, end
, &ep
);
1961 if (SkipSpace(ep
, end
) != end
) {
1962 return GenericNaN();
1967 template double js::CharsToNumber(const Latin1Char
* chars
, size_t length
);
1969 template double js::CharsToNumber(const char16_t
* chars
, size_t length
);
1971 double js::LinearStringToNumber(JSLinearString
* str
) {
1972 if (str
->hasIndexValue()) {
1973 return str
->getIndexValue();
1976 AutoCheckCannotGC nogc
;
1977 return str
->hasLatin1Chars()
1978 ? CharsToNumber(str
->latin1Chars(nogc
), str
->length())
1979 : CharsToNumber(str
->twoByteChars(nogc
), str
->length());
1982 bool js::StringToNumber(JSContext
* cx
, JSString
* str
, double* result
) {
1983 JSLinearString
* linearStr
= str
->ensureLinear(cx
);
1988 *result
= LinearStringToNumber(linearStr
);
1992 bool js::StringToNumberPure(JSContext
* cx
, JSString
* str
, double* result
) {
1993 // IC Code calls this directly.
1994 AutoUnsafeCallWithABI unsafe
;
1996 if (!StringToNumber(cx
, str
, result
)) {
1997 cx
->recoverFromOutOfMemory();
2003 JS_PUBLIC_API
bool js::ToNumberSlow(JSContext
* cx
, HandleValue v_
,
2005 RootedValue
v(cx
, v_
);
2006 MOZ_ASSERT(!v
.isNumber());
2008 if (!v
.isPrimitive()) {
2009 if (!ToPrimitive(cx
, JSTYPE_NUMBER
, &v
)) {
2014 *out
= v
.toNumber();
2019 return StringToNumber(cx
, v
.toString(), out
);
2021 if (v
.isBoolean()) {
2022 *out
= v
.toBoolean() ? 1.0 : 0.0;
2029 if (v
.isUndefined()) {
2030 *out
= GenericNaN();
2033 #ifdef ENABLE_RECORD_TUPLE
2034 if (v
.isExtendedPrimitive()) {
2035 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr,
2036 JSMSG_RECORD_TUPLE_TO_NUMBER
);
2041 MOZ_ASSERT(v
.isSymbol() || v
.isBigInt());
2042 unsigned errnum
= JSMSG_SYMBOL_TO_NUMBER
;
2044 errnum
= JSMSG_BIGINT_TO_NUMBER
;
2046 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, errnum
);
2050 // BigInt proposal section 3.1.6
2051 bool js::ToNumericSlow(JSContext
* cx
, MutableHandleValue vp
) {
2052 MOZ_ASSERT(!vp
.isNumeric());
2055 if (!vp
.isPrimitive()) {
2056 if (!ToPrimitive(cx
, JSTYPE_NUMBER
, vp
)) {
2062 if (vp
.isBigInt()) {
2067 return ToNumber(cx
, vp
);
2071 * Convert a value to an int8_t, according to the WebIDL rules for byte
2072 * conversion. Return converted value in *out on success, false on failure.
2074 JS_PUBLIC_API
bool js::ToInt8Slow(JSContext
* cx
, const HandleValue v
,
2076 MOZ_ASSERT(!v
.isInt32());
2081 if (!ToNumberSlow(cx
, v
, &d
)) {
2090 * Convert a value to an uint8_t, according to the ToUInt8() function in ES6
2091 * ECMA-262, 7.1.10. Return converted value in *out on success, false on
2094 JS_PUBLIC_API
bool js::ToUint8Slow(JSContext
* cx
, const HandleValue v
,
2096 MOZ_ASSERT(!v
.isInt32());
2101 if (!ToNumberSlow(cx
, v
, &d
)) {
2110 * Convert a value to an int16_t, according to the WebIDL rules for short
2111 * conversion. Return converted value in *out on success, false on failure.
2113 JS_PUBLIC_API
bool js::ToInt16Slow(JSContext
* cx
, const HandleValue v
,
2115 MOZ_ASSERT(!v
.isInt32());
2120 if (!ToNumberSlow(cx
, v
, &d
)) {
2129 * Convert a value to an int64_t, according to the WebIDL rules for long long
2130 * conversion. Return converted value in *out on success, false on failure.
2132 JS_PUBLIC_API
bool js::ToInt64Slow(JSContext
* cx
, const HandleValue v
,
2134 MOZ_ASSERT(!v
.isInt32());
2139 if (!ToNumberSlow(cx
, v
, &d
)) {
2148 * Convert a value to an uint64_t, according to the WebIDL rules for unsigned
2149 * long long conversion. Return converted value in *out on success, false on
2152 JS_PUBLIC_API
bool js::ToUint64Slow(JSContext
* cx
, const HandleValue v
,
2154 MOZ_ASSERT(!v
.isInt32());
2159 if (!ToNumberSlow(cx
, v
, &d
)) {
2167 JS_PUBLIC_API
bool js::ToInt32Slow(JSContext
* cx
, const HandleValue v
,
2169 MOZ_ASSERT(!v
.isInt32());
2174 if (!ToNumberSlow(cx
, v
, &d
)) {
2182 bool js::ToInt32OrBigIntSlow(JSContext
* cx
, MutableHandleValue vp
) {
2183 MOZ_ASSERT(!vp
.isInt32());
2184 if (vp
.isDouble()) {
2185 vp
.setInt32(ToInt32(vp
.toDouble()));
2189 if (!ToNumeric(cx
, vp
)) {
2193 if (vp
.isBigInt()) {
2197 vp
.setInt32(ToInt32(vp
.toNumber()));
2201 JS_PUBLIC_API
bool js::ToUint32Slow(JSContext
* cx
, const HandleValue v
,
2203 MOZ_ASSERT(!v
.isInt32());
2208 if (!ToNumberSlow(cx
, v
, &d
)) {
2216 JS_PUBLIC_API
bool js::ToUint16Slow(JSContext
* cx
, const HandleValue v
,
2218 MOZ_ASSERT(!v
.isInt32());
2222 } else if (!ToNumberSlow(cx
, v
, &d
)) {
2229 // ES2017 draft 7.1.17 ToIndex
2230 bool js::ToIndexSlow(JSContext
* cx
, JS::HandleValue v
,
2231 const unsigned errorNumber
, uint64_t* index
) {
2232 MOZ_ASSERT_IF(v
.isInt32(), v
.toInt32() < 0);
2235 if (v
.isUndefined()) {
2241 double integerIndex
;
2242 if (!ToInteger(cx
, v
, &integerIndex
)) {
2246 // Inlined version of ToLength.
2247 // 1. Already an integer.
2248 // 2. Step eliminates < 0, +0 == -0 with SameValueZero.
2249 // 3/4. Limit to <= 2^53-1, so everything above should fail.
2250 if (integerIndex
< 0 || integerIndex
>= DOUBLE_INTEGRAL_PRECISION_LIMIT
) {
2251 JS_ReportErrorNumberASCII(cx
, GetErrorMessage
, nullptr, errorNumber
);
2256 *index
= uint64_t(integerIndex
);
2260 template <typename CharT
>
2261 double js_strtod(const CharT
* begin
, const CharT
* end
, const CharT
** dEnd
) {
2262 const CharT
* s
= SkipSpace(begin
, end
);
2263 size_t length
= end
- s
;
2266 // StringToDouble can make indirect calls but can't trigger a GC.
2267 JS::AutoSuppressGCAnalysis nogc
;
2269 using SToDConverter
= double_conversion::StringToDoubleConverter
;
2270 SToDConverter
converter(SToDConverter::ALLOW_TRAILING_JUNK
,
2271 /* empty_string_value = */ 0.0,
2272 /* junk_string_value = */ GenericNaN(),
2273 /* infinity_symbol = */ nullptr,
2274 /* nan_symbol = */ nullptr);
2275 int lengthInt
= mozilla::AssertedCast
<int>(length
);
2278 if constexpr (std::is_same_v
<CharT
, char16_t
>) {
2279 d
= converter
.StringToDouble(reinterpret_cast<const uc16
*>(s
), lengthInt
,
2282 static_assert(std::is_same_v
<CharT
, Latin1Char
>);
2283 d
= converter
.StringToDouble(reinterpret_cast<const char*>(s
), lengthInt
,
2286 MOZ_ASSERT(processed
>= 0);
2287 MOZ_ASSERT(processed
<= lengthInt
);
2289 if (processed
> 0) {
2290 *dEnd
= s
+ processed
;
2295 // Try to parse +Infinity, -Infinity or Infinity. Note that we do this here
2296 // instead of using StringToDoubleConverter's infinity_symbol because it's
2297 // faster: the code below is less generic and not on the fast path for regular
2299 static constexpr std::string_view Infinity
= "Infinity";
2300 if (length
>= Infinity
.length()) {
2301 const CharT
* afterSign
= s
;
2302 bool negative
= (*afterSign
== '-');
2303 if (negative
|| *afterSign
== '+') {
2306 MOZ_ASSERT(afterSign
< end
);
2307 if (*afterSign
== 'I' && size_t(end
- afterSign
) >= Infinity
.length() &&
2308 EqualChars(afterSign
, Infinity
.data(), Infinity
.length())) {
2309 *dEnd
= afterSign
+ Infinity
.length();
2310 return negative
? NegativeInfinity
<double>() : PositiveInfinity
<double>();
2318 template double js_strtod(const char16_t
* begin
, const char16_t
* end
,
2319 const char16_t
** dEnd
);
2321 template double js_strtod(const Latin1Char
* begin
, const Latin1Char
* end
,
2322 const Latin1Char
** dEnd
);