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/. */
10 #include "mozilla/FloatingPoint.h"
11 #include "mozilla/Range.h"
12 #include "mozilla/Utf8.h"
16 #include "NamespaceImports.h"
18 #include "js/Conversions.h"
19 #include "js/friend/ErrorMessages.h" // JSMSG_*
21 #include "vm/StringType.h"
26 class ParserAtomsTable
;
27 class TaggedParserAtomIndex
;
28 } // namespace frontend
33 [[nodiscard
]] extern bool InitRuntimeNumberState(JSRuntime
* rt
);
35 // This is a no-op if built with JS_HAS_INTL_API.
36 extern void FinishRuntimeNumberState(JSRuntime
* rt
);
39 * This function implements ToString() as specified by ECMA-262-5 section 9.8.1;
40 * but note that it handles integers specially for performance.
41 * See also js::NumberToCString().
43 template <AllowGC allowGC
>
44 extern JSString
* NumberToString(JSContext
* cx
, double d
);
46 extern JSString
* NumberToStringPure(JSContext
* cx
, double d
);
48 extern JSAtom
* NumberToAtom(JSContext
* cx
, double d
);
50 frontend::TaggedParserAtomIndex
NumberToParserAtom(
51 FrontendContext
* fc
, frontend::ParserAtomsTable
& parserAtoms
, double d
);
53 template <AllowGC allowGC
>
54 extern JSLinearString
* Int32ToString(JSContext
* cx
, int32_t i
);
56 extern JSLinearString
* Int32ToStringPure(JSContext
* cx
, int32_t i
);
58 extern JSString
* Int32ToStringWithBase(JSContext
* cx
, int32_t i
, int32_t base
);
60 extern JSAtom
* Int32ToAtom(JSContext
* cx
, int32_t si
);
62 frontend::TaggedParserAtomIndex
Int32ToParserAtom(
63 FrontendContext
* fc
, frontend::ParserAtomsTable
& parserAtoms
, int32_t si
);
66 extern bool IsInteger(double d
);
69 * Convert an integer or double (contained in the given value) to a string and
70 * append to the given buffer.
72 [[nodiscard
]] extern bool NumberValueToStringBuffer(const Value
& v
,
75 extern JSLinearString
* IndexToString(JSContext
* cx
, uint32_t index
);
78 char sbuf
[JS::MaximumNumberToStringLength
] = {};
81 struct Int32ToCStringBuf
{
82 // The amount of space large enough to store the null-terminated result of
83 // |ToString| on any int32.
85 // We use the same amount for uint32 (base 10 and base 16), even though uint32
86 // only need 11 characters (base 10) resp. 9 characters (base 16) instead of
87 // 12 characters for int32 in base 10.
88 static constexpr size_t MaximumInt32ToStringLength
=
89 std::numeric_limits
<int32_t>::digits10
+
90 1 + // account for the largest possible int32 value
91 1 + // sign for negative numbers
95 char sbuf
[MaximumInt32ToStringLength
] = {};
98 // Convert a number to a C string. This function implements ToString() as
99 // specified by ECMA-262-5 section 9.8.1. It handles integral values cheaply.
100 // Infallible: always returns a non-nullptr string.
101 // The optional `length` out-param is set to the string length of the result.
102 extern char* NumberToCString(ToCStringBuf
* cbuf
, double d
,
103 size_t* length
= nullptr);
105 extern char* Int32ToCString(Int32ToCStringBuf
* cbuf
, int32_t value
,
106 size_t* length
= nullptr);
108 extern char* Uint32ToCString(Int32ToCStringBuf
* cbuf
, uint32_t value
,
109 size_t* length
= nullptr);
111 // Like NumberToCString, but accepts only unsigned integers and uses base 16.
112 // Infallible: always returns a non-nullptr string.
113 // The optional `length` out-param is set to the string length of the result.
114 extern char* Uint32ToHexCString(Int32ToCStringBuf
* cbuf
, uint32_t value
,
115 size_t* length
= nullptr);
118 * The largest positive integer such that all positive integers less than it
119 * may be precisely represented using the IEEE-754 double-precision format.
121 constexpr double DOUBLE_INTEGRAL_PRECISION_LIMIT
= uint64_t(1) << 53;
124 * The smallest positive double such that all positive doubles larger or equal
125 * than it have an exact decimal representation without exponential form.
127 constexpr double DOUBLE_DECIMAL_IN_SHORTEST_LOW
= 1.0e-6;
130 * The largest positive double such that all positive doubles less than it
131 * have an exact decimal representation without exponential form.
133 constexpr double DOUBLE_DECIMAL_IN_SHORTEST_HIGH
= 1.0e21
;
136 * Parse a decimal number encoded in |chars|. The decimal number must be
137 * sufficiently small that it will not overflow the integrally-precise range of
138 * the double type -- that is, the number will be smaller than
139 * DOUBLE_INTEGRAL_PRECISION_LIMIT
141 template <typename CharT
>
142 extern double ParseDecimalNumber(const mozilla::Range
<const CharT
> chars
);
144 enum class IntegerSeparatorHandling
: bool { None
, SkipUnderscore
};
147 * Compute the positive integer of the given base described immediately at the
148 * start of the range [start, end) -- no whitespace-skipping, no magical
149 * leading-"0" octal or leading-"0x" hex behavior, no "+"/"-" parsing, just
150 * reading the digits of the integer. Return the index one past the end of the
151 * digits of the integer in *endp, and return the integer itself in *dp. If
152 * base is 10 or a power of two the returned integer is the closest possible
153 * double; otherwise extremely large integers may be slightly inaccurate.
155 * The |separatorHandling| controls whether or not numeric separators can be
156 * part of integer string. If the option is enabled, all '_' characters in the
157 * string are ignored. Underscore characters must not appear directly next to
158 * each other, e.g. '1__2' will lead to an assertion.
160 * If [start, end) does not begin with a number with the specified base,
161 * *dp == 0 and *endp == start upon return.
163 template <typename CharT
>
164 [[nodiscard
]] extern bool GetPrefixInteger(
165 const CharT
* start
, const CharT
* end
, int base
,
166 IntegerSeparatorHandling separatorHandling
, const CharT
** endp
, double* dp
);
168 inline const char16_t
* ToRawChars(const char16_t
* units
) { return units
; }
170 inline const unsigned char* ToRawChars(const unsigned char* units
) {
174 inline const unsigned char* ToRawChars(const mozilla::Utf8Unit
* units
) {
175 return mozilla::Utf8AsUnsignedChars(units
);
179 * Like GetPrefixInteger, but [start, end) must all be digits in the given
180 * base (and so this function doesn't take a useless outparam).
182 template <typename CharT
>
183 [[nodiscard
]] extern bool GetFullInteger(
184 const CharT
* start
, const CharT
* end
, int base
,
185 IntegerSeparatorHandling separatorHandling
, double* dp
) {
186 decltype(ToRawChars(start
)) realEnd
;
187 if (GetPrefixInteger(ToRawChars(start
), ToRawChars(end
), base
,
188 separatorHandling
, &realEnd
, dp
)) {
189 MOZ_ASSERT(end
== static_cast<const void*>(realEnd
));
196 * This is like GetPrefixInteger, but only deals with base 10, always ignores
197 * '_', and doesn't have an |endp| outparam. It should only be used when the
198 * characters are known to match |DecimalIntegerLiteral|, cf. ES2020, 11.8.3
201 template <typename CharT
>
202 [[nodiscard
]] extern bool GetDecimalInteger(const CharT
* start
,
203 const CharT
* end
, double* dp
);
206 * This is like GetDecimalInteger, but also allows non-integer numbers. It
207 * should only be used when the characters are known to match |DecimalLiteral|,
208 * cf. ES2020, 11.8.3 Numeric Literals.
210 template <typename CharT
>
211 [[nodiscard
]] extern bool GetDecimal(const CharT
* start
, const CharT
* end
,
214 template <typename CharT
>
215 double CharsToNumber(const CharT
* chars
, size_t length
);
217 [[nodiscard
]] extern bool StringToNumber(JSContext
* cx
, JSString
* str
,
220 [[nodiscard
]] extern bool StringToNumberPure(JSContext
* cx
, JSString
* str
,
223 // Infallible version of StringToNumber for linear strings.
224 extern double LinearStringToNumber(JSLinearString
* str
);
226 // Parse the input string as if Number.parseInt had been called.
227 extern bool NumberParseInt(JSContext
* cx
, JS::HandleString str
, int32_t radix
,
228 JS::MutableHandleValue result
);
230 /* ES5 9.3 ToNumber, overwriting *vp with the appropriate number value. */
231 [[nodiscard
]] MOZ_ALWAYS_INLINE
bool ToNumber(JSContext
* cx
,
232 JS::MutableHandleValue vp
) {
237 extern JS_PUBLIC_API
bool ToNumberSlow(JSContext
* cx
, HandleValue v
,
239 if (!ToNumberSlow(cx
, vp
, &d
)) {
247 bool ToNumericSlow(JSContext
* cx
, JS::MutableHandleValue vp
);
249 // BigInt proposal section 3.1.6
250 [[nodiscard
]] MOZ_ALWAYS_INLINE
bool ToNumeric(JSContext
* cx
,
251 JS::MutableHandleValue vp
) {
252 if (vp
.isNumeric()) {
255 return ToNumericSlow(cx
, vp
);
258 bool ToInt32OrBigIntSlow(JSContext
* cx
, JS::MutableHandleValue vp
);
260 [[nodiscard
]] MOZ_ALWAYS_INLINE
bool ToInt32OrBigInt(
261 JSContext
* cx
, JS::MutableHandleValue vp
) {
265 return ToInt32OrBigIntSlow(cx
, vp
);
271 * Similar to strtod except that it replaces overflows with infinities of the
272 * correct sign, and underflows with zeros of the correct sign. Guaranteed to
273 * return the closest double number to the given input.
275 * Also allows inputs of the form [+|-]Infinity, which produce an infinity of
276 * the appropriate sign. The case of the "Infinity" string must match exactly.
277 * If the string does not contain a number, set *dEnd to begin and return 0.0.
279 template <typename CharT
>
280 [[nodiscard
]] extern double js_strtod(const CharT
* begin
, const CharT
* end
,
286 * Like js_strtod, but for when the number always constitutes the entire range
287 * (and so |dEnd| would be a value already known).
289 template <typename CharT
>
290 [[nodiscard
]] extern double FullStringToDouble(const CharT
* begin
,
292 decltype(ToRawChars(begin
)) realEnd
;
293 double d
= js_strtod(ToRawChars(begin
), ToRawChars(end
), &realEnd
);
294 MOZ_ASSERT(end
== static_cast<const void*>(realEnd
));
298 [[nodiscard
]] extern bool ThisNumberValueForToLocaleString(JSContext
* cx
,
302 [[nodiscard
]] extern bool num_valueOf(JSContext
* cx
, unsigned argc
, Value
* vp
);
305 * Returns true if the given value is definitely an index: that is, the value
306 * is a number that's an unsigned 32-bit integer.
308 * This method prioritizes common-case speed over accuracy in every case. It
309 * can produce false negatives (but not false positives): some values which are
310 * indexes will be reported not to be indexes by this method. Users must
311 * consider this possibility when using this method.
313 static MOZ_ALWAYS_INLINE
bool IsDefinitelyIndex(const Value
& v
,
315 if (v
.isInt32() && v
.toInt32() >= 0) {
316 *indexp
= v
.toInt32();
321 if (v
.isDouble() && mozilla::NumberEqualsInt32(v
.toDouble(), &i
) && i
>= 0) {
322 *indexp
= uint32_t(i
);
326 if (v
.isString() && v
.toString()->hasIndexValue()) {
327 *indexp
= v
.toString()->getIndexValue();
334 // ES2020 draft rev 6b05bc56ba4e3c7a2b9922c4282d9eb844426d9b
335 // 7.1.5 ToInteger ( argument )
336 [[nodiscard
]] static inline bool ToInteger(JSContext
* cx
, HandleValue v
,
344 } else if (v
.isString() && v
.toString()->hasIndexValue()) {
345 *dp
= v
.toString()->getIndexValue();
348 extern JS_PUBLIC_API
bool ToNumberSlow(JSContext
* cx
, HandleValue v
,
350 if (!ToNumberSlow(cx
, v
, dp
)) {
354 *dp
= JS::ToInteger(*dp
);
358 /* ES2017 draft 7.1.17 ToIndex
360 * Return true and set |*index| to the integer value if |v| is a valid
361 * integer index value. Otherwise report a RangeError and return false.
363 * The returned index will always be in the range 0 <= *index <= 2^53-1.
365 [[nodiscard
]] extern bool ToIndexSlow(JSContext
* cx
, JS::HandleValue v
,
366 const unsigned errorNumber
,
369 [[nodiscard
]] static inline bool ToIndex(JSContext
* cx
, JS::HandleValue v
,
370 const unsigned errorNumber
,
373 int32_t i
= v
.toInt32();
375 *index
= uint64_t(i
);
379 return ToIndexSlow(cx
, v
, errorNumber
, index
);
382 [[nodiscard
]] static inline bool ToIndex(JSContext
* cx
, JS::HandleValue v
,
384 return ToIndex(cx
, v
, JSMSG_BAD_INDEX
, index
);