array.js 48.9 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// This file relies on the fact that the following declarations have been made
// in runtime.js:
30
// var $Array = global.Array;
31 32 33 34 35

// -------------------------------------------------------------------

// Global list of arrays visited during toString, toLocaleString and
// join invocations.
36
var visited_arrays = new InternalArray();
37 38 39 40


// Gets a sorted array of array keys.  Useful for operations on sparse
// arrays.  Dupes have not been removed.
41 42 43 44 45 46 47 48 49
function GetSortedArrayKeys(array, indices) {
  var keys = new InternalArray();
  if (IS_NUMBER(indices)) {
    // It's an interval
    var limit = indices;
    for (var i = 0; i < limit; ++i) {
      var e = array[i];
      if (!IS_UNDEFINED(e) || i in array) {
        keys.push(i);
50
      }
51 52 53 54 55
    }
  } else {
    var length = indices.length;
    for (var k = 0; k < length; ++k) {
      var key = indices[k];
56 57 58 59 60 61 62
      if (!IS_UNDEFINED(key)) {
        var e = array[key];
        if (!IS_UNDEFINED(e) || key in array) {
          keys.push(key);
        }
      }
    }
63
    %_CallFunction(keys, function(a, b) { return a - b; }, ArraySort);
64 65 66 67 68
  }
  return keys;
}


69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
function SparseJoinWithSeparator(array, len, convert, separator) {
  var keys = GetSortedArrayKeys(array, %GetArrayKeys(array, len));
  var totalLength = 0;
  var elements = new InternalArray(keys.length * 2);
  var previousKey = -1;
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    if (key != previousKey) {  // keys may contain duplicates.
      var e = array[key];
      if (!IS_STRING(e)) e = convert(e);
      elements[i * 2] = key;
      elements[i * 2 + 1] = e;
      previousKey = key;
    }
  }
  return %SparseJoinWithSeparator(elements, len, separator);
}


88 89 90 91 92
// Optimized for sparse arrays if separator is ''.
function SparseJoin(array, len, convert) {
  var keys = GetSortedArrayKeys(array, %GetArrayKeys(array, len));
  var last_key = -1;
  var keys_length = keys.length;
93

94
  var elements = new InternalArray(keys_length);
95 96
  var elements_length = 0;

97 98 99 100
  for (var i = 0; i < keys_length; i++) {
    var key = keys[i];
    if (key != last_key) {
      var e = array[key];
101 102
      if (!IS_STRING(e)) e = convert(e);
      elements[elements_length++] = e;
103 104 105
      last_key = key;
    }
  }
106
  return %StringBuilderConcat(elements, elements_length, '');
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
}


function UseSparseVariant(object, length, is_array) {
   return is_array &&
       length > 1000 &&
       (!%_IsSmi(length) ||
        %EstimateNumberOfElements(object) < (length >> 2));
}


function Join(array, length, separator, convert) {
  if (length == 0) return '';

  var is_array = IS_ARRAY(array);

  if (is_array) {
    // If the array is cyclic, return the empty string for already
    // visited arrays.
126
    if (!%PushIfAbsent(visited_arrays, array)) return '';
127 128 129 130
  }

  // Attempt to convert the elements.
  try {
131 132 133 134 135 136
    if (UseSparseVariant(array, length, is_array)) {
      if (separator.length == 0) {
        return SparseJoin(array, length, convert);
      } else {
        return SparseJoinWithSeparator(array, length, convert, separator);
      }
137 138
    }

139 140 141
    // Fast case for one-element arrays.
    if (length == 1) {
      var e = array[0];
142 143
      if (IS_STRING(e)) return e;
      return convert(e);
144 145
    }

146
    // Construct an array for the elements.
147
    var elements = new InternalArray(length);
148

149 150
    // We pull the empty separator check outside the loop for speed!
    if (separator.length == 0) {
151
      var elements_length = 0;
152 153
      for (var i = 0; i < length; i++) {
        var e = array[i];
154 155
        if (!IS_STRING(e)) e = convert(e);
        elements[elements_length++] = e;
156
      }
157 158 159 160 161
      elements.length = elements_length;
      var result = %_FastAsciiArrayJoin(elements, '');
      if (!IS_UNDEFINED(result)) return result;
      return %StringBuilderConcat(elements, elements_length, '');
    }
162
    // Non-empty separator case.
163
    // If the first element is a number then use the heuristic that the
164 165 166 167
    // remaining elements are also likely to be numbers.
    if (!IS_NUMBER(array[0])) {
      for (var i = 0; i < length; i++) {
        var e = array[i];
168 169
        if (!IS_STRING(e)) e = convert(e);
        elements[i] = e;
170
      }
171
    } else {
172 173
      for (var i = 0; i < length; i++) {
        var e = array[i];
174 175 176 177 178 179
        if (IS_NUMBER(e)) {
          e = %_NumberToString(e);
        } else if (!IS_STRING(e)) {
          e = convert(e);
        }
        elements[i] = e;
180
      }
181
    }
182
    var result = %_FastAsciiArrayJoin(elements, separator);
183
    if (!IS_UNDEFINED(result)) return result;
184

185
    return %StringBuilderJoin(elements, length, separator);
186
  } finally {
187 188 189
    // Make sure to remove the last element of the visited array no
    // matter what happens.
    if (is_array) visited_arrays.length = visited_arrays.length - 1;
190
  }
191
}
192 193


194
function ConvertToString(x) {
195
  // Assumes x is a non-string.
196 197 198
  if (IS_NUMBER(x)) return %_NumberToString(x);
  if (IS_BOOLEAN(x)) return x ? 'true' : 'false';
  return (IS_NULL_OR_UNDEFINED(x)) ? '' : %ToString(%DefaultString(x));
199
}
200 201 202


function ConvertToLocaleString(e) {
203
  if (IS_NULL_OR_UNDEFINED(e)) {
204 205
    return '';
  } else {
206
    // According to ES5, section 15.4.4.3, the toLocaleString conversion
207 208
    // must throw a TypeError if ToObject(e).toLocaleString isn't
    // callable.
209
    var e_obj = ToObject(e);
210
    return %ToString(e_obj.toLocaleString());
211
  }
212
}
213 214 215 216 217 218


