Bug 1733869 [wpt PR 30916] - Add a note about counterintuitive send_keys() code point...
[gecko.git] / js / public / Conversions.h
blob6c0ca7601e4b6a2dde012a4604bf6dd23fa21cbc
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/. */
7 /* ECMAScript conversion operations. */
9 #ifndef js_Conversions_h
10 #define js_Conversions_h
12 #include "mozilla/Casting.h"
13 #include "mozilla/Compiler.h"
14 #include "mozilla/FloatingPoint.h"
15 #include "mozilla/MathAlgorithms.h"
16 #include "mozilla/WrappingOperations.h"
18 #include <cmath>
19 #include <stddef.h> // size_t
20 #include <stdint.h> // {u,}int{8,16,32,64}_t
21 #include <type_traits>
23 #include "jspubtd.h"
24 #include "jstypes.h" // JS_PUBLIC_API
26 #include "js/RootingAPI.h"
27 #include "js/Value.h"
29 namespace js {
31 /* DO NOT CALL THIS. Use JS::ToBoolean. */
32 extern JS_PUBLIC_API bool ToBooleanSlow(JS::HandleValue v);
34 /* DO NOT CALL THIS. Use JS::ToNumber. */
35 extern JS_PUBLIC_API bool ToNumberSlow(JSContext* cx, JS::HandleValue v,
36 double* dp);
38 /* DO NOT CALL THIS. Use JS::ToInt8. */
39 extern JS_PUBLIC_API bool ToInt8Slow(JSContext* cx, JS::HandleValue v,
40 int8_t* out);
42 /* DO NOT CALL THIS. Use JS::ToUint8. */
43 extern JS_PUBLIC_API bool ToUint8Slow(JSContext* cx, JS::HandleValue v,
44 uint8_t* out);
46 /* DO NOT CALL THIS. Use JS::ToInt16. */
47 extern JS_PUBLIC_API bool ToInt16Slow(JSContext* cx, JS::HandleValue v,
48 int16_t* out);
50 /* DO NOT CALL THIS. Use JS::ToInt32. */
51 extern JS_PUBLIC_API bool ToInt32Slow(JSContext* cx, JS::HandleValue v,
52 int32_t* out);
54 /* DO NOT CALL THIS. Use JS::ToUint32. */
55 extern JS_PUBLIC_API bool ToUint32Slow(JSContext* cx, JS::HandleValue v,
56 uint32_t* out);
58 /* DO NOT CALL THIS. Use JS::ToUint16. */
59 extern JS_PUBLIC_API bool ToUint16Slow(JSContext* cx, JS::HandleValue v,
60 uint16_t* out);
62 /* DO NOT CALL THIS. Use JS::ToInt64. */
63 extern JS_PUBLIC_API bool ToInt64Slow(JSContext* cx, JS::HandleValue v,
64 int64_t* out);
66 /* DO NOT CALL THIS. Use JS::ToUint64. */
67 extern JS_PUBLIC_API bool ToUint64Slow(JSContext* cx, JS::HandleValue v,
68 uint64_t* out);
70 /* DO NOT CALL THIS. Use JS::ToString. */
71 extern JS_PUBLIC_API JSString* ToStringSlow(JSContext* cx, JS::HandleValue v);
73 /* DO NOT CALL THIS. Use JS::ToObject. */
74 extern JS_PUBLIC_API JSObject* ToObjectSlow(JSContext* cx, JS::HandleValue v,
75 bool reportScanStack);
77 } // namespace js
79 namespace JS {
81 namespace detail {
83 #ifdef JS_DEBUG
84 /**
85 * Assert that we're not doing GC on cx, that we're in a request as
86 * needed, and that the compartments for cx and v are correct.
87 * Also check that GC would be safe at this point.
89 extern JS_PUBLIC_API void AssertArgumentsAreSane(JSContext* cx, HandleValue v);
90 #else
91 inline void AssertArgumentsAreSane(JSContext* cx, HandleValue v) {}
92 #endif /* JS_DEBUG */
94 } // namespace detail
96 /**
97 * ES6 draft 20141224, 7.1.1, second algorithm.
99 * Most users shouldn't call this -- use JS::ToBoolean, ToNumber, or ToString
100 * instead. This will typically only be called from custom convert hooks that
101 * wish to fall back to the ES6 default conversion behavior shared by most
102 * objects in JS, codified as OrdinaryToPrimitive.
104 extern JS_PUBLIC_API bool OrdinaryToPrimitive(JSContext* cx, HandleObject obj,
105 JSType type,
106 MutableHandleValue vp);
108 /* ES6 draft 20141224, 7.1.2. */
109 MOZ_ALWAYS_INLINE bool ToBoolean(HandleValue v) {
110 if (v.isBoolean()) {
111 return v.toBoolean();
113 if (v.isInt32()) {
114 return v.toInt32() != 0;
116 if (v.isNullOrUndefined()) {
117 return false;
119 if (v.isDouble()) {
120 double d = v.toDouble();
121 return !mozilla::IsNaN(d) && d != 0;
123 if (v.isSymbol()) {
124 return true;
127 /* The slow path handles strings, BigInts and objects. */
128 return js::ToBooleanSlow(v);
131 /* ES6 draft 20141224, 7.1.3. */
132 MOZ_ALWAYS_INLINE bool ToNumber(JSContext* cx, HandleValue v, double* out) {
133 detail::AssertArgumentsAreSane(cx, v);
135 if (v.isNumber()) {
136 *out = v.toNumber();
137 return true;
139 return js::ToNumberSlow(cx, v, out);
142 // ES2020 draft rev 6b05bc56ba4e3c7a2b9922c4282d9eb844426d9b
143 // 7.1.5 ToInteger ( argument )
145 // Specialized for double values.
146 inline double ToInteger(double d) {
147 if (d == 0) {
148 return 0;
151 if (!mozilla::IsFinite(d)) {
152 if (mozilla::IsNaN(d)) {
153 return 0;
155 return d;
158 return std::trunc(d) + (+0.0); // Add zero to convert -0 to +0.
161 /* ES6 draft 20141224, 7.1.5. */
162 MOZ_ALWAYS_INLINE bool ToInt32(JSContext* cx, JS::HandleValue v, int32_t* out) {
163 detail::AssertArgumentsAreSane(cx, v);
165 if (v.isInt32()) {
166 *out = v.toInt32();
167 return true;
169 return js::ToInt32Slow(cx, v, out);
172 /* ES6 draft 20141224, 7.1.6. */
173 MOZ_ALWAYS_INLINE bool ToUint32(JSContext* cx, HandleValue v, uint32_t* out) {
174 detail::AssertArgumentsAreSane(cx, v);
176 if (v.isInt32()) {
177 *out = uint32_t(v.toInt32());
178 return true;
180 return js::ToUint32Slow(cx, v, out);
183 /* ES6 draft 20141224, 7.1.7. */
184 MOZ_ALWAYS_INLINE bool ToInt16(JSContext* cx, JS::HandleValue v, int16_t* out) {
185 detail::AssertArgumentsAreSane(cx, v);
187 if (v.isInt32()) {
188 *out = int16_t(v.toInt32());
189 return true;
191 return js::ToInt16Slow(cx, v, out);
194 /* ES6 draft 20141224, 7.1.8. */
195 MOZ_ALWAYS_INLINE bool ToUint16(JSContext* cx, HandleValue v, uint16_t* out) {
196 detail::AssertArgumentsAreSane(cx, v);
198 if (v.isInt32()) {
199 *out = uint16_t(v.toInt32());
200 return true;
202 return js::ToUint16Slow(cx, v, out);
205 /* ES6 draft 20141224, 7.1.9 */
206 MOZ_ALWAYS_INLINE bool ToInt8(JSContext* cx, JS::HandleValue v, int8_t* out) {
207 detail::AssertArgumentsAreSane(cx, v);
209 if (v.isInt32()) {
210 *out = int8_t(v.toInt32());
211 return true;
213 return js::ToInt8Slow(cx, v, out);
216 /* ES6 ECMA-262, 7.1.10 */
217 MOZ_ALWAYS_INLINE bool ToUint8(JSContext* cx, JS::HandleValue v, uint8_t* out) {
218 detail::AssertArgumentsAreSane(cx, v);
220 if (v.isInt32()) {
221 *out = uint8_t(v.toInt32());
222 return true;
224 return js::ToUint8Slow(cx, v, out);
228 * Non-standard, with behavior similar to that of ToInt32, except in its
229 * producing an int64_t.
231 MOZ_ALWAYS_INLINE bool ToInt64(JSContext* cx, HandleValue v, int64_t* out) {
232 detail::AssertArgumentsAreSane(cx, v);
234 if (v.isInt32()) {
235 *out = int64_t(v.toInt32());
236 return true;
238 return js::ToInt64Slow(cx, v, out);
242 * Non-standard, with behavior similar to that of ToUint32, except in its
243 * producing a uint64_t.
245 MOZ_ALWAYS_INLINE bool ToUint64(JSContext* cx, HandleValue v, uint64_t* out) {
246 detail::AssertArgumentsAreSane(cx, v);
248 if (v.isInt32()) {
249 *out = uint64_t(v.toInt32());
250 return true;
252 return js::ToUint64Slow(cx, v, out);
255 /* ES6 draft 20141224, 7.1.12. */
256 MOZ_ALWAYS_INLINE JSString* ToString(JSContext* cx, HandleValue v) {
257 detail::AssertArgumentsAreSane(cx, v);
259 if (v.isString()) {
260 return v.toString();
262 return js::ToStringSlow(cx, v);
265 /* ES6 draft 20141224, 7.1.13. */
266 inline JSObject* ToObject(JSContext* cx, HandleValue v) {
267 detail::AssertArgumentsAreSane(cx, v);
269 if (v.isObject()) {
270 return &v.toObject();
272 return js::ToObjectSlow(cx, v, false);
276 * Convert a double value to UnsignedInteger (an unsigned integral type) using
277 * ECMAScript-style semantics (that is, in like manner to how ECMAScript's
278 * ToInt32 converts to int32_t).
280 * If d is infinite or NaN, return 0.
281 * Otherwise compute d2 = sign(d) * floor(abs(d)), and return the
282 * UnsignedInteger value congruent to d2 % 2**(bit width of UnsignedInteger).
284 * The algorithm below is inspired by that found in
285 * <https://trac.webkit.org/changeset/67825/webkit/trunk/JavaScriptCore/runtime/JSValue.cpp>
286 * but has been generalized to all integer widths.
288 template <typename UnsignedInteger>
289 inline UnsignedInteger ToUnsignedInteger(double d) {
290 static_assert(std::is_unsigned_v<UnsignedInteger>,
291 "UnsignedInteger must be an unsigned type");
293 uint64_t bits = mozilla::BitwiseCast<uint64_t>(d);
294 unsigned DoubleExponentShift = mozilla::FloatingPoint<double>::kExponentShift;
296 // Extract the exponent component. (Be careful here! It's not technically
297 // the exponent in NaN, infinities, and subnormals.)
298 int_fast16_t exp =
299 int_fast16_t((bits & mozilla::FloatingPoint<double>::kExponentBits) >>
300 DoubleExponentShift) -
301 int_fast16_t(mozilla::FloatingPoint<double>::kExponentBias);
303 // If the exponent's less than zero, abs(d) < 1, so the result is 0. (This
304 // also handles subnormals.)
305 if (exp < 0) {
306 return 0;
309 uint_fast16_t exponent = mozilla::AssertedCast<uint_fast16_t>(exp);
311 // If the exponent is greater than or equal to the bits of precision of a
312 // double plus UnsignedInteger's width, the number is either infinite, NaN,
313 // or too large to have lower-order bits in the congruent value. (Example:
314 // 2**84 is exactly representable as a double. The next exact double is
315 // 2**84 + 2**32. Thus if UnsignedInteger is uint32_t, an exponent >= 84
316 // implies floor(abs(d)) == 0 mod 2**32.) Return 0 in all these cases.
317 constexpr size_t ResultWidth = CHAR_BIT * sizeof(UnsignedInteger);
318 if (exponent >= DoubleExponentShift + ResultWidth) {
319 return 0;
322 // The significand contains the bits that will determine the final result.
323 // Shift those bits left or right, according to the exponent, to their
324 // locations in the unsigned binary representation of floor(abs(d)).
325 static_assert(sizeof(UnsignedInteger) <= sizeof(uint64_t),
326 "left-shifting below would lose upper bits");
327 UnsignedInteger result =
328 (exponent > DoubleExponentShift)
329 ? UnsignedInteger(bits << (exponent - DoubleExponentShift))
330 : UnsignedInteger(bits >> (DoubleExponentShift - exponent));
332 // Two further complications remain. First, |result| may contain bogus
333 // sign/exponent bits. Second, IEEE-754 numbers' significands (excluding
334 // subnormals, but we already handled those) have an implicit leading 1
335 // which may affect the final result.
337 // It may appear that there's complexity here depending on how ResultWidth
338 // and DoubleExponentShift relate, but it turns out there's not.
340 // Assume ResultWidth < DoubleExponentShift:
341 // Only right-shifts leave bogus bits in |result|. For this to happen,
342 // we must right-shift by > |DoubleExponentShift - ResultWidth|, implying
343 // |exponent < ResultWidth|.
344 // The implicit leading bit only matters if it appears in the final
345 // result -- if |2**exponent mod 2**ResultWidth != 0|. This implies
346 // |exponent < ResultWidth|.
347 // Otherwise assume ResultWidth >= DoubleExponentShift:
348 // Any left-shift less than |ResultWidth - DoubleExponentShift| leaves
349 // bogus bits in |result|. This implies |exponent < ResultWidth|. Any
350 // right-shift less than |ResultWidth| does too, which implies
351 // |DoubleExponentShift - ResultWidth < exponent|. By assumption, then,
352 // |exponent| is negative, but we excluded that above. So bogus bits
353 // need only |exponent < ResultWidth|.
354 // The implicit leading bit matters identically to the other case, so
355 // again, |exponent < ResultWidth|.
356 if (exponent < ResultWidth) {
357 const auto implicitOne =
358 static_cast<UnsignedInteger>(UnsignedInteger{1} << exponent);
359 result &= implicitOne - 1; // remove bogus bits
360 result += implicitOne; // add the implicit bit
363 // Compute the congruent value in the signed range.
364 return (bits & mozilla::FloatingPoint<double>::kSignBit) ? ~result + 1
365 : result;
368 template <typename SignedInteger>
369 inline SignedInteger ToSignedInteger(double d) {
370 static_assert(std::is_signed_v<SignedInteger>,
371 "SignedInteger must be a signed type");
373 using UnsignedInteger = std::make_unsigned_t<SignedInteger>;
374 UnsignedInteger u = ToUnsignedInteger<UnsignedInteger>(d);
376 return mozilla::WrapToSigned(u);
379 // clang crashes compiling this when targeting arm:
380 // https://llvm.org/bugs/show_bug.cgi?id=22974
381 #if defined(__arm__) && MOZ_IS_GCC
383 template <>
384 inline int32_t ToSignedInteger<int32_t>(double d) {
385 int32_t i;
386 uint32_t tmp0;
387 uint32_t tmp1;
388 uint32_t tmp2;
389 asm(
390 // We use a pure integer solution here. In the 'softfp' ABI, the argument
391 // will start in r0 and r1, and VFP can't do all of the necessary ECMA
392 // conversions by itself so some integer code will be required anyway. A
393 // hybrid solution is faster on A9, but this pure integer solution is
394 // notably faster for A8.
396 // %0 is the result register, and may alias either of the %[QR]1
397 // registers.
398 // %Q4 holds the lower part of the mantissa.
399 // %R4 holds the sign, exponent, and the upper part of the mantissa.
400 // %1, %2 and %3 are used as temporary values.
402 // Extract the exponent.
403 " mov %1, %R4, LSR #20\n"
404 " bic %1, %1, #(1 << 11)\n" // Clear the sign.
406 // Set the implicit top bit of the mantissa. This clobbers a bit of the
407 // exponent, but we have already extracted that.
408 " orr %R4, %R4, #(1 << 20)\n"
410 // Special Cases
411 // We should return zero in the following special cases:
412 // - Exponent is 0x000 - 1023: +/-0 or subnormal.
413 // - Exponent is 0x7ff - 1023: +/-INFINITY or NaN
414 // - This case is implicitly handled by the standard code path
415 // anyway, as shifting the mantissa up by the exponent will
416 // result in '0'.
418 // The result is composed of the mantissa, prepended with '1' and
419 // bit-shifted left by the (decoded) exponent. Note that because the
420 // r1[20] is the bit with value '1', r1 is effectively already shifted
421 // (left) by 20 bits, and r0 is already shifted by 52 bits.
423 // Adjust the exponent to remove the encoding offset. If the decoded
424 // exponent is negative, quickly bail out with '0' as such values round to
425 // zero anyway. This also catches +/-0 and subnormals.
426 " sub %1, %1, #0xff\n"
427 " subs %1, %1, #0x300\n"
428 " bmi 8f\n"
430 // %1 = (decoded) exponent >= 0
431 // %R4 = upper mantissa and sign
433 // ---- Lower Mantissa ----
434 " subs %3, %1, #52\n" // Calculate exp-52
435 " bmi 1f\n"
437 // Shift r0 left by exp-52.
438 // Ensure that we don't overflow ARM's 8-bit shift operand range.
439 // We need to handle anything up to an 11-bit value here as we know that
440 // 52 <= exp <= 1024 (0x400). Any shift beyond 31 bits results in zero
441 // anyway, so as long as we don't touch the bottom 5 bits, we can use
442 // a logical OR to push long shifts into the 32 <= (exp&0xff) <= 255
443 // range.
444 " bic %2, %3, #0xff\n"
445 " orr %3, %3, %2, LSR #3\n"
446 // We can now perform a straight shift, avoiding the need for any
447 // conditional instructions or extra branches.
448 " mov %Q4, %Q4, LSL %3\n"
449 " b 2f\n"
450 "1:\n" // Shift r0 right by 52-exp.
451 // We know that 0 <= exp < 52, and we can shift up to 255 bits so
452 // 52-exp will always be a valid shift and we can sk%3 the range
453 // check for this case.
454 " rsb %3, %1, #52\n"
455 " mov %Q4, %Q4, LSR %3\n"
457 // %1 = (decoded) exponent
458 // %R4 = upper mantissa and sign
459 // %Q4 = partially-converted integer
461 "2:\n"
462 // ---- Upper Mantissa ----
463 // This is much the same as the lower mantissa, with a few different
464 // boundary checks and some masking to hide the exponent & sign bit in the
465 // upper word.
466 // Note that the upper mantissa is pre-shifted by 20 in %R4, but we shift
467 // it left more to remove the sign and exponent so it is effectively
468 // pre-shifted by 31 bits.
469 " subs %3, %1, #31\n" // Calculate exp-31
470 " mov %1, %R4, LSL #11\n" // Re-use %1 as a temporary register.
471 " bmi 3f\n"
473 // Shift %R4 left by exp-31.
474 // Avoid overflowing the 8-bit shift range, as before.
475 " bic %2, %3, #0xff\n"
476 " orr %3, %3, %2, LSR #3\n"
477 // Perform the shift.
478 " mov %2, %1, LSL %3\n"
479 " b 4f\n"
480 "3:\n" // Shift r1 right by 31-exp.
481 // We know that 0 <= exp < 31, and we can shift up to 255 bits so
482 // 31-exp will always be a valid shift and we can skip the range
483 // check for this case.
484 " rsb %3, %3, #0\n" // Calculate 31-exp from -(exp-31)
485 " mov %2, %1, LSR %3\n" // Thumb-2 can't do "LSR %3" in "orr".
487 // %Q4 = partially-converted integer (lower)
488 // %R4 = upper mantissa and sign
489 // %2 = partially-converted integer (upper)
491 "4:\n"
492 // Combine the converted parts.
493 " orr %Q4, %Q4, %2\n"
494 // Negate the result if we have to, and move it to %0 in the process. To
495 // avoid conditionals, we can do this by inverting on %R4[31], then adding
496 // %R4[31]>>31.
497 " eor %Q4, %Q4, %R4, ASR #31\n"
498 " add %0, %Q4, %R4, LSR #31\n"
499 " b 9f\n"
500 "8:\n"
501 // +/-INFINITY, +/-0, subnormals, NaNs, and anything else out-of-range
502 // that will result in a conversion of '0'.
503 " mov %0, #0\n"
504 "9:\n"
505 : "=r"(i), "=&r"(tmp0), "=&r"(tmp1), "=&r"(tmp2), "=&r"(d)
506 : "4"(d)
507 : "cc");
508 return i;
511 #endif // defined (__arm__) && MOZ_IS_GCC
513 namespace detail {
515 template <typename IntegerType,
516 bool IsUnsigned = std::is_unsigned_v<IntegerType>>
517 struct ToSignedOrUnsignedInteger;
519 template <typename IntegerType>
520 struct ToSignedOrUnsignedInteger<IntegerType, true> {
521 static IntegerType compute(double d) {
522 return ToUnsignedInteger<IntegerType>(d);
526 template <typename IntegerType>
527 struct ToSignedOrUnsignedInteger<IntegerType, false> {
528 static IntegerType compute(double d) {
529 return ToSignedInteger<IntegerType>(d);
533 } // namespace detail
535 template <typename IntegerType>
536 inline IntegerType ToSignedOrUnsignedInteger(double d) {
537 return detail::ToSignedOrUnsignedInteger<IntegerType>::compute(d);
540 /* WEBIDL 4.2.4 */
541 inline int8_t ToInt8(double d) { return ToSignedInteger<int8_t>(d); }
543 /* ECMA-262 7.1.10 ToUInt8() specialized for doubles. */
544 inline int8_t ToUint8(double d) { return ToUnsignedInteger<uint8_t>(d); }
546 /* WEBIDL 4.2.6 */
547 inline int16_t ToInt16(double d) { return ToSignedInteger<int16_t>(d); }
549 inline uint16_t ToUint16(double d) { return ToUnsignedInteger<uint16_t>(d); }
551 /* ES5 9.5 ToInt32 (specialized for doubles). */
552 inline int32_t ToInt32(double d) { return ToSignedInteger<int32_t>(d); }
554 /* ES5 9.6 (specialized for doubles). */
555 inline uint32_t ToUint32(double d) { return ToUnsignedInteger<uint32_t>(d); }
557 /* WEBIDL 4.2.10 */
558 inline int64_t ToInt64(double d) { return ToSignedInteger<int64_t>(d); }
560 /* WEBIDL 4.2.11 */
561 inline uint64_t ToUint64(double d) { return ToUnsignedInteger<uint64_t>(d); }
564 * An amount of space large enough to store the null-terminated result of
565 * |ToString| on any Number.
567 * The <https://tc39.es/ecma262/#sec-tostring-applied-to-the-number-type>
568 * |NumberToString| algorithm is specified in terms of results, not an
569 * algorithm. It is extremely unclear from the algorithm's definition what its
570 * longest output can be. |-(2**-19 - 2**-72)| requires 25 + 1 characters and
571 * is believed to be at least *very close* to the upper bound, so we round that
572 * *very generously* upward to a 64-bit pointer-size boundary (to be extra
573 * cautious) and assume that's adequate.
575 * If you can supply better reasoning for a tighter bound, file a bug to improve
576 * this!
578 static constexpr size_t MaximumNumberToStringLength = 31 + 1;
581 * Store in |out| the null-terminated, base-10 result of |ToString| applied to
582 * |d| per <https://tc39.es/ecma262/#sec-tostring-applied-to-the-number-type>.
583 * (This will produce "NaN", "-Infinity", or "Infinity" for non-finite |d|.)
585 extern JS_PUBLIC_API void NumberToString(
586 double d, char (&out)[MaximumNumberToStringLength]);
588 } // namespace JS
590 #endif /* js_Conversions_h */