conversions-inl.h 25 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7

#ifndef V8_CONVERSIONS_INL_H_
#define V8_CONVERSIONS_INL_H_

8 9 10
#include <float.h>         // Required for DBL_MAX and on Win32 for finite()
#include <limits.h>        // Required for INT_MAX etc.
#include <stdarg.h>
11
#include <cmath>
12
#include "src/globals.h"       // Required for V8_INFINITY
13
#include "src/unicode-cache-inl.h"
14 15 16 17

// ----------------------------------------------------------------------------
// Extra POSIX/ANSI functions for Win32/MSVC.

18
#include "src/base/bits.h"
19
#include "src/base/platform/platform.h"
20 21
#include "src/conversions.h"
#include "src/double.h"
22
#include "src/objects-inl.h"
23
#include "src/strtod.h"
24

25 26
namespace v8 {
namespace internal {
27

28
inline double JunkStringValue() {
29
  return bit_cast<double, uint64_t>(kQuietNaNMask);
30 31 32
}


33 34 35 36 37
inline double SignedZero(bool negative) {
  return negative ? uint64_to_double(Double::kSignMask) : 0.0;
}


38
// The fast double-to-unsigned-int conversion routine does not guarantee
39 40
// rounding towards zero, or any reasonable value if the argument is larger
// than what fits in an unsigned 32-bit integer.
41
inline unsigned int FastD2UI(double x) {
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  // There is no unsigned version of lrint, so there is no fast path
  // in this function as there is in FastD2I. Using lrint doesn't work
  // for values of 2^31 and above.

  // Convert "small enough" doubles to uint32_t by fixing the 32
  // least significant non-fractional bits in the low 32 bits of the
  // double, and reading them from there.
  const double k2Pow52 = 4503599627370496.0;
  bool negative = x < 0;
  if (negative) {
    x = -x;
  }
  if (x < k2Pow52) {
    x += k2Pow52;
    uint32_t result;
57
#ifndef V8_TARGET_BIG_ENDIAN
58
    Address mantissa_ptr = reinterpret_cast<Address>(&x);
59
#else
60
    Address mantissa_ptr = reinterpret_cast<Address>(&x) + kInt32Size;
61
#endif
62
    // Copy least significant 32 bits of mantissa.
63
    memcpy(&result, mantissa_ptr, sizeof(result));
64 65 66 67 68 69 70
    return negative ? ~result + 1 : result;
  }
  // Large number (outside uint32 range), Infinity or NaN.
  return 0x80000000u;  // Return integer indefinite.
}


71
inline float DoubleToFloat32(double x) {
72
  // TODO(yangguo): This static_cast is implementation-defined behaviour in C++,
73 74 75 76 77 78
  // so we may need to do the conversion manually instead to match the spec.
  volatile float f = static_cast<float>(x);
  return f;
}


79
inline double DoubleToInteger(double x) {
80 81
  if (std::isnan(x)) return 0;
  if (!std::isfinite(x) || x == 0) return x;
82
  return (x >= 0) ? std::floor(x) : std::ceil(x);
83 84 85 86 87 88
}


int32_t DoubleToInt32(double x) {
  int32_t i = FastD2I(x);
  if (FastI2D(i) == x) return i;
89 90 91 92 93 94 95 96 97
  Double d(x);
  int exponent = d.Exponent();
  if (exponent < 0) {
    if (exponent <= -Double::kSignificandSize) return 0;
    return d.Sign() * static_cast<int32_t>(d.Significand() >> -exponent);
  } else {
    if (exponent > 31) return 0;
    return d.Sign() * static_cast<int32_t>(d.Significand() << exponent);
  }
98 99
}

100 101 102 103 104 105 106
bool DoubleToSmiInteger(double value, int* smi_int_value) {
  if (IsMinusZero(value)) return false;
  int i = FastD2IChecked(value);
  if (value != i || !Smi::IsValid(i)) return false;
  *smi_int_value = i;
  return true;
}
107

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
bool IsSmiDouble(double value) {
  return !IsMinusZero(value) && value >= Smi::kMinValue &&
         value <= Smi::kMaxValue && value == FastI2D(FastD2I(value));
}


bool IsInt32Double(double value) {
  return !IsMinusZero(value) && value >= kMinInt && value <= kMaxInt &&
         value == FastI2D(FastD2I(value));
}


bool IsUint32Double(double value) {
  return !IsMinusZero(value) && value >= 0 && value <= kMaxUInt32 &&
         value == FastUI2D(FastD2UI(value));
}

125
bool DoubleToUint32IfEqualToSelf(double value, uint32_t* uint32_value) {
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  const double k2Pow52 = 4503599627370496.0;
  const uint32_t kValidTopBits = 0x43300000;
  const uint64_t kBottomBitMask = V8_2PART_UINT64_C(0x00000000, FFFFFFFF);

  // Add 2^52 to the double, to place valid uint32 values in the low-significant
  // bits of the exponent, by effectively setting the (implicit) top bit of the
  // significand. Note that this addition also normalises 0.0 and -0.0.
  double shifted_value = value + k2Pow52;

  // At this point, a valid uint32 valued double will be represented as:
  //
  // sign = 0
  // exponent = 52
  // significand = 1. 00...00 <value>
  //       implicit^          ^^^^^^^ 32 bits
  //                  ^^^^^^^^^^^^^^^ 52 bits
  //
  // Therefore, we can first check the top 32 bits to make sure that the sign,
  // exponent and remaining significand bits are valid, and only then check the
  // value in the bottom 32 bits.

  uint64_t result = bit_cast<uint64_t>(shifted_value);
  if ((result >> 32) == kValidTopBits) {
    *uint32_value = result & kBottomBitMask;
    return FastUI2D(result & kBottomBitMask) == value;
151 152 153
  }
  return false;
}
154 155 156 157 158 159 160 161 162 163 164

int32_t NumberToInt32(Object* number) {
  if (number->IsSmi()) return Smi::cast(number)->value();
  return DoubleToInt32(number->Number());
}

uint32_t NumberToUint32(Object* number) {
  if (number->IsSmi()) return Smi::cast(number)->value();
  return DoubleToUint32(number->Number());
}

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
uint32_t PositiveNumberToUint32(Object* number) {
  if (number->IsSmi()) {
    int value = Smi::cast(number)->value();
    if (value <= 0) return 0;
    return value;
  }
  DCHECK(number->IsHeapNumber());
  double value = number->Number();
  // Catch all values smaller than 1 and use the double-negation trick for NANs.
  if (!(value >= 1)) return 0;
  uint32_t max = std::numeric_limits<uint32_t>::max();
  if (value < max) return static_cast<uint32_t>(value);
  return max;
}

180 181 182 183
int64_t NumberToInt64(Object* number) {
  if (number->IsSmi()) return Smi::cast(number)->value();
  return static_cast<int64_t>(number->Number());
}
184

185
bool TryNumberToSize(Object* number, size_t* result) {
186 187
  // Do not create handles in this function! Don't use SealHandleScope because
  // the function can be used concurrently.
188 189 190 191 192 193 194 195 196 197 198 199
  if (number->IsSmi()) {
    int value = Smi::cast(number)->value();
    DCHECK(static_cast<unsigned>(Smi::kMaxValue) <=
           std::numeric_limits<size_t>::max());
    if (value >= 0) {
      *result = static_cast<size_t>(value);
      return true;
    }
    return false;
  } else {
    DCHECK(number->IsHeapNumber());
    double value = HeapNumber::cast(number)->value();
200 201 202 203 204 205
    // If value is compared directly to the limit, the limit will be
    // casted to a double and could end up as limit + 1,
    // because a double might not have enough mantissa bits for it.
    // So we might as well cast the limit first, and use < instead of <=.
    double maxSize = static_cast<double>(std::numeric_limits<size_t>::max());
    if (value >= 0 && value < maxSize) {
206 207 208 209 210 211 212 213
      *result = static_cast<size_t>(value);
      return true;
    } else {
      return false;
    }
  }
}

214
size_t NumberToSize(Object* number) {
215
  size_t result = 0;
216
  bool is_valid = TryNumberToSize(number, &result);
217 218 219 220 221
  CHECK(is_valid);
  return result;
}


222 223 224 225 226
uint32_t DoubleToUint32(double x) {
  return static_cast<uint32_t>(DoubleToInt32(x));
}


227
template <class Iterator, class EndMark>
228 229 230
bool SubStringEquals(Iterator* current,
                     EndMark end,
                     const char* substring) {
231
  DCHECK(**current == *substring);
232 233 234 235 236 237 238 239 240 241 242 243
  for (substring++; *substring != '\0'; substring++) {
    ++*current;
    if (*current == end || **current != *substring) return false;
  }
  ++*current;
  return true;
}


// Returns true if a nonspace character has been found and false if the
// end was been reached before finding a nonspace character.
template <class Iterator, class EndMark>
244 245 246
inline bool AdvanceToNonspace(UnicodeCache* unicode_cache,
                              Iterator* current,
                              EndMark end) {
247
  while (*current != end) {
248
    if (!unicode_cache->IsWhiteSpaceOrLineTerminator(**current)) return true;
249 250 251 252 253 254 255 256
    ++*current;
  }
  return false;
}


// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
template <int radix_log_2, class Iterator, class EndMark>
257 258 259 260 261
double InternalStringToIntDouble(UnicodeCache* unicode_cache,
                                 Iterator current,
                                 EndMark end,
                                 bool negative,
                                 bool allow_trailing_junk) {
262
  DCHECK(current != end);
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

  // Skip leading 0s.
  while (*current == '0') {
    ++current;
    if (current == end) return SignedZero(negative);
  }

  int64_t number = 0;
  int exponent = 0;
  const int radix = (1 << radix_log_2);

  do {
    int digit;
    if (*current >= '0' && *current <= '9' && *current < '0' + radix) {
      digit = static_cast<char>(*current) - '0';
    } else if (radix > 10 && *current >= 'a' && *current < 'a' + radix - 10) {
      digit = static_cast<char>(*current) - 'a' + 10;
    } else if (radix > 10 && *current >= 'A' && *current < 'A' + radix - 10) {
      digit = static_cast<char>(*current) - 'A' + 10;
    } else {
      if (allow_trailing_junk ||
          !AdvanceToNonspace(unicode_cache, &current, end)) {
        break;
      } else {
287
        return JunkStringValue();
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
      }
    }

    number = number * radix + digit;
    int overflow = static_cast<int>(number >> 53);
    if (overflow != 0) {
      // Overflow occurred. Need to determine which direction to round the
      // result.
      int overflow_bits_count = 1;
      while (overflow > 1) {
        overflow_bits_count++;
        overflow >>= 1;
      }

      int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
      int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
      number >>= overflow_bits_count;
      exponent = overflow_bits_count;

      bool zero_tail = true;
      while (true) {
        ++current;
        if (current == end || !isDigit(*current, radix)) break;
        zero_tail = zero_tail && *current == '0';
        exponent += radix_log_2;
      }

      if (!allow_trailing_junk &&
          AdvanceToNonspace(unicode_cache, &current, end)) {
317
        return JunkStringValue();
318 319 320 321 322 323 324 325 326 327 328 329 330 331
      }

      int middle_value = (1 << (overflow_bits_count - 1));
      if (dropped_bits > middle_value) {
        number++;  // Rounding up.
      } else if (dropped_bits == middle_value) {
        // Rounding to even to consistency with decimals: half-way case rounds
        // up if significant part is odd and down otherwise.
        if ((number & 1) != 0 || !zero_tail) {
          number++;  // Rounding up.
        }
      }

      // Rounding up may cause overflow.
332
      if ((number & (static_cast<int64_t>(1) << 53)) != 0) {
333 334 335 336 337 338 339 340
        exponent++;
        number >>= 1;
      }
      break;
    }
    ++current;
  } while (current != end);

341 342
  DCHECK(number < ((int64_t)1 << 53));
  DCHECK(static_cast<int64_t>(static_cast<double>(number)) == number);
343 344 345 346 347 348 349 350 351

  if (exponent == 0) {
    if (negative) {
      if (number == 0) return -0.0;
      number = -number;
    }
    return static_cast<double>(number);
  }

352
  DCHECK(number != 0);
353
  return std::ldexp(static_cast<double>(negative ? -number : number), exponent);
354 355
}

356
// ES6 18.2.5 parseInt(string, radix)
357
template <class Iterator, class EndMark>
358 359 360 361
double InternalStringToInt(UnicodeCache* unicode_cache,
                           Iterator current,
                           EndMark end,
                           int radix) {
362
  const bool allow_trailing_junk = true;
363
  const double empty_string_val = JunkStringValue();
364 365 366 367 368 369 370 371 372 373 374 375

  if (!AdvanceToNonspace(unicode_cache, &current, end)) {
    return empty_string_val;
  }

  bool negative = false;
  bool leading_zero = false;

  if (*current == '+') {
    // Ignore leading sign; skip following spaces.
    ++current;
    if (current == end) {
376
      return JunkStringValue();
377 378 379 380
    }
  } else if (*current == '-') {
    ++current;
    if (current == end) {
381
      return JunkStringValue();
382 383 384 385 386 387
    }
    negative = true;
  }

  if (radix == 0) {
    // Radix detection.
388
    radix = 10;
389 390 391 392 393 394
    if (*current == '0') {
      ++current;
      if (current == end) return SignedZero(negative);
      if (*current == 'x' || *current == 'X') {
        radix = 16;
        ++current;
395
        if (current == end) return JunkStringValue();
396 397 398 399 400 401 402 403 404 405 406
      } else {
        leading_zero = true;
      }
    }
  } else if (radix == 16) {
    if (*current == '0') {
      // Allow "0x" prefix.
      ++current;
      if (current == end) return SignedZero(negative);
      if (*current == 'x' || *current == 'X') {
        ++current;
407
        if (current == end) return JunkStringValue();
408 409 410 411 412 413
      } else {
        leading_zero = true;
      }
    }
  }

414
  if (radix < 2 || radix > 36) return JunkStringValue();
415 416 417 418 419 420 421 422 423

  // Skip leading zeros.
  while (*current == '0') {
    leading_zero = true;
    ++current;
    if (current == end) return SignedZero(negative);
  }

  if (!leading_zero && !isDigit(*current, radix)) {
424
    return JunkStringValue();
425 426
  }

427
  if (base::bits::IsPowerOfTwo32(radix)) {
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    switch (radix) {
      case 2:
        return InternalStringToIntDouble<1>(
            unicode_cache, current, end, negative, allow_trailing_junk);
      case 4:
        return InternalStringToIntDouble<2>(
            unicode_cache, current, end, negative, allow_trailing_junk);
      case 8:
        return InternalStringToIntDouble<3>(
            unicode_cache, current, end, negative, allow_trailing_junk);

      case 16:
        return InternalStringToIntDouble<4>(
            unicode_cache, current, end, negative, allow_trailing_junk);

      case 32:
        return InternalStringToIntDouble<5>(
            unicode_cache, current, end, negative, allow_trailing_junk);
      default:
        UNREACHABLE();
    }
  }

  if (radix == 10) {
    // Parsing with strtod.
    const int kMaxSignificantDigits = 309;  // Doubles are less than 1.8e308.
    // The buffer may contain up to kMaxSignificantDigits + 1 digits and a zero
    // end.
    const int kBufferSize = kMaxSignificantDigits + 2;
    char buffer[kBufferSize];
    int buffer_pos = 0;
    while (*current >= '0' && *current <= '9') {
      if (buffer_pos <= kMaxSignificantDigits) {
        // If the number has more than kMaxSignificantDigits it will be parsed
        // as infinity.
463
        DCHECK(buffer_pos < kBufferSize);
464 465 466 467 468 469 470 471
        buffer[buffer_pos++] = static_cast<char>(*current);
      }
      ++current;
      if (current == end) break;
    }

    if (!allow_trailing_junk &&
        AdvanceToNonspace(unicode_cache, &current, end)) {
472
      return JunkStringValue();
473 474
    }

475
    SLOW_DCHECK(buffer_pos < kBufferSize);
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    buffer[buffer_pos] = '\0';
    Vector<const char> buffer_vector(buffer, buffer_pos);
    return negative ? -Strtod(buffer_vector, 0) : Strtod(buffer_vector, 0);
  }

  // The following code causes accumulating rounding error for numbers greater
  // than ~2^56. It's explicitly allowed in the spec: "if R is not 2, 4, 8, 10,
  // 16, or 32, then mathInt may be an implementation-dependent approximation to
  // the mathematical integer value" (15.1.2.2).

  int lim_0 = '0' + (radix < 10 ? radix : 10);
  int lim_a = 'a' + (radix - 10);
  int lim_A = 'A' + (radix - 10);

  // NOTE: The code for computing the value may seem a bit complex at
  // first glance. It is structured to use 32-bit multiply-and-add
  // loops as long as possible to avoid loosing precision.

  double v = 0.0;
  bool done = false;
  do {
    // Parse the longest part of the string starting at index j
    // possible while keeping the multiplier, and thus the part
    // itself, within 32 bits.
    unsigned int part = 0, multiplier = 1;
    while (true) {
      int d;
      if (*current >= '0' && *current < lim_0) {
        d = *current - '0';
      } else if (*current >= 'a' && *current < lim_a) {
        d = *current - 'a' + 10;
      } else if (*current >= 'A' && *current < lim_A) {
        d = *current - 'A' + 10;
      } else {
        done = true;
        break;
      }

      // Update the value of the part as long as the multiplier fits
      // in 32 bits. When we can't guarantee that the next iteration
      // will not overflow the multiplier, we stop parsing the part
      // by leaving the loop.
      const unsigned int kMaximumMultiplier = 0xffffffffU / 36;
      uint32_t m = multiplier * radix;
      if (m > kMaximumMultiplier) break;
      part = part * radix + d;
      multiplier = m;
523
      DCHECK(multiplier > part);
524 525 526 527 528 529 530 531 532 533 534 535 536 537

      ++current;
      if (current == end) {
        done = true;
        break;
      }
    }

    // Update the value and skip the part in the string.
    v = v * multiplier + part;
  } while (!done);

  if (!allow_trailing_junk &&
      AdvanceToNonspace(unicode_cache, &current, end)) {
538
    return JunkStringValue();
539 540 541 542 543 544 545 546 547 548 549 550
  }

  return negative ? -v : v;
}


// Converts a string to a double value. Assumes the Iterator supports
// the following operations:
// 1. current == end (other ops are not allowed), current != end.
// 2. *current - gets the current character in the sequence.
// 3. ++current (advances the position).
template <class Iterator, class EndMark>
551 552 553 554 555
double InternalStringToDouble(UnicodeCache* unicode_cache,
                              Iterator current,
                              EndMark end,
                              int flags,
                              double empty_string_val) {
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  // To make sure that iterator dereferencing is valid the following
  // convention is used:
  // 1. Each '++current' statement is followed by check for equality to 'end'.
  // 2. If AdvanceToNonspace returned false then current == end.
  // 3. If 'current' becomes be equal to 'end' the function returns or goes to
  // 'parsing_done'.
  // 4. 'current' is not dereferenced after the 'parsing_done' label.
  // 5. Code before 'parsing_done' may rely on 'current != end'.
  if (!AdvanceToNonspace(unicode_cache, &current, end)) {
    return empty_string_val;
  }

  const bool allow_trailing_junk = (flags & ALLOW_TRAILING_JUNK) != 0;

  // The longest form of simplified number is: "-<significant digits>'.1eXXX\0".
  const int kBufferSize = kMaxSignificantDigits + 10;
  char buffer[kBufferSize];  // NOLINT: size is known at compile time.
  int buffer_pos = 0;

  // Exponent will be adjusted if insignificant digits of the integer part
  // or insignificant leading zeros of the fractional part are dropped.
  int exponent = 0;
  int significant_digits = 0;
  int insignificant_digits = 0;
  bool nonzero_digit_dropped = false;

582 583 584 585 586 587 588
  enum Sign {
    NONE,
    NEGATIVE,
    POSITIVE
  };

  Sign sign = NONE;
589 590 591 592

  if (*current == '+') {
    // Ignore leading sign.
    ++current;
593
    if (current == end) return JunkStringValue();
594
    sign = POSITIVE;
595 596
  } else if (*current == '-') {
    ++current;
597
    if (current == end) return JunkStringValue();
598
    sign = NEGATIVE;
599 600
  }

601 602 603
  static const char kInfinityString[] = "Infinity";
  if (*current == kInfinityString[0]) {
    if (!SubStringEquals(&current, end, kInfinityString)) {
604
      return JunkStringValue();
605 606 607 608
    }

    if (!allow_trailing_junk &&
        AdvanceToNonspace(unicode_cache, &current, end)) {
609
      return JunkStringValue();
610 611
    }

612
    DCHECK(buffer_pos == 0);
613
    return (sign == NEGATIVE) ? -V8_INFINITY : V8_INFINITY;
614 615 616 617 618
  }

  bool leading_zero = false;
  if (*current == '0') {
    ++current;
619
    if (current == end) return SignedZero(sign == NEGATIVE);
620 621 622 623 624 625

    leading_zero = true;

    // It could be hexadecimal value.
    if ((flags & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
      ++current;
626
      if (current == end || !isDigit(*current, 16) || sign != NONE) {
627
        return JunkStringValue();  // "0x".
628 629 630 631 632
      }

      return InternalStringToIntDouble<4>(unicode_cache,
                                          current,
                                          end,
633
                                          false,
634
                                          allow_trailing_junk);
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

    // It could be an explicit octal value.
    } else if ((flags & ALLOW_OCTAL) && (*current == 'o' || *current == 'O')) {
      ++current;
      if (current == end || !isDigit(*current, 8) || sign != NONE) {
        return JunkStringValue();  // "0o".
      }

      return InternalStringToIntDouble<3>(unicode_cache,
                                          current,
                                          end,
                                          false,
                                          allow_trailing_junk);

    // It could be a binary value.
    } else if ((flags & ALLOW_BINARY) && (*current == 'b' || *current == 'B')) {
      ++current;
      if (current == end || !isBinaryDigit(*current) || sign != NONE) {
        return JunkStringValue();  // "0b".
      }

      return InternalStringToIntDouble<1>(unicode_cache,
                                          current,
                                          end,
                                          false,
                                          allow_trailing_junk);
661 662 663 664 665
    }

    // Ignore leading zeros in the integer part.
    while (*current == '0') {
      ++current;
666
      if (current == end) return SignedZero(sign == NEGATIVE);
667 668 669
    }
  }

670
  bool octal = leading_zero && (flags & ALLOW_IMPLICIT_OCTAL) != 0;
671 672 673 674

  // Copy significant digits of the integer part (if any) to the buffer.
  while (*current >= '0' && *current <= '9') {
    if (significant_digits < kMaxSignificantDigits) {
675
      DCHECK(buffer_pos < kBufferSize);
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
      buffer[buffer_pos++] = static_cast<char>(*current);
      significant_digits++;
      // Will later check if it's an octal in the buffer.
    } else {
      insignificant_digits++;  // Move the digit into the exponential part.
      nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
    }
    octal = octal && *current < '8';
    ++current;
    if (current == end) goto parsing_done;
  }

  if (significant_digits == 0) {
    octal = false;
  }

  if (*current == '.') {
693
    if (octal && !allow_trailing_junk) return JunkStringValue();
694 695 696 697 698
    if (octal) goto parsing_done;

    ++current;
    if (current == end) {
      if (significant_digits == 0 && !leading_zero) {
699
        return JunkStringValue();
700 701 702 703 704 705 706 707 708 709 710
      } else {
        goto parsing_done;
      }
    }

    if (significant_digits == 0) {
      // octal = false;
      // Integer part consists of 0 or is absent. Significant digits start after
      // leading zeros (if any).
      while (*current == '0') {
        ++current;
711
        if (current == end) return SignedZero(sign == NEGATIVE);
712 713 714 715
        exponent--;  // Move this 0 into the exponent.
      }
    }

716 717
    // There is a fractional part.  We don't emit a '.', but adjust the exponent
    // instead.
718 719
    while (*current >= '0' && *current <= '9') {
      if (significant_digits < kMaxSignificantDigits) {
720
        DCHECK(buffer_pos < kBufferSize);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
        buffer[buffer_pos++] = static_cast<char>(*current);
        significant_digits++;
        exponent--;
      } else {
        // Ignore insignificant digits in the fractional part.
        nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
      }
      ++current;
      if (current == end) goto parsing_done;
    }
  }

  if (!leading_zero && exponent == 0 && significant_digits == 0) {
    // If leading_zeros is true then the string contains zeros.
    // If exponent < 0 then string was [+-]\.0*...
    // If significant_digits != 0 the string is not equal to 0.
    // Otherwise there are no digits in the string.
738
    return JunkStringValue();
739 740 741 742
  }

  // Parse exponential part.
  if (*current == 'e' || *current == 'E') {
743
    if (octal) return JunkStringValue();
744 745 746 747 748
    ++current;
    if (current == end) {
      if (allow_trailing_junk) {
        goto parsing_done;
      } else {
749
        return JunkStringValue();
750 751 752 753 754 755 756 757 758 759
      }
    }
    char sign = '+';
    if (*current == '+' || *current == '-') {
      sign = static_cast<char>(*current);
      ++current;
      if (current == end) {
        if (allow_trailing_junk) {
          goto parsing_done;
        } else {
760
          return JunkStringValue();
761 762 763 764 765 766 767 768
        }
      }
    }

    if (current == end || *current < '0' || *current > '9') {
      if (allow_trailing_junk) {
        goto parsing_done;
      } else {
769
        return JunkStringValue();
770 771 772
      }
    }

773
    const int max_exponent = INT_MAX / 2;
774
    DCHECK(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    int num = 0;
    do {
      // Check overflow.
      int digit = *current - '0';
      if (num >= max_exponent / 10
          && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
        num = max_exponent;
      } else {
        num = num * 10 + digit;
      }
      ++current;
    } while (current != end && *current >= '0' && *current <= '9');

    exponent += (sign == '-' ? -num : num);
  }

  if (!allow_trailing_junk &&
      AdvanceToNonspace(unicode_cache, &current, end)) {
793
    return JunkStringValue();
794 795 796 797 798 799 800 801 802
  }

  parsing_done:
  exponent += insignificant_digits;

  if (octal) {
    return InternalStringToIntDouble<3>(unicode_cache,
                                        buffer,
                                        buffer + buffer_pos,
803
                                        sign == NEGATIVE,
804 805 806 807 808 809 810 811
                                        allow_trailing_junk);
  }

  if (nonzero_digit_dropped) {
    buffer[buffer_pos++] = '1';
    exponent--;
  }

812
  SLOW_DCHECK(buffer_pos < kBufferSize);
813 814 815
  buffer[buffer_pos] = '\0';

  double converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
816
  return (sign == NEGATIVE) ? -converted : converted;
817 818
}

819 820
}  // namespace internal
}  // namespace v8
821 822

#endif  // V8_CONVERSIONS_INL_H_