// This function implements the optimized splice implementation that can use
// special array operations to handle sparse arrays in a sensible fashion.
function SmartSlice(array, start_i, del_count, len, deleted_elements) {
  // Move deleted elements to a new array (the return value from splice).
219 220 221 222 223 224 225
  var indices = %GetArrayKeys(array, start_i + del_count);
  if (IS_NUMBER(indices)) {
    var limit = indices;
    for (var i = start_i; i < limit; ++i) {
      var current = array[i];
      if (!IS_UNDEFINED(current) || i in array) {
        deleted_elements[i - start_i] = current;
226
      }
227 228 229 230 231
    }
  } else {
    var length = indices.length;
    for (var k = 0; k < length; ++k) {
      var key = indices[k];
232 233 234 235 236 237 238 239 240 241
      if (!IS_UNDEFINED(key)) {
        if (key >= start_i) {
          var current = array[key];
          if (!IS_UNDEFINED(current) || key in array) {
            deleted_elements[key - start_i] = current;
          }
        }
      }
    }
  }
242
}
243 244 245 246 247 248


// This function implements the optimized splice implementation that can use
// special array operations to handle sparse arrays in a sensible fashion.
function SmartMove(array, start_i, del_count, len, num_additional_args) {
  // Move data to new array.
249
  var new_array = new InternalArray(len - del_count + num_additional_args);
250 251 252 253 254 255 256
  var indices = %GetArrayKeys(array, len);
  if (IS_NUMBER(indices)) {
    var limit = indices;
    for (var i = 0; i < start_i && i < limit; ++i) {
      var current = array[i];
      if (!IS_UNDEFINED(current) || i in array) {
        new_array[i] = current;
257
      }
258 259 260 261 262
    }
    for (var i = start_i + del_count; i < limit; ++i) {
      var current = array[i];
      if (!IS_UNDEFINED(current) || i in array) {
        new_array[i - del_count + num_additional_args] = current;
263
      }
264 265 266 267 268
    }
  } else {
    var length = indices.length;
    for (var k = 0; k < length; ++k) {
      var key = indices[k];
269 270 271
      if (!IS_UNDEFINED(key)) {
        if (key < start_i) {
          var current = array[key];
272
          if (!IS_UNDEFINED(current) || key in array) {
273
            new_array[key] = current;
274
          }
275 276
        } else if (key >= start_i + del_count) {
          var current = array[key];
277
          if (!IS_UNDEFINED(current) || key in array) {
278
            new_array[key - del_count + num_additional_args] = current;
279
          }
280 281 282 283 284 285
        }
      }
    }
  }
  // Move contents of new_array into this array
  %MoveArrayContents(new_array, array);
286
}
287 288 289 290 291 292 293 294 295 296 297 298


// This is part of the old simple-minded splice.  We are using it either
// because the receiver is not an array (so we have no choice) or because we
// know we are not deleting or moving a lot of elements.
function SimpleSlice(array, start_i, del_count, len, deleted_elements) {
  for (var i = 0; i < del_count; i++) {
    var index = start_i + i;
    // The spec could also be interpreted such that %HasLocalProperty
    // would be the appropriate test.  We follow KJS in consulting the
    // prototype.
    var current = array[index];
299
    if (!IS_UNDEFINED(current) || index in array) {
300
      deleted_elements[i] = current;
301
    }
302
  }
303
}
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342


function SimpleMove(array, start_i, del_count, len, num_additional_args) {
  if (num_additional_args !== del_count) {
    // Move the existing elements after the elements to be deleted
    // to the right position in the resulting array.
    if (num_additional_args > del_count) {
      for (var i = len - del_count; i > start_i; i--) {
        var from_index = i + del_count - 1;
        var to_index = i + num_additional_args - 1;
        // The spec could also be interpreted such that
        // %HasLocalProperty would be the appropriate test.  We follow
        // KJS in consulting the prototype.
        var current = array[from_index];
        if (!IS_UNDEFINED(current) || from_index in array) {
          array[to_index] = current;
        } else {
          delete array[to_index];
        }
      }
    } else {
      for (var i = start_i; i < len - del_count; i++) {
        var from_index = i + del_count;
        var to_index = i + num_additional_args;
        // The spec could also be interpreted such that
        // %HasLocalProperty would be the appropriate test.  We follow
        // KJS in consulting the prototype.
        var current = array[from_index];
        if (!IS_UNDEFINED(current) || from_index in array) {
          array[to_index] = current;
        } else {
          delete array[to_index];
        }
      }
      for (var i = len; i > len - del_count + num_additional_args; i--) {
        delete array[i - 1];
      }
    }
  }
343
}
344 345 346 347 348 349


// -------------------------------------------------------------------


function ArrayToString() {
350 351 352 353 354 355 356 357 358 359 360
  var array;
  var func;
  if (IS_ARRAY(this)) {
    func = this.join;
    if (func === ArrayJoin) {
      return Join(this, this.length, ',', ConvertToString);
    }
    array = this;
  } else {
    array = ToObject(this);
    func = array.join;
361
  }
362 363 364 365
  if (!IS_SPEC_FUNCTION(func)) {
    return %_CallFunction(array, ObjectToString);
  }
  return %_CallFunction(array, func);
366
}
367 368 369


function ArrayToLocaleString() {
370 371 372 373 374
  var array = ToObject(this);
  var arrayLen = array.length;
  var len = TO_UINT32(arrayLen);
  if (len === 0) return "";
  return Join(array, len, ',', ConvertToLocaleString);
375
}
376 377 378


function ArrayJoin(separator) {
379 380 381 382 383
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.join"]);
  }

384
  var length = TO_UINT32(this.length);
385 386 387
  if (IS_UNDEFINED(separator)) {
    separator = ',';
  } else if (!IS_STRING(separator)) {
388
    separator = NonStringToString(separator);
389
  }
390 391

  var result = %_FastAsciiArrayJoin(this, separator);
392
  if (!IS_UNDEFINED(result)) return result;
393

394
  return Join(this, length, separator, ConvertToString);
395
}
396 397


398 399 400 401 402 403 404 405 406 407
function ObservedArrayPop(n) {
  n--;
  var value = this[n];

  try {
    BeginPerformSplice(this);
    delete this[n];
    this.length = n;
  } finally {
    EndPerformSplice(this);
408
    EnqueueSpliceRecord(this, n, [value], 0);
409 410 411 412 413
  }

  return value;
}

414 415 416
// Removes the last element from the array and returns it. See
// ECMA-262, section 15.4.4.6.
function ArrayPop() {
417 418 419 420 421
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.pop"]);
  }

422
  var n = TO_UINT32(this.length);
423 424 425 426
  if (n == 0) {
    this.length = n;
    return;
  }
