1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_CONVERSIONS_INL_H_
6 #define V8_CONVERSIONS_INL_H_
8 #include <float.h> // Required for DBL_MAX and on Win32 for finite()
9 #include <limits.h> // Required for INT_MAX etc.
12 #include "src/globals.h" // Required for V8_INFINITY
13 #include "src/unicode-cache-inl.h"
15 // ----------------------------------------------------------------------------
16 // Extra POSIX/ANSI functions for Win32/MSVC.
18 #include "src/base/bits.h"
19 #include "src/base/platform/platform.h"
20 #include "src/conversions.h"
21 #include "src/double.h"
22 #include "src/objects-inl.h"
23 #include "src/scanner.h"
24 #include "src/strtod.h"
29 inline double JunkStringValue() {
30 return bit_cast<double, uint64_t>(kQuietNaNMask);
34 inline double SignedZero(bool negative) {
35 return negative ? uint64_to_double(Double::kSignMask) : 0.0;
39 // The fast double-to-unsigned-int conversion routine does not guarantee
40 // rounding towards zero, or any reasonable value if the argument is larger
41 // than what fits in an unsigned 32-bit integer.
42 inline unsigned int FastD2UI(double x) {
43 // There is no unsigned version of lrint, so there is no fast path
44 // in this function as there is in FastD2I. Using lrint doesn't work
45 // for values of 2^31 and above.
47 // Convert "small enough" doubles to uint32_t by fixing the 32
48 // least significant non-fractional bits in the low 32 bits of the
49 // double, and reading them from there.
50 const double k2Pow52 = 4503599627370496.0;
51 bool negative = x < 0;
58 #ifndef V8_TARGET_BIG_ENDIAN
59 Address mantissa_ptr = reinterpret_cast<Address>(&x);
61 Address mantissa_ptr = reinterpret_cast<Address>(&x) + kIntSize;
63 // Copy least significant 32 bits of mantissa.
64 memcpy(&result, mantissa_ptr, sizeof(result));
65 return negative ? ~result + 1 : result;
67 // Large number (outside uint32 range), Infinity or NaN.
68 return 0x80000000u; // Return integer indefinite.
72 inline float DoubleToFloat32(double x) {
73 // TODO(yanggou): This static_cast is implementation-defined behaviour in C++,
74 // so we may need to do the conversion manually instead to match the spec.
75 volatile float f = static_cast<float>(x);
80 inline double DoubleToInteger(double x) {
81 if (std::isnan(x)) return 0;
82 if (!std::isfinite(x) || x == 0) return x;
83 return (x >= 0) ? std::floor(x) : std::ceil(x);
87 int32_t DoubleToInt32(double x) {
88 int32_t i = FastD2I(x);
89 if (FastI2D(i) == x) return i;
91 int exponent = d.Exponent();
93 if (exponent <= -Double::kSignificandSize) return 0;
94 return d.Sign() * static_cast<int32_t>(d.Significand() >> -exponent);
96 if (exponent > 31) return 0;
97 return d.Sign() * static_cast<int32_t>(d.Significand() << exponent);
102 bool IsSmiDouble(double value) {
103 return !IsMinusZero(value) && value >= Smi::kMinValue &&
104 value <= Smi::kMaxValue && value == FastI2D(FastD2I(value));
108 bool IsInt32Double(double value) {
109 return !IsMinusZero(value) && value >= kMinInt && value <= kMaxInt &&
110 value == FastI2D(FastD2I(value));
114 bool IsUint32Double(double value) {
115 return !IsMinusZero(value) && value >= 0 && value <= kMaxUInt32 &&
116 value == FastUI2D(FastD2UI(value));
120 int32_t NumberToInt32(Object* number) {
121 if (number->IsSmi()) return Smi::cast(number)->value();
122 return DoubleToInt32(number->Number());
126 uint32_t NumberToUint32(Object* number) {
127 if (number->IsSmi()) return Smi::cast(number)->value();
128 return DoubleToUint32(number->Number());
132 bool TryNumberToSize(Isolate* isolate, Object* number, size_t* result) {
133 SealHandleScope shs(isolate);
134 if (number->IsSmi()) {
135 int value = Smi::cast(number)->value();
136 DCHECK(static_cast<unsigned>(Smi::kMaxValue) <=
137 std::numeric_limits<size_t>::max());
139 *result = static_cast<size_t>(value);
144 DCHECK(number->IsHeapNumber());
145 double value = HeapNumber::cast(number)->value();
146 if (value >= 0 && value <= std::numeric_limits<size_t>::max()) {
147 *result = static_cast<size_t>(value);
156 size_t NumberToSize(Isolate* isolate, Object* number) {
158 bool is_valid = TryNumberToSize(isolate, number, &result);
164 uint32_t DoubleToUint32(double x) {
165 return static_cast<uint32_t>(DoubleToInt32(x));
169 template <class Iterator, class EndMark>
170 bool SubStringEquals(Iterator* current,
172 const char* substring) {
173 DCHECK(**current == *substring);
174 for (substring++; *substring != '\0'; substring++) {
176 if (*current == end || **current != *substring) return false;
183 // Returns true if a nonspace character has been found and false if the
184 // end was been reached before finding a nonspace character.
185 template <class Iterator, class EndMark>
186 inline bool AdvanceToNonspace(UnicodeCache* unicode_cache,
189 while (*current != end) {
190 if (!unicode_cache->IsWhiteSpaceOrLineTerminator(**current)) return true;
197 // Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
198 template <int radix_log_2, class Iterator, class EndMark>
199 double InternalStringToIntDouble(UnicodeCache* unicode_cache,
203 bool allow_trailing_junk) {
204 DCHECK(current != end);
207 while (*current == '0') {
209 if (current == end) return SignedZero(negative);
214 const int radix = (1 << radix_log_2);
218 if (*current >= '0' && *current <= '9' && *current < '0' + radix) {
219 digit = static_cast<char>(*current) - '0';
220 } else if (radix > 10 && *current >= 'a' && *current < 'a' + radix - 10) {
221 digit = static_cast<char>(*current) - 'a' + 10;
222 } else if (radix > 10 && *current >= 'A' && *current < 'A' + radix - 10) {
223 digit = static_cast<char>(*current) - 'A' + 10;
225 if (allow_trailing_junk ||
226 !AdvanceToNonspace(unicode_cache, ¤t, end)) {
229 return JunkStringValue();
233 number = number * radix + digit;
234 int overflow = static_cast<int>(number >> 53);
236 // Overflow occurred. Need to determine which direction to round the
238 int overflow_bits_count = 1;
239 while (overflow > 1) {
240 overflow_bits_count++;
244 int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
245 int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
246 number >>= overflow_bits_count;
247 exponent = overflow_bits_count;
249 bool zero_tail = true;
252 if (current == end || !isDigit(*current, radix)) break;
253 zero_tail = zero_tail && *current == '0';
254 exponent += radix_log_2;
257 if (!allow_trailing_junk &&
258 AdvanceToNonspace(unicode_cache, ¤t, end)) {
259 return JunkStringValue();
262 int middle_value = (1 << (overflow_bits_count - 1));
263 if (dropped_bits > middle_value) {
264 number++; // Rounding up.
265 } else if (dropped_bits == middle_value) {
266 // Rounding to even to consistency with decimals: half-way case rounds
267 // up if significant part is odd and down otherwise.
268 if ((number & 1) != 0 || !zero_tail) {
269 number++; // Rounding up.
273 // Rounding up may cause overflow.
274 if ((number & (static_cast<int64_t>(1) << 53)) != 0) {
281 } while (current != end);
283 DCHECK(number < ((int64_t)1 << 53));
284 DCHECK(static_cast<int64_t>(static_cast<double>(number)) == number);
288 if (number == 0) return -0.0;
291 return static_cast<double>(number);
295 return std::ldexp(static_cast<double>(negative ? -number : number), exponent);
299 template <class Iterator, class EndMark>
300 double InternalStringToInt(UnicodeCache* unicode_cache,
304 const bool allow_trailing_junk = true;
305 const double empty_string_val = JunkStringValue();
307 if (!AdvanceToNonspace(unicode_cache, ¤t, end)) {
308 return empty_string_val;
311 bool negative = false;
312 bool leading_zero = false;
314 if (*current == '+') {
315 // Ignore leading sign; skip following spaces.
317 if (current == end) {
318 return JunkStringValue();
320 } else if (*current == '-') {
322 if (current == end) {
323 return JunkStringValue();
331 if (*current == '0') {
333 if (current == end) return SignedZero(negative);
334 if (*current == 'x' || *current == 'X') {
337 if (current == end) return JunkStringValue();
342 } else if (radix == 16) {
343 if (*current == '0') {
344 // Allow "0x" prefix.
346 if (current == end) return SignedZero(negative);
347 if (*current == 'x' || *current == 'X') {
349 if (current == end) return JunkStringValue();
356 if (radix < 2 || radix > 36) return JunkStringValue();
358 // Skip leading zeros.
359 while (*current == '0') {
362 if (current == end) return SignedZero(negative);
365 if (!leading_zero && !isDigit(*current, radix)) {
366 return JunkStringValue();
369 if (base::bits::IsPowerOfTwo32(radix)) {
372 return InternalStringToIntDouble<1>(
373 unicode_cache, current, end, negative, allow_trailing_junk);
375 return InternalStringToIntDouble<2>(
376 unicode_cache, current, end, negative, allow_trailing_junk);
378 return InternalStringToIntDouble<3>(
379 unicode_cache, current, end, negative, allow_trailing_junk);
382 return InternalStringToIntDouble<4>(
383 unicode_cache, current, end, negative, allow_trailing_junk);
386 return InternalStringToIntDouble<5>(
387 unicode_cache, current, end, negative, allow_trailing_junk);
394 // Parsing with strtod.
395 const int kMaxSignificantDigits = 309; // Doubles are less than 1.8e308.
396 // The buffer may contain up to kMaxSignificantDigits + 1 digits and a zero
398 const int kBufferSize = kMaxSignificantDigits + 2;
399 char buffer[kBufferSize];
401 while (*current >= '0' && *current <= '9') {
402 if (buffer_pos <= kMaxSignificantDigits) {
403 // If the number has more than kMaxSignificantDigits it will be parsed
405 DCHECK(buffer_pos < kBufferSize);
406 buffer[buffer_pos++] = static_cast<char>(*current);
409 if (current == end) break;
412 if (!allow_trailing_junk &&
413 AdvanceToNonspace(unicode_cache, ¤t, end)) {
414 return JunkStringValue();
417 SLOW_DCHECK(buffer_pos < kBufferSize);
418 buffer[buffer_pos] = '\0';
419 Vector<const char> buffer_vector(buffer, buffer_pos);
420 return negative ? -Strtod(buffer_vector, 0) : Strtod(buffer_vector, 0);
423 // The following code causes accumulating rounding error for numbers greater
424 // than ~2^56. It's explicitly allowed in the spec: "if R is not 2, 4, 8, 10,
425 // 16, or 32, then mathInt may be an implementation-dependent approximation to
426 // the mathematical integer value" (15.1.2.2).
428 int lim_0 = '0' + (radix < 10 ? radix : 10);
429 int lim_a = 'a' + (radix - 10);
430 int lim_A = 'A' + (radix - 10);
432 // NOTE: The code for computing the value may seem a bit complex at
433 // first glance. It is structured to use 32-bit multiply-and-add
434 // loops as long as possible to avoid loosing precision.
439 // Parse the longest part of the string starting at index j
440 // possible while keeping the multiplier, and thus the part
441 // itself, within 32 bits.
442 unsigned int part = 0, multiplier = 1;
445 if (*current >= '0' && *current < lim_0) {
447 } else if (*current >= 'a' && *current < lim_a) {
448 d = *current - 'a' + 10;
449 } else if (*current >= 'A' && *current < lim_A) {
450 d = *current - 'A' + 10;
456 // Update the value of the part as long as the multiplier fits
457 // in 32 bits. When we can't guarantee that the next iteration
458 // will not overflow the multiplier, we stop parsing the part
459 // by leaving the loop.
460 const unsigned int kMaximumMultiplier = 0xffffffffU / 36;
461 uint32_t m = multiplier * radix;
462 if (m > kMaximumMultiplier) break;
463 part = part * radix + d;
465 DCHECK(multiplier > part);
468 if (current == end) {
474 // Update the value and skip the part in the string.
475 v = v * multiplier + part;
478 if (!allow_trailing_junk &&
479 AdvanceToNonspace(unicode_cache, ¤t, end)) {
480 return JunkStringValue();
483 return negative ? -v : v;
487 // Converts a string to a double value. Assumes the Iterator supports
488 // the following operations:
489 // 1. current == end (other ops are not allowed), current != end.
490 // 2. *current - gets the current character in the sequence.
491 // 3. ++current (advances the position).
492 template <class Iterator, class EndMark>
493 double InternalStringToDouble(UnicodeCache* unicode_cache,
497 double empty_string_val) {
498 // To make sure that iterator dereferencing is valid the following
499 // convention is used:
500 // 1. Each '++current' statement is followed by check for equality to 'end'.
501 // 2. If AdvanceToNonspace returned false then current == end.
502 // 3. If 'current' becomes be equal to 'end' the function returns or goes to
504 // 4. 'current' is not dereferenced after the 'parsing_done' label.
505 // 5. Code before 'parsing_done' may rely on 'current != end'.
506 if (!AdvanceToNonspace(unicode_cache, ¤t, end)) {
507 return empty_string_val;
510 const bool allow_trailing_junk = (flags & ALLOW_TRAILING_JUNK) != 0;
512 // The longest form of simplified number is: "-<significant digits>'.1eXXX\0".
513 const int kBufferSize = kMaxSignificantDigits + 10;
514 char buffer[kBufferSize]; // NOLINT: size is known at compile time.
517 // Exponent will be adjusted if insignificant digits of the integer part
518 // or insignificant leading zeros of the fractional part are dropped.
520 int significant_digits = 0;
521 int insignificant_digits = 0;
522 bool nonzero_digit_dropped = false;
532 if (*current == '+') {
533 // Ignore leading sign.
535 if (current == end) return JunkStringValue();
537 } else if (*current == '-') {
539 if (current == end) return JunkStringValue();
543 static const char kInfinityString[] = "Infinity";
544 if (*current == kInfinityString[0]) {
545 if (!SubStringEquals(¤t, end, kInfinityString)) {
546 return JunkStringValue();
549 if (!allow_trailing_junk &&
550 AdvanceToNonspace(unicode_cache, ¤t, end)) {
551 return JunkStringValue();
554 DCHECK(buffer_pos == 0);
555 return (sign == NEGATIVE) ? -V8_INFINITY : V8_INFINITY;
558 bool leading_zero = false;
559 if (*current == '0') {
561 if (current == end) return SignedZero(sign == NEGATIVE);
565 // It could be hexadecimal value.
566 if ((flags & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
568 if (current == end || !isDigit(*current, 16) || sign != NONE) {
569 return JunkStringValue(); // "0x".
572 return InternalStringToIntDouble<4>(unicode_cache,
576 allow_trailing_junk);
578 // It could be an explicit octal value.
579 } else if ((flags & ALLOW_OCTAL) && (*current == 'o' || *current == 'O')) {
581 if (current == end || !isDigit(*current, 8) || sign != NONE) {
582 return JunkStringValue(); // "0o".
585 return InternalStringToIntDouble<3>(unicode_cache,
589 allow_trailing_junk);
591 // It could be a binary value.
592 } else if ((flags & ALLOW_BINARY) && (*current == 'b' || *current == 'B')) {
594 if (current == end || !isBinaryDigit(*current) || sign != NONE) {
595 return JunkStringValue(); // "0b".
598 return InternalStringToIntDouble<1>(unicode_cache,
602 allow_trailing_junk);
605 // Ignore leading zeros in the integer part.
606 while (*current == '0') {
608 if (current == end) return SignedZero(sign == NEGATIVE);
612 bool octal = leading_zero && (flags & ALLOW_IMPLICIT_OCTAL) != 0;
614 // Copy significant digits of the integer part (if any) to the buffer.
615 while (*current >= '0' && *current <= '9') {
616 if (significant_digits < kMaxSignificantDigits) {
617 DCHECK(buffer_pos < kBufferSize);
618 buffer[buffer_pos++] = static_cast<char>(*current);
619 significant_digits++;
620 // Will later check if it's an octal in the buffer.
622 insignificant_digits++; // Move the digit into the exponential part.
623 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
625 octal = octal && *current < '8';
627 if (current == end) goto parsing_done;
630 if (significant_digits == 0) {
634 if (*current == '.') {
635 if (octal && !allow_trailing_junk) return JunkStringValue();
636 if (octal) goto parsing_done;
639 if (current == end) {
640 if (significant_digits == 0 && !leading_zero) {
641 return JunkStringValue();
647 if (significant_digits == 0) {
649 // Integer part consists of 0 or is absent. Significant digits start after
650 // leading zeros (if any).
651 while (*current == '0') {
653 if (current == end) return SignedZero(sign == NEGATIVE);
654 exponent--; // Move this 0 into the exponent.
658 // There is a fractional part. We don't emit a '.', but adjust the exponent
660 while (*current >= '0' && *current <= '9') {
661 if (significant_digits < kMaxSignificantDigits) {
662 DCHECK(buffer_pos < kBufferSize);
663 buffer[buffer_pos++] = static_cast<char>(*current);
664 significant_digits++;
667 // Ignore insignificant digits in the fractional part.
668 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
671 if (current == end) goto parsing_done;
675 if (!leading_zero && exponent == 0 && significant_digits == 0) {
676 // If leading_zeros is true then the string contains zeros.
677 // If exponent < 0 then string was [+-]\.0*...
678 // If significant_digits != 0 the string is not equal to 0.
679 // Otherwise there are no digits in the string.
680 return JunkStringValue();
683 // Parse exponential part.
684 if (*current == 'e' || *current == 'E') {
685 if (octal) return JunkStringValue();
687 if (current == end) {
688 if (allow_trailing_junk) {
691 return JunkStringValue();
695 if (*current == '+' || *current == '-') {
696 sign = static_cast<char>(*current);
698 if (current == end) {
699 if (allow_trailing_junk) {
702 return JunkStringValue();
707 if (current == end || *current < '0' || *current > '9') {
708 if (allow_trailing_junk) {
711 return JunkStringValue();
715 const int max_exponent = INT_MAX / 2;
716 DCHECK(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
720 int digit = *current - '0';
721 if (num >= max_exponent / 10
722 && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
725 num = num * 10 + digit;
728 } while (current != end && *current >= '0' && *current <= '9');
730 exponent += (sign == '-' ? -num : num);
733 if (!allow_trailing_junk &&
734 AdvanceToNonspace(unicode_cache, ¤t, end)) {
735 return JunkStringValue();
739 exponent += insignificant_digits;
742 return InternalStringToIntDouble<3>(unicode_cache,
746 allow_trailing_junk);
749 if (nonzero_digit_dropped) {
750 buffer[buffer_pos++] = '1';
754 SLOW_DCHECK(buffer_pos < kBufferSize);
755 buffer[buffer_pos] = '\0';
757 double converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
758 return (sign == NEGATIVE) ? -converted : converted;
761 } // namespace internal
764 #endif // V8_CONVERSIONS_INL_H_