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
14 // ----------------------------------------------------------------------------
15 // Extra POSIX/ANSI functions for Win32/MSVC.
17 #include "src/base/bits.h"
18 #include "src/base/platform/platform.h"
19 #include "src/conversions.h"
20 #include "src/double.h"
21 #include "src/scanner.h"
22 #include "src/strtod.h"
27 inline double JunkStringValue() {
28 return bit_cast<double, uint64_t>(kQuietNaNMask);
32 inline double SignedZero(bool negative) {
33 return negative ? uint64_to_double(Double::kSignMask) : 0.0;
37 // The fast double-to-unsigned-int conversion routine does not guarantee
38 // rounding towards zero, or any reasonable value if the argument is larger
39 // than what fits in an unsigned 32-bit integer.
40 inline unsigned int FastD2UI(double x) {
41 // There is no unsigned version of lrint, so there is no fast path
42 // in this function as there is in FastD2I. Using lrint doesn't work
43 // for values of 2^31 and above.
45 // Convert "small enough" doubles to uint32_t by fixing the 32
46 // least significant non-fractional bits in the low 32 bits of the
47 // double, and reading them from there.
48 const double k2Pow52 = 4503599627370496.0;
49 bool negative = x < 0;
56 #ifndef V8_TARGET_BIG_ENDIAN
57 Address mantissa_ptr = reinterpret_cast<Address>(&x);
59 Address mantissa_ptr = reinterpret_cast<Address>(&x) + kIntSize;
61 // Copy least significant 32 bits of mantissa.
62 memcpy(&result, mantissa_ptr, sizeof(result));
63 return negative ? ~result + 1 : result;
65 // Large number (outside uint32 range), Infinity or NaN.
66 return 0x80000000u; // Return integer indefinite.
70 inline float DoubleToFloat32(double x) {
71 // TODO(yanggou): This static_cast is implementation-defined behaviour in C++,
72 // so we may need to do the conversion manually instead to match the spec.
73 volatile float f = static_cast<float>(x);
78 inline double DoubleToInteger(double x) {
79 if (std::isnan(x)) return 0;
80 if (!std::isfinite(x) || x == 0) return x;
81 return (x >= 0) ? std::floor(x) : std::ceil(x);
85 int32_t DoubleToInt32(double x) {
86 int32_t i = FastD2I(x);
87 if (FastI2D(i) == x) return i;
89 int exponent = d.Exponent();
91 if (exponent <= -Double::kSignificandSize) return 0;
92 return d.Sign() * static_cast<int32_t>(d.Significand() >> -exponent);
94 if (exponent > 31) return 0;
95 return d.Sign() * static_cast<int32_t>(d.Significand() << exponent);
100 template <class Iterator, class EndMark>
101 bool SubStringEquals(Iterator* current,
103 const char* substring) {
104 DCHECK(**current == *substring);
105 for (substring++; *substring != '\0'; substring++) {
107 if (*current == end || **current != *substring) return false;
114 // Returns true if a nonspace character has been found and false if the
115 // end was been reached before finding a nonspace character.
116 template <class Iterator, class EndMark>
117 inline bool AdvanceToNonspace(UnicodeCache* unicode_cache,
120 while (*current != end) {
121 if (!unicode_cache->IsWhiteSpaceOrLineTerminator(**current)) return true;
128 // Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
129 template <int radix_log_2, class Iterator, class EndMark>
130 double InternalStringToIntDouble(UnicodeCache* unicode_cache,
134 bool allow_trailing_junk) {
135 DCHECK(current != end);
138 while (*current == '0') {
140 if (current == end) return SignedZero(negative);
145 const int radix = (1 << radix_log_2);
149 if (*current >= '0' && *current <= '9' && *current < '0' + radix) {
150 digit = static_cast<char>(*current) - '0';
151 } else if (radix > 10 && *current >= 'a' && *current < 'a' + radix - 10) {
152 digit = static_cast<char>(*current) - 'a' + 10;
153 } else if (radix > 10 && *current >= 'A' && *current < 'A' + radix - 10) {
154 digit = static_cast<char>(*current) - 'A' + 10;
156 if (allow_trailing_junk ||
157 !AdvanceToNonspace(unicode_cache, ¤t, end)) {
160 return JunkStringValue();
164 number = number * radix + digit;
165 int overflow = static_cast<int>(number >> 53);
167 // Overflow occurred. Need to determine which direction to round the
169 int overflow_bits_count = 1;
170 while (overflow > 1) {
171 overflow_bits_count++;
175 int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
176 int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
177 number >>= overflow_bits_count;
178 exponent = overflow_bits_count;
180 bool zero_tail = true;
183 if (current == end || !isDigit(*current, radix)) break;
184 zero_tail = zero_tail && *current == '0';
185 exponent += radix_log_2;
188 if (!allow_trailing_junk &&
189 AdvanceToNonspace(unicode_cache, ¤t, end)) {
190 return JunkStringValue();
193 int middle_value = (1 << (overflow_bits_count - 1));
194 if (dropped_bits > middle_value) {
195 number++; // Rounding up.
196 } else if (dropped_bits == middle_value) {
197 // Rounding to even to consistency with decimals: half-way case rounds
198 // up if significant part is odd and down otherwise.
199 if ((number & 1) != 0 || !zero_tail) {
200 number++; // Rounding up.
204 // Rounding up may cause overflow.
205 if ((number & (static_cast<int64_t>(1) << 53)) != 0) {
212 } while (current != end);
214 DCHECK(number < ((int64_t)1 << 53));
215 DCHECK(static_cast<int64_t>(static_cast<double>(number)) == number);
219 if (number == 0) return -0.0;
222 return static_cast<double>(number);
226 return std::ldexp(static_cast<double>(negative ? -number : number), exponent);
230 template <class Iterator, class EndMark>
231 double InternalStringToInt(UnicodeCache* unicode_cache,
235 const bool allow_trailing_junk = true;
236 const double empty_string_val = JunkStringValue();
238 if (!AdvanceToNonspace(unicode_cache, ¤t, end)) {
239 return empty_string_val;
242 bool negative = false;
243 bool leading_zero = false;
245 if (*current == '+') {
246 // Ignore leading sign; skip following spaces.
248 if (current == end) {
249 return JunkStringValue();
251 } else if (*current == '-') {
253 if (current == end) {
254 return JunkStringValue();
262 if (*current == '0') {
264 if (current == end) return SignedZero(negative);
265 if (*current == 'x' || *current == 'X') {
268 if (current == end) return JunkStringValue();
273 } else if (radix == 16) {
274 if (*current == '0') {
275 // Allow "0x" prefix.
277 if (current == end) return SignedZero(negative);
278 if (*current == 'x' || *current == 'X') {
280 if (current == end) return JunkStringValue();
287 if (radix < 2 || radix > 36) return JunkStringValue();
289 // Skip leading zeros.
290 while (*current == '0') {
293 if (current == end) return SignedZero(negative);
296 if (!leading_zero && !isDigit(*current, radix)) {
297 return JunkStringValue();
300 if (base::bits::IsPowerOfTwo32(radix)) {
303 return InternalStringToIntDouble<1>(
304 unicode_cache, current, end, negative, allow_trailing_junk);
306 return InternalStringToIntDouble<2>(
307 unicode_cache, current, end, negative, allow_trailing_junk);
309 return InternalStringToIntDouble<3>(
310 unicode_cache, current, end, negative, allow_trailing_junk);
313 return InternalStringToIntDouble<4>(
314 unicode_cache, current, end, negative, allow_trailing_junk);
317 return InternalStringToIntDouble<5>(
318 unicode_cache, current, end, negative, allow_trailing_junk);
325 // Parsing with strtod.
326 const int kMaxSignificantDigits = 309; // Doubles are less than 1.8e308.
327 // The buffer may contain up to kMaxSignificantDigits + 1 digits and a zero
329 const int kBufferSize = kMaxSignificantDigits + 2;
330 char buffer[kBufferSize];
332 while (*current >= '0' && *current <= '9') {
333 if (buffer_pos <= kMaxSignificantDigits) {
334 // If the number has more than kMaxSignificantDigits it will be parsed
336 DCHECK(buffer_pos < kBufferSize);
337 buffer[buffer_pos++] = static_cast<char>(*current);
340 if (current == end) break;
343 if (!allow_trailing_junk &&
344 AdvanceToNonspace(unicode_cache, ¤t, end)) {
345 return JunkStringValue();
348 SLOW_DCHECK(buffer_pos < kBufferSize);
349 buffer[buffer_pos] = '\0';
350 Vector<const char> buffer_vector(buffer, buffer_pos);
351 return negative ? -Strtod(buffer_vector, 0) : Strtod(buffer_vector, 0);
354 // The following code causes accumulating rounding error for numbers greater
355 // than ~2^56. It's explicitly allowed in the spec: "if R is not 2, 4, 8, 10,
356 // 16, or 32, then mathInt may be an implementation-dependent approximation to
357 // the mathematical integer value" (15.1.2.2).
359 int lim_0 = '0' + (radix < 10 ? radix : 10);
360 int lim_a = 'a' + (radix - 10);
361 int lim_A = 'A' + (radix - 10);
363 // NOTE: The code for computing the value may seem a bit complex at
364 // first glance. It is structured to use 32-bit multiply-and-add
365 // loops as long as possible to avoid loosing precision.
370 // Parse the longest part of the string starting at index j
371 // possible while keeping the multiplier, and thus the part
372 // itself, within 32 bits.
373 unsigned int part = 0, multiplier = 1;
376 if (*current >= '0' && *current < lim_0) {
378 } else if (*current >= 'a' && *current < lim_a) {
379 d = *current - 'a' + 10;
380 } else if (*current >= 'A' && *current < lim_A) {
381 d = *current - 'A' + 10;
387 // Update the value of the part as long as the multiplier fits
388 // in 32 bits. When we can't guarantee that the next iteration
389 // will not overflow the multiplier, we stop parsing the part
390 // by leaving the loop.
391 const unsigned int kMaximumMultiplier = 0xffffffffU / 36;
392 uint32_t m = multiplier * radix;
393 if (m > kMaximumMultiplier) break;
394 part = part * radix + d;
396 DCHECK(multiplier > part);
399 if (current == end) {
405 // Update the value and skip the part in the string.
406 v = v * multiplier + part;
409 if (!allow_trailing_junk &&
410 AdvanceToNonspace(unicode_cache, ¤t, end)) {
411 return JunkStringValue();
414 return negative ? -v : v;
418 // Converts a string to a double value. Assumes the Iterator supports
419 // the following operations:
420 // 1. current == end (other ops are not allowed), current != end.
421 // 2. *current - gets the current character in the sequence.
422 // 3. ++current (advances the position).
423 template <class Iterator, class EndMark>
424 double InternalStringToDouble(UnicodeCache* unicode_cache,
428 double empty_string_val) {
429 // To make sure that iterator dereferencing is valid the following
430 // convention is used:
431 // 1. Each '++current' statement is followed by check for equality to 'end'.
432 // 2. If AdvanceToNonspace returned false then current == end.
433 // 3. If 'current' becomes be equal to 'end' the function returns or goes to
435 // 4. 'current' is not dereferenced after the 'parsing_done' label.
436 // 5. Code before 'parsing_done' may rely on 'current != end'.
437 if (!AdvanceToNonspace(unicode_cache, ¤t, end)) {
438 return empty_string_val;
441 const bool allow_trailing_junk = (flags & ALLOW_TRAILING_JUNK) != 0;
443 // The longest form of simplified number is: "-<significant digits>'.1eXXX\0".
444 const int kBufferSize = kMaxSignificantDigits + 10;
445 char buffer[kBufferSize]; // NOLINT: size is known at compile time.
448 // Exponent will be adjusted if insignificant digits of the integer part
449 // or insignificant leading zeros of the fractional part are dropped.
451 int significant_digits = 0;
452 int insignificant_digits = 0;
453 bool nonzero_digit_dropped = false;
463 if (*current == '+') {
464 // Ignore leading sign.
466 if (current == end) return JunkStringValue();
468 } else if (*current == '-') {
470 if (current == end) return JunkStringValue();
474 static const char kInfinityString[] = "Infinity";
475 if (*current == kInfinityString[0]) {
476 if (!SubStringEquals(¤t, end, kInfinityString)) {
477 return JunkStringValue();
480 if (!allow_trailing_junk &&
481 AdvanceToNonspace(unicode_cache, ¤t, end)) {
482 return JunkStringValue();
485 DCHECK(buffer_pos == 0);
486 return (sign == NEGATIVE) ? -V8_INFINITY : V8_INFINITY;
489 bool leading_zero = false;
490 if (*current == '0') {
492 if (current == end) return SignedZero(sign == NEGATIVE);
496 // It could be hexadecimal value.
497 if ((flags & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
499 if (current == end || !isDigit(*current, 16) || sign != NONE) {
500 return JunkStringValue(); // "0x".
503 return InternalStringToIntDouble<4>(unicode_cache,
507 allow_trailing_junk);
509 // It could be an explicit octal value.
510 } else if ((flags & ALLOW_OCTAL) && (*current == 'o' || *current == 'O')) {
512 if (current == end || !isDigit(*current, 8) || sign != NONE) {
513 return JunkStringValue(); // "0o".
516 return InternalStringToIntDouble<3>(unicode_cache,
520 allow_trailing_junk);
522 // It could be a binary value.
523 } else if ((flags & ALLOW_BINARY) && (*current == 'b' || *current == 'B')) {
525 if (current == end || !isBinaryDigit(*current) || sign != NONE) {
526 return JunkStringValue(); // "0b".
529 return InternalStringToIntDouble<1>(unicode_cache,
533 allow_trailing_junk);
536 // Ignore leading zeros in the integer part.
537 while (*current == '0') {
539 if (current == end) return SignedZero(sign == NEGATIVE);
543 bool octal = leading_zero && (flags & ALLOW_IMPLICIT_OCTAL) != 0;
545 // Copy significant digits of the integer part (if any) to the buffer.
546 while (*current >= '0' && *current <= '9') {
547 if (significant_digits < kMaxSignificantDigits) {
548 DCHECK(buffer_pos < kBufferSize);
549 buffer[buffer_pos++] = static_cast<char>(*current);
550 significant_digits++;
551 // Will later check if it's an octal in the buffer.
553 insignificant_digits++; // Move the digit into the exponential part.
554 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
556 octal = octal && *current < '8';
558 if (current == end) goto parsing_done;
561 if (significant_digits == 0) {
565 if (*current == '.') {
566 if (octal && !allow_trailing_junk) return JunkStringValue();
567 if (octal) goto parsing_done;
570 if (current == end) {
571 if (significant_digits == 0 && !leading_zero) {
572 return JunkStringValue();
578 if (significant_digits == 0) {
580 // Integer part consists of 0 or is absent. Significant digits start after
581 // leading zeros (if any).
582 while (*current == '0') {
584 if (current == end) return SignedZero(sign == NEGATIVE);
585 exponent--; // Move this 0 into the exponent.
589 // There is a fractional part. We don't emit a '.', but adjust the exponent
591 while (*current >= '0' && *current <= '9') {
592 if (significant_digits < kMaxSignificantDigits) {
593 DCHECK(buffer_pos < kBufferSize);
594 buffer[buffer_pos++] = static_cast<char>(*current);
595 significant_digits++;
598 // Ignore insignificant digits in the fractional part.
599 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
602 if (current == end) goto parsing_done;
606 if (!leading_zero && exponent == 0 && significant_digits == 0) {
607 // If leading_zeros is true then the string contains zeros.
608 // If exponent < 0 then string was [+-]\.0*...
609 // If significant_digits != 0 the string is not equal to 0.
610 // Otherwise there are no digits in the string.
611 return JunkStringValue();
614 // Parse exponential part.
615 if (*current == 'e' || *current == 'E') {
616 if (octal) return JunkStringValue();
618 if (current == end) {
619 if (allow_trailing_junk) {
622 return JunkStringValue();
626 if (*current == '+' || *current == '-') {
627 sign = static_cast<char>(*current);
629 if (current == end) {
630 if (allow_trailing_junk) {
633 return JunkStringValue();
638 if (current == end || *current < '0' || *current > '9') {
639 if (allow_trailing_junk) {
642 return JunkStringValue();
646 const int max_exponent = INT_MAX / 2;
647 DCHECK(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
651 int digit = *current - '0';
652 if (num >= max_exponent / 10
653 && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
656 num = num * 10 + digit;
659 } while (current != end && *current >= '0' && *current <= '9');
661 exponent += (sign == '-' ? -num : num);
664 if (!allow_trailing_junk &&
665 AdvanceToNonspace(unicode_cache, ¤t, end)) {
666 return JunkStringValue();
670 exponent += insignificant_digits;
673 return InternalStringToIntDouble<3>(unicode_cache,
677 allow_trailing_junk);
680 if (nonzero_digit_dropped) {
681 buffer[buffer_pos++] = '1';
685 SLOW_DCHECK(buffer_pos < kBufferSize);
686 buffer[buffer_pos] = '\0';
688 double converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
689 return (sign == NEGATIVE) ? -converted : converted;
692 } } // namespace v8::internal
694 #endif // V8_CONVERSIONS_INL_H_