427 428 429 430

  if (%IsObserved(this))
    return ObservedArrayPop.call(this, n);

431 432 433
  n--;
  var value = this[n];
  delete this[n];
434
  this.length = n;
435
  return value;
436
}
437 438


439 440 441 442 443 444 445 446 447 448 449 450
function ObservedArrayPush() {
  var n = TO_UINT32(this.length);
  var m = %_ArgumentsLength();

  try {
    BeginPerformSplice(this);
    for (var i = 0; i < m; i++) {
      this[i+n] = %_Arguments(i);
    }
    this.length = n + m;
  } finally {
    EndPerformSplice(this);
451
    EnqueueSpliceRecord(this, n, [], m);
452 453 454 455 456
  }

  return this.length;
}

457 458 459
// Appends the arguments to the end of the array and returns the new
// length of the array. See ECMA-262, section 15.4.4.7.
function ArrayPush() {
460 461 462 463 464
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.push"]);
  }

465 466 467
  if (%IsObserved(this))
    return ObservedArrayPush.apply(this, arguments);

468
  var n = TO_UINT32(this.length);
469 470 471 472 473 474
  var m = %_ArgumentsLength();
  for (var i = 0; i < m; i++) {
    this[i+n] = %_Arguments(i);
  }
  this.length = n + m;
  return this.length;
475
}
476 477


478 479 480
// Returns an array containing the array elements of the object followed
// by the array elements of each argument in order. See ECMA-262,
// section 15.4.4.7.
481
function ArrayConcat(arg1) {  // length == 1
482 483 484 485 486
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.concat"]);
  }

487
  var array = ToObject(this);
488
  var arg_count = %_ArgumentsLength();
489
  var arrays = new InternalArray(1 + arg_count);
490
  arrays[0] = array;
491 492
  for (var i = 0; i < arg_count; i++) {
    arrays[i + 1] = %_Arguments(i);
493 494
  }

495
  return %ArrayConcat(arrays);
496
}
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512


// For implementing reverse() on large, sparse arrays.
function SparseReverse(array, len) {
  var keys = GetSortedArrayKeys(array, %GetArrayKeys(array, len));
  var high_counter = keys.length - 1;
  var low_counter = 0;
  while (low_counter <= high_counter) {
    var i = keys[low_counter];
    var j = keys[high_counter];

    var j_complement = len - j - 1;
    var low, high;

    if (j_complement <= i) {
      high = j;
513
      while (keys[--high_counter] == j) { }
514 515 516 517
      low = j_complement;
    }
    if (j_complement >= i) {
      low = i;
518
      while (keys[++low_counter] == i) { }
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
      high = len - i - 1;
    }

    var current_i = array[low];
    if (!IS_UNDEFINED(current_i) || low in array) {
      var current_j = array[high];
      if (!IS_UNDEFINED(current_j) || high in array) {
        array[low] = current_j;
        array[high] = current_i;
      } else {
        array[high] = current_i;
        delete array[low];
      }
    } else {
      var current_j = array[high];
      if (!IS_UNDEFINED(current_j) || high in array) {
        array[low] = current_j;
        delete array[high];
      }
    }
  }
}


function ArrayReverse() {
544 545 546 547 548
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.reverse"]);
  }

549
  var j = TO_UINT32(this.length) - 1;
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575

  if (UseSparseVariant(this, j, IS_ARRAY(this))) {
    SparseReverse(this, j+1);
    return this;
  }

  for (var i = 0; i < j; i++, j--) {
    var current_i = this[i];
    if (!IS_UNDEFINED(current_i) || i in this) {
      var current_j = this[j];
      if (!IS_UNDEFINED(current_j) || j in this) {
        this[i] = current_j;
        this[j] = current_i;
      } else {
        this[j] = current_i;
        delete this[i];
      }
    } else {
      var current_j = this[j];
      if (!IS_UNDEFINED(current_j) || j in this) {
        this[i] = current_j;
        delete this[j];
      }
    }
  }
  return this;
576
}
577 578


579 580 581 582 583 584 585 586 587
function ObservedArrayShift(len) {
  var first = this[0];

  try {
    BeginPerformSplice(this);
    SimpleMove(this, 0, 1, len, 0);
    this.length = len - 1;
  } finally {
    EndPerformSplice(this);
588
    EnqueueSpliceRecord(this, 0, [first], 0);
589 590 591 592 593
  }

  return first;
}

594
function ArrayShift() {
595 596 597 598 599
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.shift"]);
  }

600
  var len = TO_UINT32(this.length);
601

602 603 604 605
  if (len === 0) {
    this.length = 0;
    return;
  }
606

607 608 609
  if (%IsObserved(this))
    return ObservedArrayShift.call(this, len);

610
  var first = this[0];
611

612
  if (IS_ARRAY(this)) {
613
    SmartMove(this, 0, 1, len, 0);
614
  } else {
615
    SimpleMove(this, 0, 1, len, 0);
616
  }
617

618
  this.length = len - 1;
619

620
  return first;
621
}
622

623 624 625 626 627 628 629 630 631 632 633 634 635
function ObservedArrayUnshift() {
  var len = TO_UINT32(this.length);
  var num_arguments = %_ArgumentsLength();

  try {
    BeginPerformSplice(this);
    SimpleMove(this, 0, 0, len, num_arguments);
    for (var i = 0; i < num_arguments; i++) {
      this[i] = %_Arguments(i);
    }
    this.length = len + num_arguments;
  } finally {
    EndPerformSplice(this);
636
    EnqueueSpliceRecord(this, 0, [], num_arguments);
637 638 639 640
  }

  return len + num_arguments;
}
641 642

function ArrayUnshift(arg1) {  // length == 1
643 644 645 646 647
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.unshift"]);
  }

648 649 650
  if (%IsObserved(this))
    return ObservedArrayUnshift.apply(this, arguments);

651
  var len = TO_UINT32(this.length);
652
  var num_arguments = %_ArgumentsLength();
653

654
  if (IS_ARRAY(this)) {
655
    SmartMove(this, 0, 0, len, num_arguments);
656
  } else {
657
    SimpleMove(this, 0, 0, len, num_arguments);
658
  }
659

660 661 662
  for (var i = 0; i < num_arguments; i++) {
    this[i] = %_Arguments(i);
  }
663

664
  this.length = len + num_arguments;
665

666
  return len + num_arguments;
667
}
668 669 670


function ArraySlice(start, end) {
671 672 673 674 675
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.slice"]);
  }

676
  var len = TO_UINT32(this.length);
677 678
  var start_i = TO_INTEGER(start);
  var end_i = len;
679

680
  if (end !== void 0) end_i = TO_INTEGER(end);
681

682 683 684 685 686 687
  if (start_i < 0) {
    start_i += len;
    if (start_i < 0) start_i = 0;
  } else {
    if (start_i > len) start_i = len;
  }
688

689 690 691 692 693 694
  if (end_i < 0) {
    end_i += len;
    if (end_i < 0) end_i = 0;
  } else {
    if (end_i > len) end_i = len;
  }
695

696
  var result = [];
697 698 699

  if (end_i < start_i) return result;

700
  if (IS_ARRAY(this) &&
701
      !%IsObserved(this) &&
702 703
      (end_i > 1000) &&
      (%EstimateNumberOfElements(this) < end_i)) {
704
    SmartSlice(this, start_i, end_i - start_i, len, result);
705
  } else {
706
    SimpleSlice(this, start_i, end_i - start_i, len, result);
707 708
  }

709
  result.length = end_i - start_i;
710

711
  return result;
712
}
713 714


715
function ComputeSpliceStartIndex(start_i, len) {
716 717
  if (start_i < 0) {
    start_i += len;
718
    return start_i < 0 ? 0 : start_i;
719
  }
720

721 722 723 724 725
  return start_i > len ? len : start_i;
}


function ComputeSpliceDeleteCount(delete_count, num_arguments, len, start_i) {
726
  // SpiderMonkey, TraceMonkey and JSC treat the case where no delete count is
727 728
  // given as a request to delete all the elements from the start.
  // And it differs from the case of undefined delete count.
729 730 731
  // This does not follow ECMA-262, but we do the same for
  // compatibility.
  var del_count = 0;
732 733 734 735 736 737 738 739 740 741 742 743
  if (num_arguments == 1)
    return len - start_i;

  del_count = TO_INTEGER(delete_count);
  if (del_count < 0)
    return 0;

  if (del_count > len - start_i)
    return len - start_i;

  return del_count;
}
744

745 746 747 748 749 750 751

function ObservedArraySplice(start, delete_count) {
  var num_arguments = %_ArgumentsLength();
  var len = TO_UINT32(this.length);
  var start_i = ComputeSpliceStartIndex(TO_INTEGER(start), len);
  var del_count = ComputeSpliceDeleteCount(delete_count, num_arguments, len,
                                           start_i);
752 753
  var deleted_elements = [];
  deleted_elements.length = del_count;
754 755 756 757
  var num_elements_to_add = num_arguments > 2 ? num_arguments - 2 : 0;

  try {
    BeginPerformSplice(this);
758

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    SimpleSlice(this, start_i, del_count, len, deleted_elements);
    SimpleMove(this, start_i, del_count, len, num_elements_to_add);

    // Insert the arguments into the resulting array in
    // place of the deleted elements.
    var i = start_i;
    var arguments_index = 2;
    var arguments_length = %_ArgumentsLength();
    while (arguments_index < arguments_length) {
      this[i++] = %_Arguments(arguments_index++);
    }
    this.length = len - del_count + num_elements_to_add;

  } finally {
    EndPerformSplice(this);
    if (deleted_elements.length || num_elements_to_add) {
       EnqueueSpliceRecord(this,
                           start_i,
                           deleted_elements.slice(),
                           num_elements_to_add);
    }
780
  }
781

782 783 784 785 786 787 788 789 790 791
  // Return the deleted elements.
  return deleted_elements;
}


function ArraySplice(start, delete_count) {
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.splice"]);
  }
792

793 794 795 796 797 798 799 800 801 802 803 804 805
  if (%IsObserved(this))
    return ObservedArraySplice.apply(this, arguments);

  var num_arguments = %_ArgumentsLength();
  var len = TO_UINT32(this.length);
  var start_i = ComputeSpliceStartIndex(TO_INTEGER(start), len);
  var del_count = ComputeSpliceDeleteCount(delete_count, num_arguments, len,
                                           start_i);
  var deleted_elements = [];
  deleted_elements.length = del_count;
  var num_elements_to_add = num_arguments > 2 ? num_arguments - 2 : 0;

  var use_simple_splice = true;
806
  if (IS_ARRAY(this) &&
807
      num_elements_to_add !== del_count) {
808 809 810 811 812 813 814 815
    // If we are only deleting/moving a few things near the end of the
    // array then the simple version is going to be faster, because it
    // doesn't touch most of the array.
    var estimated_non_hole_elements = %EstimateNumberOfElements(this);
    if (len > 20 && (estimated_non_hole_elements >> 2) < (len - start_i)) {
      use_simple_splice = false;
    }
  }
816

817 818
  if (use_simple_splice) {
    SimpleSlice(this, start_i, del_count, len, deleted_elements);
819
    SimpleMove(this, start_i, del_count, len, num_elements_to_add);
820 821
  } else {
    SmartSlice(this, start_i, del_count, len, deleted_elements);
822
    SmartMove(this, start_i, del_count, len, num_elements_to_add);
823
  }
824

825 826 827 828 829 830 831 832
  // Insert the arguments into the resulting array in
  // place of the deleted elements.
  var i = start_i;
  var arguments_index = 2;
  var arguments_length = %_ArgumentsLength();
  while (arguments_index < arguments_length) {
    this[i++] = %_Arguments(arguments_index++);
  }
833
  this.length = len - del_count + num_elements_to_add;
834

835 836
  // Return the deleted elements.
  return deleted_elements;
837
}
838 839 840


function ArraySort(comparefn) {
841 842 843 844 845
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.sort"]);
  }

olehougaard's avatar
olehougaard committed
846
  // In-place QuickSort algorithm.
olehougaard's avatar
olehougaard committed
847
  // For short (length <= 22) arrays, insertion sort is used for efficiency.
848

849
  if (!IS_SPEC_FUNCTION(comparefn)) {
850 851 852 853
    comparefn = function (x, y) {
      if (x === y) return 0;
      if (%_IsSmi(x) && %_IsSmi(y)) {
        return %SmiLexicographicCompare(x, y);
854
      }
855 856 857 858 859
      x = ToString(x);
      y = ToString(y);
      if (x == y) return 0;
      else return x < y ? -1 : 1;
    };
860
  }
861
  var receiver = %GetDefaultReceiver(comparefn);
862

863
  var InsertionSort = function InsertionSort(a, from, to) {
olehougaard's avatar
olehougaard committed
864 865
    for (var i = from + 1; i < to; i++) {
      var element = a[i];
866 867
      for (var j = i - 1; j >= from; j--) {
        var tmp = a[j];
868
        var order = %_CallFunction(receiver, tmp, element, comparefn);
869 870
        if (order > 0) {
          a[j + 1] = tmp;
olehougaard's avatar
olehougaard committed
871
        } else {
872
          break;
olehougaard's avatar
olehougaard committed
873 874
        }
      }
875
      a[j + 1] = element;
olehougaard's avatar
olehougaard committed
876
    }
877
  };
878

879 880 881 882 883 884 885 886 887 888 889 890 891
  var GetThirdIndex = function(a, from, to) {
    var t_array = [];
    // Use both 'from' and 'to' to determine the pivot candidates.
    var increment = 200 + ((to - from) & 15);
    for (var i = from + 1; i < to - 1; i += increment) {
      t_array.push([i, a[i]]);
    }
    t_array.sort(function(a, b) {
        return %_CallFunction(receiver, a[1], b[1], comparefn) } );
    var third_index = t_array[t_array.length >> 1][0];
    return third_index;
  }

892
  var QuickSort = function QuickSort(a, from, to) {
893
    var third_index = 0;
894 895 896 897 898
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from <= 10) {
        InsertionSort(a, from, to);
        return;
899
      }
900 901 902 903 904
      if (to - from > 1000) {
        third_index = GetThirdIndex(a, from, to);
      } else {
        third_index = from + ((to - from) >> 1);
      }
905 906 907
      // Find a pivot as the median of first, last and middle element.
      var v0 = a[from];
      var v1 = a[to - 1];
908
      var v2 = a[third_index];
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
      var c01 = %_CallFunction(receiver, v0, v1, comparefn);
      if (c01 > 0) {
        // v1 < v0, so swap them.
        var tmp = v0;
        v0 = v1;
        v1 = tmp;
      } // v0 <= v1.
      var c02 = %_CallFunction(receiver, v0, v2, comparefn);
      if (c02 >= 0) {
        // v2 <= v0 <= v1.
        var tmp = v0;
        v0 = v2;
        v2 = v1;
        v1 = tmp;
      } else {
        // v0 <= v1 && v0 < v2
        var c12 = %_CallFunction(receiver, v1, v2, comparefn);
        if (c12 > 0) {
          // v0 <= v2 < v1
          var tmp = v1;
          v1 = v2;
          v2 = tmp;
        }
      }
      // v0 <= v1 <= v2
      a[from] = v0;
      a[to - 1] = v2;
      var pivot = v1;
      var low_end = from + 1;   // Upper bound of elements lower than pivot.
      var high_start = to - 1;  // Lower bound of elements greater than pivot.
939
      a[third_index] = a[low_end];
940 941 942 943 944 945 946
      a[low_end] = pivot;

      // From low_end to i are elements equal to pivot.
      // From i to high_start are elements that haven't been compared yet.
      partition: for (var i = low_end + 1; i < high_start; i++) {
        var element = a[i];
        var order = %_CallFunction(receiver, element, pivot, comparefn);
947
        if (order < 0) {
948 949
          a[i] = a[low_end];
          a[low_end] = element;
950
          low_end++;
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
        } else if (order > 0) {
          do {
            high_start--;
            if (high_start == i) break partition;
            var top_elem = a[high_start];
            order = %_CallFunction(receiver, top_elem, pivot, comparefn);
          } while (order > 0);
          a[i] = a[high_start];
          a[high_start] = element;
          if (order < 0) {
            element = a[i];
            a[i] = a[low_end];
            a[low_end] = element;
            low_end++;
          }
966
        }
967
      }
968 969 970 971 972 973 974
      if (to - high_start < low_end - from) {
        QuickSort(a, high_start, to);
        to = low_end;
      } else {
        QuickSort(a, from, low_end);
        from = high_start;
      }
975
    }
976
  };
977

978 979
  // Copy elements in the range 0..length from obj's prototype chain
  // to obj itself, if obj has holes. Return one more than the maximal index
980
  // of a prototype property.
981
  var CopyFromPrototype = function CopyFromPrototype(obj, length) {
982
    var max = 0;
983
    for (var proto = %GetPrototype(obj); proto; proto = %GetPrototype(proto)) {
984
      var indices = %GetArrayKeys(proto, length);
985 986 987 988 989 990 991
      if (IS_NUMBER(indices)) {
        // It's an interval.
        var proto_length = indices;
        for (var i = 0; i < proto_length; i++) {
          if (!obj.hasOwnProperty(i) && proto.hasOwnProperty(i)) {
            obj[i] = proto[i];
            if (i >= max) { max = i + 1; }
992
          }
993 994 995 996 997 998 999 1000
        }
      } else {
        for (var i = 0; i < indices.length; i++) {
          var index = indices[i];
          if (!IS_UNDEFINED(index) &&
              !obj.hasOwnProperty(index) && proto.hasOwnProperty(index)) {
            obj[index] = proto[index];
            if (index >= max) { max = index + 1; }
1001 1002 1003 1004 1005
          }
        }
      }
    }
    return max;
1006
  };
1007 1008 1009 1010

  // Set a value of "undefined" on all indices in the range from..to
  // where a prototype of obj has an element. I.e., shadow all prototype
  // elements in that range.
1011
  var ShadowPrototypeElements = function(obj, from, to) {
1012
    for (var proto = %GetPrototype(obj); proto; proto = %GetPrototype(proto)) {
1013
      var indices = %GetArrayKeys(proto, to);
1014 1015 1016 1017 1018 1019
      if (IS_NUMBER(indices)) {
        // It's an interval.
        var proto_length = indices;
        for (var i = from; i < proto_length; i++) {
          if (proto.hasOwnProperty(i)) {
            obj[i] = void 0;
1020
          }
1021 1022 1023 1024 1025 1026 1027
        }
      } else {
        for (var i = 0; i < indices.length; i++) {
          var index = indices[i];
          if (!IS_UNDEFINED(index) && from <= index &&
              proto.hasOwnProperty(index)) {
            obj[index] = void 0;
1028 1029 1030 1031
          }
        }
      }
    }
1032
  };
1033

1034
  var SafeRemoveArrayHoles = function SafeRemoveArrayHoles(obj) {
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    // Copy defined elements from the end to fill in all holes and undefineds
    // in the beginning of the array.  Write undefineds and holes at the end
    // after loop is finished.
    var first_undefined = 0;
    var last_defined = length - 1;
    var num_holes = 0;
    while (first_undefined < last_defined) {
      // Find first undefined element.
      while (first_undefined < last_defined &&
             !IS_UNDEFINED(obj[first_undefined])) {
        first_undefined++;
      }
      // Maintain the invariant num_holes = the number of holes in the original
      // array with indices <= first_undefined or > last_defined.
      if (!obj.hasOwnProperty(first_undefined)) {
        num_holes++;
      }

      // Find last defined element.
      while (first_undefined < last_defined &&
             IS_UNDEFINED(obj[last_defined])) {
        if (!obj.hasOwnProperty(last_defined)) {
          num_holes++;
        }
        last_defined--;
      }
      if (first_undefined < last_defined) {
        // Fill in hole or undefined.
        obj[first_undefined] = obj[last_defined];
        obj[last_defined] = void 0;
      }
    }
    // If there were any undefineds in the entire array, first_undefined
    // points to one past the last defined element.  Make this true if
    // there were no undefineds, as well, so that first_undefined == number
    // of defined elements.
    if (!IS_UNDEFINED(obj[first_undefined])) first_undefined++;
    // Fill in the undefineds and the holes.  There may be a hole where
    // an undefined should be and vice versa.
    var i;
    for (i = first_undefined; i < length - num_holes; i++) {
      obj[i] = void 0;
    }
    for (i = length - num_holes; i < length; i++) {
      // For compatability with Webkit, do not expose elements in the prototype.
1080
      if (i in %GetPrototype(obj)) {
1081 1082 1083 1084 1085 1086 1087 1088
        obj[i] = void 0;
      } else {
        delete obj[i];
      }
    }

    // Return the number of defined elements.
    return first_undefined;
1089
  };
1090

1091
  var length = TO_UINT32(this.length);
1092
  if (length < 2) return this;
1093

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
  var is_array = IS_ARRAY(this);
  var max_prototype_element;
  if (!is_array) {
    // For compatibility with JSC, we also sort elements inherited from
    // the prototype chain on non-Array objects.
    // We do this by copying them to this object and sorting only
    // local elements. This is not very efficient, but sorting with
    // inherited elements happens very, very rarely, if at all.
    // The specification allows "implementation dependent" behavior
    // if an element on the prototype chain has an element that
    // might interact with sorting.
    max_prototype_element = CopyFromPrototype(this, length);
  }

1108 1109 1110
  var num_non_undefined = %IsObserved(this) ?
      -1 : %RemoveArrayHoles(this, length);

1111
  if (num_non_undefined == -1) {
1112 1113 1114
    // The array is observed, or there were indexed accessors in the array.
    // Move array holes and undefineds to the end using a Javascript function
    // that is safe in the presence of accessors and is observable.
1115 1116
    num_non_undefined = SafeRemoveArrayHoles(this);
  }
1117

1118
  QuickSort(this, 0, num_non_undefined);
1119

1120 1121 1122 1123 1124 1125
  if (!is_array && (num_non_undefined + 1 < max_prototype_element)) {
    // For compatibility with JSC, we shadow any elements in the prototype
    // chain that has become exposed by sort moving a hole to its position.
    ShadowPrototypeElements(this, num_non_undefined, max_prototype_element);
  }

1126
  return this;
1127
}
1128 1129 1130 1131 1132 1133


// The following functions cannot be made efficient on sparse arrays while
// preserving the semantics, since the calls to the receiver function can add
// or delete elements from the array.
function ArrayFilter(f, receiver) {
1134 1135 1136 1137 1138
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.filter"]);
  }

1139 1140 1141 1142 1143
  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = ToObject(this);
  var length = ToUint32(array.length);

1144
  if (!IS_SPEC_FUNCTION(f)) {
1145 1146
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1147 1148
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1149
  } else if (!IS_SPEC_OBJECT(receiver) && %IsClassicModeFunction(f)) {
1150
    receiver = ToObject(receiver);
1151
  }
1152

1153 1154 1155
  var result = new $Array();
  var accumulator = new InternalArray();
  var accumulator_length = 0;
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  if (%DebugCallbackSupportsStepping(f)) {
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(f);
        if (%_CallFunction(receiver, element, i, array, f)) {
          accumulator[accumulator_length++] = element;
        }
      }
    }
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        if (%_CallFunction(receiver, element, i, array, f)) {
          accumulator[accumulator_length++] = element;
        }
1175
      }
1176
    }
1177
    // End of duplicate.
1178
  }
1179
  %MoveArrayContents(accumulator, result);
1180
  return result;
1181
}
1182 1183 1184


function ArrayForEach(f, receiver) {
1185 1186 1187 1188 1189
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.forEach"]);
  }

1190 1191 1192 1193 1194
  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = ToObject(this);
  var length = TO_UINT32(array.length);

1195
  if (!IS_SPEC_FUNCTION(f)) {
1196 1197
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1198 1199
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1200
  } else if (!IS_SPEC_OBJECT(receiver) && %IsClassicModeFunction(f)) {
1201
    receiver = ToObject(receiver);
1202
  }
1203

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
  if (%DebugCallbackSupportsStepping(f)) {
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(f);
        %_CallFunction(receiver, element, i, array, f);
      }
    }
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        %_CallFunction(receiver, element, i, array, f);
      }
1220
    }
1221
    // End of duplicate.
1222
  }
1223
}
1224 1225 1226 1227 1228


// Executes the function once for each element present in the
// array until it finds one where callback returns true.
function ArraySome(f, receiver) {
1229 1230 1231 1232 1233
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.some"]);
  }

1234 1235 1236 1237 1238
  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = ToObject(this);
  var length = TO_UINT32(array.length);

1239
  if (!IS_SPEC_FUNCTION(f)) {
1240 1241
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1242 1243
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1244
  } else if (!IS_SPEC_OBJECT(receiver) && %IsClassicModeFunction(f)) {
1245
    receiver = ToObject(receiver);
1246
  }
1247

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  if (%DebugCallbackSupportsStepping(f)) {
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(f);
        if (%_CallFunction(receiver, element, i, array, f)) return true;
      }
    }
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        if (%_CallFunction(receiver, element, i, array, f)) return true;
      }
1264
    }
1265
    // End of duplicate.
1266 1267
  }
  return false;
1268
}
1269 1270 1271


function ArrayEvery(f, receiver) {
1272 1273 1274 1275 1276
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.every"]);
  }

1277 1278 1279 1280 1281
  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = ToObject(this);
  var length = TO_UINT32(array.length);

1282
  if (!IS_SPEC_FUNCTION(f)) {
1283 1284
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1285 1286
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1287
  } else if (!IS_SPEC_OBJECT(receiver) && %IsClassicModeFunction(f)) {
1288
    receiver = ToObject(receiver);
1289
  }
1290

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  if (%DebugCallbackSupportsStepping(f)) {
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(f);
        if (!%_CallFunction(receiver, element, i, array, f)) return false;
      }
    }
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        if (!%_CallFunction(receiver, element, i, array, f)) return false;
      }
1307
    }
1308
    // End of duplicate.
1309 1310
  }
  return true;
1311
}
1312 1313

function ArrayMap(f, receiver) {
1314 1315 1316 1317 1318
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.map"]);
  }

1319 1320 1321 1322 1323
  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = ToObject(this);
  var length = TO_UINT32(array.length);

1324
  if (!IS_SPEC_FUNCTION(f)) {
1325 1326
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1327 1328
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1329
  } else if (!IS_SPEC_OBJECT(receiver) && %IsClassicModeFunction(f)) {
1330
    receiver = ToObject(receiver);
1331
  }
1332

1333 1334
  var result = new $Array();
  var accumulator = new InternalArray(length);
1335 1336 1337 1338 1339 1340 1341 1342
  if (%DebugCallbackSupportsStepping(f)) {
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(f);
        accumulator[i] = %_CallFunction(receiver, element, i, array, f);
      }
1343
    }
1344 1345 1346 1347 1348 1349 1350 1351 1352
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (var i = 0; i < length; i++) {
      if (i in array) {
        var element = array[i];
        accumulator[i] = %_CallFunction(receiver, element, i, array, f);
      }
    }
    // End of duplicate.
1353
  }
1354
  %MoveArrayContents(accumulator, result);
1355
  return result;
1356
}
1357 1358 1359


function ArrayIndexOf(element, index) {
1360 1361 1362 1363 1364
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.indexOf"]);
  }

1365 1366
  var length = TO_UINT32(this.length);
  if (length == 0) return -1;
1367
  if (IS_UNDEFINED(index)) {
1368 1369 1370 1371
    index = 0;
  } else {
    index = TO_INTEGER(index);
    // If index is negative, index from the end of the array.
1372 1373 1374 1375 1376
    if (index < 0) {
      index = length + index;
      // If index is still negative, search the entire array.
      if (index < 0) index = 0;
    }
1377
  }
1378 1379
  var min = index;
  var max = length;
lrn@chromium.org's avatar
lrn@chromium.org committed
1380
  if (UseSparseVariant(this, length, IS_ARRAY(this))) {
1381 1382 1383 1384
    var indices = %GetArrayKeys(this, length);
    if (IS_NUMBER(indices)) {
      // It's an interval.
      max = indices;  // Capped by length already.
1385 1386
      // Fall through to loop below.
    } else {
1387
      if (indices.length == 0) return -1;
1388
      // Get all the keys in sorted order.
1389
      var sortedKeys = GetSortedArrayKeys(this, indices);
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
      var n = sortedKeys.length;
      var i = 0;
      while (i < n && sortedKeys[i] < index) i++;
      while (i < n) {
        var key = sortedKeys[i];
        if (!IS_UNDEFINED(key) && this[key] === element) return key;
        i++;
      }
      return -1;
    }
  }
1401
  // Lookup through the array.
1402
  if (!IS_UNDEFINED(element)) {
1403
    for (var i = min; i < max; i++) {
1404 1405 1406 1407
      if (this[i] === element) return i;
    }
    return -1;
  }
1408 1409
  // Lookup through the array.
  for (var i = min; i < max; i++) {
1410 1411
    if (IS_UNDEFINED(this[i]) && i in this) {
      return i;
1412 1413 1414
    }
  }
  return -1;
1415
}
1416 1417 1418


function ArrayLastIndexOf(element, index) {
1419 1420 1421 1422 1423
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.lastIndexOf"]);
  }

1424 1425
  var length = TO_UINT32(this.length);
  if (length == 0) return -1;
1426
  if (%_ArgumentsLength() < 2) {
1427 1428 1429 1430
    index = length - 1;
  } else {
    index = TO_INTEGER(index);
    // If index is negative, index from end of the array.
1431
    if (index < 0) index += length;
1432
    // If index is still negative, do not search the array.
1433
    if (index < 0) return -1;
1434 1435
    else if (index >= length) index = length - 1;
  }
1436 1437
  var min = 0;
  var max = index;
lrn@chromium.org's avatar
lrn@chromium.org committed
1438
  if (UseSparseVariant(this, length, IS_ARRAY(this))) {
1439 1440 1441 1442
    var indices = %GetArrayKeys(this, index + 1);
    if (IS_NUMBER(indices)) {
      // It's an interval.
      max = indices;  // Capped by index already.
1443 1444
      // Fall through to loop below.
    } else {
1445
      if (indices.length == 0) return -1;
1446
      // Get all the keys in sorted order.
1447
      var sortedKeys = GetSortedArrayKeys(this, indices);
1448 1449 1450 1451 1452 1453 1454 1455 1456
      var i = sortedKeys.length - 1;
      while (i >= 0) {
        var key = sortedKeys[i];
        if (!IS_UNDEFINED(key) && this[key] === element) return key;
        i--;
      }
      return -1;
    }
  }
1457
  // Lookup through the array.
1458
  if (!IS_UNDEFINED(element)) {
1459
    for (var i = max; i >= min; i--) {
1460 1461 1462 1463
      if (this[i] === element) return i;
    }
    return -1;
  }
1464
  for (var i = max; i >= min; i--) {
1465 1466
    if (IS_UNDEFINED(this[i]) && i in this) {
      return i;
1467 1468 1469
    }
  }
  return -1;
1470
}
1471 1472


1473
function ArrayReduce(callback, current) {
1474 1475 1476 1477 1478
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.reduce"]);
  }

1479 1480 1481 1482 1483
  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = ToObject(this);
  var length = ToUint32(array.length);

1484
  if (!IS_SPEC_FUNCTION(callback)) {
1485 1486
    throw MakeTypeError('called_non_callable', [callback]);
  }
1487

1488 1489 1490
  var i = 0;
  find_initial: if (%_ArgumentsLength() < 2) {
    for (; i < length; i++) {
1491 1492
      current = array[i];
      if (!IS_UNDEFINED(current) || i in array) {
1493 1494 1495 1496 1497 1498 1499
        i++;
        break find_initial;
      }
    }
    throw MakeTypeError('reduce_no_initial', []);
  }

1500
  var receiver = %GetDefaultReceiver(callback);
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

  if (%DebugCallbackSupportsStepping(callback)) {
    for (; i < length; i++) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(callback);
        current =
          %_CallFunction(receiver, current, element, i, array, callback);
      }
    }
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (; i < length; i++) {
      if (i in array) {
        var element = array[i];
        current =
          %_CallFunction(receiver, current, element, i, array, callback);
      }
1520
    }
1521
    // End of duplicate.
1522 1523 1524 1525 1526
  }
  return current;
}

function ArrayReduceRight(callback, current) {
1527 1528 1529 1530 1531
  if (IS_NULL_OR_UNDEFINED(this) && !IS_UNDETECTABLE(this)) {
    throw MakeTypeError("called_on_null_or_undefined",
                        ["Array.prototype.reduceRight"]);
  }

1532 1533 1534 1535 1536
  // Pull out the length so that side effects are visible before the
  // callback function is checked.
  var array = ToObject(this);
  var length = ToUint32(array.length);

1537
  if (!IS_SPEC_FUNCTION(callback)) {
1538 1539 1540
    throw MakeTypeError('called_non_callable', [callback]);
  }

1541
  var i = length - 1;
1542 1543
  find_initial: if (%_ArgumentsLength() < 2) {
    for (; i >= 0; i--) {
1544 1545
      current = array[i];
      if (!IS_UNDEFINED(current) || i in array) {
1546 1547 1548 1549 1550 1551 1552
        i--;
        break find_initial;
      }
    }
    throw MakeTypeError('reduce_no_initial', []);
  }

1553
  var receiver = %GetDefaultReceiver(callback);
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572

  if (%DebugCallbackSupportsStepping(callback)) {
    for (; i >= 0; i--) {
      if (i in array) {
        var element = array[i];
        // Prepare break slots for debugger step in.
        %DebugPrepareStepInIfStepping(callback);
        current =
          %_CallFunction(receiver, current, element, i, array, callback);
      }
    }
  } else {
    // This is a duplicate of the previous loop sans debug stepping.
    for (; i >= 0; i--) {
      if (i in array) {
        var element = array[i];
        current =
          %_CallFunction(receiver, current, element, i, array, callback);
      }
1573
    }
1574
    // End of duplicate.
1575 1576 1577 1578
  }
  return current;
}

1579 1580 1581 1582
// ES5, 15.4.3.2
function ArrayIsArray(obj) {
  return IS_ARRAY(obj);
}
1583

1584 1585

// -------------------------------------------------------------------
1586

1587 1588
function SetUpArray() {
  %CheckIsBootstrapping();
1589

1590
  // Set up non-enumerable constructor property on the Array.prototype
1591
  // object.
1592
  %SetProperty($Array.prototype, "constructor", $Array, DONT_ENUM);
1593

1594
  // Set up non-enumerable functions on the Array object.
1595 1596 1597 1598
  InstallFunctions($Array, DONT_ENUM, $Array(
    "isArray", ArrayIsArray
  ));

1599 1600
  var specialFunctions = %SpecialArrayFunctions({});

1601
  var getFunction = function(name, jsBuiltin, len) {
1602 1603 1604 1605
    var f = jsBuiltin;
    if (specialFunctions.hasOwnProperty(name)) {
      f = specialFunctions[name];
    }
1606
    if (!IS_UNDEFINED(len)) {
1607 1608 1609
      %FunctionSetLength(f, len);
    }
    return f;
1610
  };
1611

1612
  // Set up non-enumerable functions of the Array.prototype object and
1613
  // set their names.
1614 1615
  // Manipulate the length of some of the functions to meet
  // expectations set by ECMA-262 or Mozilla.
1616
  InstallFunctions($Array.prototype, DONT_ENUM, $Array(
1617 1618 1619 1620 1621
    "toString", getFunction("toString", ArrayToString),
    "toLocaleString", getFunction("toLocaleString", ArrayToLocaleString),
    "join", getFunction("join", ArrayJoin),
    "pop", getFunction("pop", ArrayPop),
    "push", getFunction("push", ArrayPush, 1),
1622
    "concat", getFunction("concat", ArrayConcat, 1),
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    "reverse", getFunction("reverse", ArrayReverse),
    "shift", getFunction("shift", ArrayShift),
    "unshift", getFunction("unshift", ArrayUnshift, 1),
    "slice", getFunction("slice", ArraySlice, 2),
    "splice", getFunction("splice", ArraySplice, 2),
    "sort", getFunction("sort", ArraySort),
    "filter", getFunction("filter", ArrayFilter, 1),
    "forEach", getFunction("forEach", ArrayForEach, 1),
    "some", getFunction("some", ArraySome, 1),
    "every", getFunction("every", ArrayEvery, 1),
    "map", getFunction("map", ArrayMap, 1),
    "indexOf", getFunction("indexOf", ArrayIndexOf, 1),
    "lastIndexOf", getFunction("lastIndexOf", ArrayLastIndexOf, 1),
    "reduce", getFunction("reduce", ArrayReduce, 1),
    "reduceRight", getFunction("reduceRight", ArrayReduceRight, 1)
1638
  ));
1639

1640
  %FinishArrayPrototypeSetup($Array.prototype);
1641 1642

  // The internal Array prototype doesn't need to be fancy, since it's never
1643 1644 1645
  // exposed to user code.
  // Adding only the functions that are actually used.
  SetUpLockedPrototype(InternalArray, $Array(), $Array(
1646
    "concat", getFunction("concat", ArrayConcat),
1647
    "indexOf", getFunction("indexOf", ArrayIndexOf),
1648 1649
    "join", getFunction("join", ArrayJoin),
    "pop", getFunction("pop", ArrayPop),
1650 1651
    "push", getFunction("push", ArrayPush),
    "splice", getFunction("splice", ArraySplice)
1652
  ));
1653 1654 1655 1656 1657 1658

  SetUpLockedPrototype(InternalPackedArray, $Array(), $Array(
    "join", getFunction("join", ArrayJoin),
    "pop", getFunction("pop", ArrayPop),
    "push", getFunction("push", ArrayPush)
  ));
1659
}
1660

1661
SetUpArray();