array.js 46.7 KB
Newer Older
1
// Copyright 2012 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
"use strict";

7 8
// This file relies on the fact that the following declarations have been made
// in runtime.js:
9
// var $Array = global.Array;
10 11 12 13 14

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

// Global list of arrays visited during toString, toLocaleString and
// join invocations.
15
var visited_arrays = new InternalArray();
16 17 18 19


// Gets a sorted array of array keys.  Useful for operations on sparse
// arrays.  Dupes have not been removed.
20 21 22 23 24 25 26 27 28
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);
29
      }
30 31 32 33 34
    }
  } else {
    var length = indices.length;
    for (var k = 0; k < length; ++k) {
      var key = indices[k];
35 36 37 38 39 40 41
      if (!IS_UNDEFINED(key)) {
        var e = array[key];
        if (!IS_UNDEFINED(e) || key in array) {
          keys.push(key);
        }
      }
    }
42
    %_CallFunction(keys, function(a, b) { return a - b; }, ArraySort);
43 44 45 46 47
  }
  return keys;
}


48
function SparseJoinWithSeparatorJS(array, len, convert, separator) {
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  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);
}


67 68 69 70 71
// 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;
72

73
  var elements = new InternalArray(keys_length);
74 75
  var elements_length = 0;

76 77 78 79
  for (var i = 0; i < keys_length; i++) {
    var key = keys[i];
    if (key != last_key) {
      var e = array[key];
80 81
      if (!IS_STRING(e)) e = convert(e);
      elements[elements_length++] = e;
82 83 84
      last_key = key;
    }
  }
85
  return %StringBuilderConcat(elements, elements_length, '');
86 87 88
}


89 90 91 92
function UseSparseVariant(array, length, is_array, touched) {
  // Only use the sparse variant on arrays that are likely to be sparse and the
  // number of elements touched in the operation is relatively small compared to
  // the overall size of the array.
93 94
  if (!is_array || length < 1000 || %IsObserved(array) ||
      %HasComplexElements(array)) {
95 96 97 98 99 100 101 102 103
    return false;
  }
  if (!%_IsSmi(length)) {
    return true;
  }
  var elements_threshold = length >> 2;  // No more than 75% holes
  var estimated_elements = %EstimateNumberOfElements(array);
  return (estimated_elements < elements_threshold) &&
    (touched > estimated_elements * 4);
104 105 106 107 108 109 110 111 112 113 114
}


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.
115
    if (!%PushIfAbsent(visited_arrays, array)) return '';
116 117 118 119
  }

  // Attempt to convert the elements.
  try {
120 121
    if (UseSparseVariant(array, length, is_array, length)) {
      %NormalizeElements(array);
122 123 124
      if (separator.length == 0) {
        return SparseJoin(array, length, convert);
      } else {
125
        return SparseJoinWithSeparatorJS(array, length, convert, separator);
126
      }
127 128
    }

129 130 131
    // Fast case for one-element arrays.
    if (length == 1) {
      var e = array[0];
132 133
      if (IS_STRING(e)) return e;
      return convert(e);
134 135
    }

136
    // Construct an array for the elements.
137
    var elements = new InternalArray(length);
138

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

175
    return %StringBuilderJoin(elements, length, separator);
176
  } finally {
177 178 179
    // 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;
180
  }
181
}
182 183


184
function ConvertToString(x) {
185
  // Assumes x is a non-string.
186 187 188
  if (IS_NUMBER(x)) return %_NumberToString(x);
  if (IS_BOOLEAN(x)) return x ? 'true' : 'false';
  return (IS_NULL_OR_UNDEFINED(x)) ? '' : %ToString(%DefaultString(x));
189
}
190 191 192


function ConvertToLocaleString(e) {
193
  if (IS_NULL_OR_UNDEFINED(e)) {
194 195
    return '';
  } else {
196
    // According to ES5, section 15.4.4.3, the toLocaleString conversion
197 198
    // must throw a TypeError if ToObject(e).toLocaleString isn't
    // callable.
199
    var e_obj = ToObject(e);
200
    return %ToString(e_obj.toLocaleString());
201
  }
202
}
203 204 205 206


// This function implements the optimized splice implementation that can use
// special array operations to handle sparse arrays in a sensible fashion.
207
function SparseSlice(array, start_i, del_count, len, deleted_elements) {
208
  // Move deleted elements to a new array (the return value from splice).
209 210 211 212 213 214
  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) {
215
        %AddElement(deleted_elements, i - start_i, current, NONE);
216
      }
217 218 219 220 221
    }
  } else {
    var length = indices.length;
    for (var k = 0; k < length; ++k) {
      var key = indices[k];
222 223 224 225
      if (!IS_UNDEFINED(key)) {
        if (key >= start_i) {
          var current = array[key];
          if (!IS_UNDEFINED(current) || key in array) {
226
            %AddElement(deleted_elements, key - start_i, current, NONE);
227 228 229 230 231
          }
        }
      }
    }
  }
232
}
233 234


235 236
// This function implements the optimized splice implementation that can use
// special array operations to handle sparse arrays in a sensible fashion.
237
function SparseMove(array, start_i, del_count, len, num_additional_args) {
238 239
  // Bail out if no moving is necessary.
  if (num_additional_args === del_count) return;
240
  // Move data to new array.
241 242
  var new_array = new InternalArray(
      // Clamp array length to 2^32-1 to avoid early RangeError.
243
      $min(len - del_count + num_additional_args, 0xffffffff));
244
  var big_indices;
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  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;
      }
    }
    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;
      }
    }
  } else {
    var length = indices.length;
    for (var k = 0; k < length; ++k) {
      var key = indices[k];
      if (!IS_UNDEFINED(key)) {
        if (key < start_i) {
          var current = array[key];
          if (!IS_UNDEFINED(current) || key in array) {
            new_array[key] = current;
          }
        } else if (key >= start_i + del_count) {
          var current = array[key];
          if (!IS_UNDEFINED(current) || key in array) {
273 274 275 276 277 278
            var new_key = key - del_count + num_additional_args;
            new_array[new_key] = current;
            if (new_key > 0xffffffff) {
              big_indices = big_indices || new InternalArray();
              big_indices.push(new_key);
            }
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
  // Add any moved values that aren't elements anymore.
  if (!IS_UNDEFINED(big_indices)) {
    var length = big_indices.length;
    for (var i = 0; i < length; ++i) {
      var key = big_indices[i];
      array[key] = new_array[key];
    }
  }
294 295 296
}


297 298 299 300
// 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) {
301
  var is_array = IS_ARRAY(array);
302 303
  for (var i = 0; i < del_count; i++) {
    var index = start_i + i;
304
    if (HAS_INDEX(array, index, is_array)) {
305
      var current = array[index];
306 307 308
      // The spec requires [[DefineOwnProperty]] here, %AddElement is close
      // enough (in that it ignores the prototype).
      %AddElement(deleted_elements, i, current, NONE);
309
    }
310
  }
311
}
312 313


314
function SimpleMove(array, start_i, del_count, len, num_additional_args) {
315
  var is_array = IS_ARRAY(array);
316
  if (num_additional_args !== del_count) {
317 318 319 320 321 322
    // 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;
323
        if (HAS_INDEX(array, from_index, is_array)) {
324
          array[to_index] = array[from_index];
325 326 327 328 329 330 331 332
        } 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;
333
        if (HAS_INDEX(array, from_index, is_array)) {
334
          array[to_index] = array[from_index];
335 336 337 338 339 340 341 342 343
        } else {
          delete array[to_index];
        }
      }
      for (var i = len; i > len - del_count + num_additional_args; i--) {
        delete array[i - 1];
      }
    }
  }
344
}
345 346 347 348 349 350


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


function ArrayToString() {
351 352 353 354 355 356 357 358 359 360 361
  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;
362
  }
363
  if (!IS_SPEC_FUNCTION(func)) {
364
    return %_CallFunction(array, DefaultObjectToString);
365 366
  }
  return %_CallFunction(array, func);
367
}
368 369 370


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


function ArrayJoin(separator) {
380
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.join");
381

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

390
  var result = %_FastOneByteArrayJoin(array, separator);
391
  if (!IS_UNDEFINED(result)) return result;
392

393 394 395 396 397 398 399 400
  // Fast case for one-element arrays.
  if (length === 1) {
    var e = array[0];
    if (IS_STRING(e)) return e;
    if (IS_NULL_OR_UNDEFINED(e)) return '';
    return NonStringToString(e);
  }

401
  return Join(array, length, separator, ConvertToString);
402
}
403 404


405 406 407 408 409 410 411 412 413 414
function ObservedArrayPop(n) {
  n--;
  var value = this[n];

  try {
    BeginPerformSplice(this);
    delete this[n];
    this.length = n;
  } finally {
    EndPerformSplice(this);
415
    EnqueueSpliceRecord(this, n, [value], 0);
416 417 418 419 420
  }

  return value;
}

421 422 423
// Removes the last element from the array and returns it. See
// ECMA-262, section 15.4.4.6.
function ArrayPop() {
424
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.pop");
425

426 427
  var array = TO_OBJECT_INLINE(this);
  var n = TO_UINT32(array.length);
428
  if (n == 0) {
429
    array.length = n;
430 431
    return;
  }
432

433 434
  if (%IsObserved(array))
    return ObservedArrayPop.call(array, n);
435

436
  n--;
437 438 439
  var value = array[n];
  Delete(array, ToName(n), true);
  array.length = n;
440
  return value;
441
}
442 443


444 445 446 447 448 449 450 451 452
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);
    }
453 454
    var new_length = n + m;
    this.length = new_length;
455 456
  } finally {
    EndPerformSplice(this);
457
    EnqueueSpliceRecord(this, n, [], m);
458 459
  }

460
  return new_length;
461 462
}

463 464 465
// 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() {
466
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.push");
467

468 469 470
  if (%IsObserved(this))
    return ObservedArrayPush.apply(this, arguments);

471 472 473 474
  var array = TO_OBJECT_INLINE(this);
  var n = TO_UINT32(array.length);
  var m = %_ArgumentsLength();

475
  for (var i = 0; i < m; i++) {
476
    array[i+n] = %_Arguments(i);
477
  }
478 479

  var new_length = n + m;
480
  array.length = new_length;
481
  return new_length;
482
}
483 484


485 486 487
// 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.
488
function ArrayConcatJS(arg1) {  // length == 1
489
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.concat");
490

491
  var array = ToObject(this);
492
  var arg_count = %_ArgumentsLength();
493
  var arrays = new InternalArray(1 + arg_count);
494
  arrays[0] = array;
495 496
  for (var i = 0; i < arg_count; i++) {
    arrays[i + 1] = %_Arguments(i);
497 498
  }

499
  return %ArrayConcat(arrays);
500
}
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516


// 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;
517
      while (keys[--high_counter] == j) { }
518 519 520 521
      low = j_complement;
    }
    if (j_complement >= i) {
      low = i;
522
      while (keys[++low_counter] == i) { }
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
      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() {
548
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.reverse");
549

550
  var array = TO_OBJECT_INLINE(this);
551
  var len = TO_UINT32(array.length);
552

553 554 555
  if (UseSparseVariant(array, len, IS_ARRAY(array), len)) {
    %NormalizeElements(array);
    SparseReverse(array, len);
556
    return array;
557 558
  }

559
  var j = len - 1;
560
  for (var i = 0; i < j; i++, j--) {
561 562 563 564 565 566
    var current_i = array[i];
    if (!IS_UNDEFINED(current_i) || i in array) {
      var current_j = array[j];
      if (!IS_UNDEFINED(current_j) || j in array) {
        array[i] = current_j;
        array[j] = current_i;
567
      } else {
568 569
        array[j] = current_i;
        delete array[i];
570 571
      }
    } else {
572 573 574 575
      var current_j = array[j];
      if (!IS_UNDEFINED(current_j) || j in array) {
        array[i] = current_j;
        delete array[j];
576 577 578
      }
    }
  }
579
  return array;
580
}
581 582


583 584 585 586 587 588 589 590 591
function ObservedArrayShift(len) {
  var first = this[0];

  try {
    BeginPerformSplice(this);
    SimpleMove(this, 0, 1, len, 0);
    this.length = len - 1;
  } finally {
    EndPerformSplice(this);
592
    EnqueueSpliceRecord(this, 0, [first], 0);
593 594 595 596 597
  }

  return first;
}

598
function ArrayShift() {
599
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.shift");
600

601 602
  var array = TO_OBJECT_INLINE(this);
  var len = TO_UINT32(array.length);
603

604
  if (len === 0) {
605
    array.length = 0;
606 607
    return;
  }
608

609
  if (ObjectIsSealed(array)) {
610 611 612 613
    throw MakeTypeError("array_functions_change_sealed",
                        ["Array.prototype.shift"]);
  }

614 615
  if (%IsObserved(array))
    return ObservedArrayShift.call(array, len);
616

617
  var first = array[0];
618

619 620
  if (UseSparseVariant(array, len, IS_ARRAY(array), len)) {
    SparseMove(array, 0, 1, len, 0);
621 622 623
  } else {
    SimpleMove(array, 0, 1, len, 0);
  }
624

625
  array.length = len - 1;
626

627
  return first;
628
}
629

630 631 632 633 634 635 636 637 638 639
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);
    }
640 641
    var new_length = len + num_arguments;
    this.length = new_length;
642 643
  } finally {
    EndPerformSplice(this);
644
    EnqueueSpliceRecord(this, 0, [], num_arguments);
645 646
  }

647
  return new_length;
648
}
649 650

function ArrayUnshift(arg1) {  // length == 1
651
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.unshift");
652

653 654 655
  if (%IsObserved(this))
    return ObservedArrayUnshift.apply(this, arguments);

656 657 658
  var array = TO_OBJECT_INLINE(this);
  var len = TO_UINT32(array.length);
  var num_arguments = %_ArgumentsLength();
659

660 661 662
  if (len > 0 && UseSparseVariant(array, len, IS_ARRAY(array), len) &&
     !ObjectIsSealed(array)) {
    SparseMove(array, 0, 0, len, num_arguments);
663 664 665 666
  } else {
    SimpleMove(array, 0, 0, len, num_arguments);
  }

667
  for (var i = 0; i < num_arguments; i++) {
668
    array[i] = %_Arguments(i);
669
  }
670

671
  var new_length = len + num_arguments;
672
  array.length = new_length;
673
  return new_length;
674
}
675 676 677


function ArraySlice(start, end) {
678
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.slice");
679

680 681
  var array = TO_OBJECT_INLINE(this);
  var len = TO_UINT32(array.length);
682 683
  var start_i = TO_INTEGER(start);
  var end_i = len;
684

685
  if (!IS_UNDEFINED(end)) end_i = TO_INTEGER(end);
686

687 688 689 690 691 692
  if (start_i < 0) {
    start_i += len;
    if (start_i < 0) start_i = 0;
  } else {
    if (start_i > len) start_i = len;
  }
693

694 695 696 697 698 699
  if (end_i < 0) {
    end_i += len;
    if (end_i < 0) end_i = 0;
  } else {
    if (end_i > len) end_i = len;
  }
700

701
  var result = [];
702 703 704

  if (end_i < start_i) return result;

705 706 707
  if (UseSparseVariant(array, len, IS_ARRAY(array), end_i - start_i)) {
    %NormalizeElements(array);
    %NormalizeElements(result);
708
    SparseSlice(array, start_i, end_i - start_i, len, result);
709
  } else {
710
    SimpleSlice(array, start_i, end_i - start_i, len, result);
711 712
  }

713
  result.length = end_i - start_i;
714

715
  return result;
716
}
717 718


719
function ComputeSpliceStartIndex(start_i, len) {
720 721
  if (start_i < 0) {
    start_i += len;
722
    return start_i < 0 ? 0 : start_i;
723
  }
724

725 726 727 728 729
  return start_i > len ? len : start_i;
}


function ComputeSpliceDeleteCount(delete_count, num_arguments, len, start_i) {
730
  // SpiderMonkey, TraceMonkey and JSC treat the case where no delete count is
731 732
  // given as a request to delete all the elements from the start.
  // And it differs from the case of undefined delete count.
733 734 735
  // This does not follow ECMA-262, but we do the same for
  // compatibility.
  var del_count = 0;
736 737 738 739 740 741 742 743 744 745 746 747
  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;
}
748

749 750 751 752 753 754 755

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);
756 757
  var deleted_elements = [];
  deleted_elements.length = del_count;
758 759 760 761
  var num_elements_to_add = num_arguments > 2 ? num_arguments - 2 : 0;

  try {
    BeginPerformSplice(this);
762

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    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);
    }
784
  }
785

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


function ArraySplice(start, delete_count) {
792
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.splice");
793

794 795 796 797
  if (%IsObserved(this))
    return ObservedArraySplice.apply(this, arguments);

  var num_arguments = %_ArgumentsLength();
798 799
  var array = TO_OBJECT_INLINE(this);
  var len = TO_UINT32(array.length);
800 801 802 803 804 805 806
  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;

807
  if (del_count != num_elements_to_add && ObjectIsSealed(array)) {
808 809
    throw MakeTypeError("array_functions_change_sealed",
                        ["Array.prototype.splice"]);
810
  } else if (del_count > 0 && ObjectIsFrozen(array)) {
811 812 813 814
    throw MakeTypeError("array_functions_on_frozen",
                        ["Array.prototype.splice"]);
  }

815 816 817 818 819
  var changed_elements = del_count;
  if (num_elements_to_add != del_count) {
    // If the slice needs to do a actually move elements after the insertion
    // point, then include those in the estimate of changed elements.
    changed_elements += len - start_i - del_count;
820
  }
821 822 823
  if (UseSparseVariant(array, len, IS_ARRAY(array), changed_elements)) {
    %NormalizeElements(array);
    %NormalizeElements(deleted_elements);
824 825
    SparseSlice(array, start_i, del_count, len, deleted_elements);
    SparseMove(array, start_i, del_count, len, num_elements_to_add);
826 827 828 829
  } else {
    SimpleSlice(array, start_i, del_count, len, deleted_elements);
    SimpleMove(array, start_i, del_count, len, num_elements_to_add);
  }
830

831 832 833 834 835 836
  // 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) {
837
    array[i++] = %_Arguments(arguments_index++);
838
  }
839
  array.length = len - del_count + num_elements_to_add;
840

841 842
  // Return the deleted elements.
  return deleted_elements;
843
}
844 845 846


function ArraySort(comparefn) {
847
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.sort");
848

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

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

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

882 883 884 885
  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);
886 887
    for (var i = from + 1, j = 0; i < to - 1; i += increment, j++) {
      t_array[j] = [i, a[i]];
888
    }
889 890 891
    %_CallFunction(t_array, function(a, b) {
      return %_CallFunction(receiver, a[1], b[1], comparefn);
    }, ArraySort);
892 893 894 895
    var third_index = t_array[t_array.length >> 1][0];
    return third_index;
  }

896
  var QuickSort = function QuickSort(a, from, to) {
897
    var third_index = 0;
898 899 900 901 902
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from <= 10) {
        InsertionSort(a, from, to);
        return;
903
      }
904 905 906 907 908
      if (to - from > 1000) {
        third_index = GetThirdIndex(a, from, to);
      } else {
        third_index = from + ((to - from) >> 1);
      }
909 910 911
      // Find a pivot as the median of first, last and middle element.
      var v0 = a[from];
      var v1 = a[to - 1];
912
      var v2 = a[third_index];
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 939 940 941 942
      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.
943
      a[third_index] = a[low_end];
944 945 946 947 948 949 950
      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);
951
        if (order < 0) {
952 953
          a[i] = a[low_end];
          a[low_end] = element;
954
          low_end++;
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
        } 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++;
          }
970
        }
971
      }
972 973 974 975 976 977 978
      if (to - high_start < low_end - from) {
        QuickSort(a, high_start, to);
        to = low_end;
      } else {
        QuickSort(a, from, low_end);
        from = high_start;
      }
979
    }
980
  };
981

982 983
  // 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
984
  // of a prototype property.
985
  var CopyFromPrototype = function CopyFromPrototype(obj, length) {
986
    var max = 0;
arv's avatar
arv committed
987
    for (var proto = %_GetPrototype(obj); proto; proto = %_GetPrototype(proto)) {
988
      var indices = %GetArrayKeys(proto, length);
989 990 991 992
      if (IS_NUMBER(indices)) {
        // It's an interval.
        var proto_length = indices;
        for (var i = 0; i < proto_length; i++) {
993
          if (!HAS_OWN_PROPERTY(obj, i) && HAS_OWN_PROPERTY(proto, i)) {
994 995
            obj[i] = proto[i];
            if (i >= max) { max = i + 1; }
996
          }
997 998 999 1000
        }
      } else {
        for (var i = 0; i < indices.length; i++) {
          var index = indices[i];
1001 1002
          if (!IS_UNDEFINED(index) && !HAS_OWN_PROPERTY(obj, index)
              && HAS_OWN_PROPERTY(proto, index)) {
1003 1004
            obj[index] = proto[index];
            if (index >= max) { max = index + 1; }
1005 1006 1007 1008 1009
          }
        }
      }
    }
    return max;
1010
  };
1011 1012 1013 1014

  // 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.
1015
  var ShadowPrototypeElements = function(obj, from, to) {
arv's avatar
arv committed
1016
    for (var proto = %_GetPrototype(obj); proto; proto = %_GetPrototype(proto)) {
1017
      var indices = %GetArrayKeys(proto, to);
1018 1019 1020 1021
      if (IS_NUMBER(indices)) {
        // It's an interval.
        var proto_length = indices;
        for (var i = from; i < proto_length; i++) {
1022
          if (HAS_OWN_PROPERTY(proto, i)) {
1023
            obj[i] = UNDEFINED;
1024
          }
1025 1026 1027 1028 1029
        }
      } else {
        for (var i = 0; i < indices.length; i++) {
          var index = indices[i];
          if (!IS_UNDEFINED(index) && from <= index &&
1030
              HAS_OWN_PROPERTY(proto, index)) {
1031
            obj[index] = UNDEFINED;
1032 1033 1034 1035
          }
        }
      }
    }
1036
  };
1037

1038
  var SafeRemoveArrayHoles = function SafeRemoveArrayHoles(obj) {
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    // 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.
1053
      if (!HAS_OWN_PROPERTY(obj, first_undefined)) {
1054 1055 1056 1057 1058 1059
        num_holes++;
      }

      // Find last defined element.
      while (first_undefined < last_defined &&
             IS_UNDEFINED(obj[last_defined])) {
1060
        if (!HAS_OWN_PROPERTY(obj, last_defined)) {
1061 1062 1063 1064 1065 1066 1067
          num_holes++;
        }
        last_defined--;
      }
      if (first_undefined < last_defined) {
        // Fill in hole or undefined.
        obj[first_undefined] = obj[last_defined];
1068
        obj[last_defined] = UNDEFINED;
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
      }
    }
    // 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++) {
1080
      obj[i] = UNDEFINED;
1081 1082 1083
    }
    for (i = length - num_holes; i < length; i++) {
      // For compatability with Webkit, do not expose elements in the prototype.
arv's avatar
arv committed
1084
      if (i in %_GetPrototype(obj)) {
1085
        obj[i] = UNDEFINED;
1086 1087 1088 1089 1090 1091 1092
      } else {
        delete obj[i];
      }
    }

    // Return the number of defined elements.
    return first_undefined;
1093
  };
1094

1095
  var length = TO_UINT32(this.length);
1096
  if (length < 2) return this;
1097

1098 1099 1100 1101 1102 1103
  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
1104
    // own elements. This is not very efficient, but sorting with
1105 1106 1107 1108 1109 1110 1111
    // 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);
  }

1112 1113
  // %RemoveArrayHoles returns -1 if fast removal is not supported.
  var num_non_undefined = %RemoveArrayHoles(this, length);
1114

1115
  if (num_non_undefined == -1) {
1116 1117 1118
    // 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.
1119 1120
    num_non_undefined = SafeRemoveArrayHoles(this);
  }
1121

1122
  QuickSort(this, 0, num_non_undefined);
1123

1124 1125 1126 1127 1128 1129
  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);
  }

1130
  return this;
1131
}
1132 1133 1134 1135 1136 1137


// 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) {
1138
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.filter");
1139

1140 1141 1142 1143 1144
  // 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);

1145
  if (!IS_SPEC_FUNCTION(f)) {
1146 1147
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1148
  var needs_wrapper = false;
1149 1150
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1151 1152
  } else {
    needs_wrapper = SHOULD_CREATE_WRAPPER(f, receiver);
1153
  }
1154

1155 1156 1157
  var result = new $Array();
  var accumulator = new InternalArray();
  var accumulator_length = 0;
1158
  var is_array = IS_ARRAY(array);
1159
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(f);
1160
  for (var i = 0; i < length; i++) {
1161
    if (HAS_INDEX(array, i, is_array)) {
1162 1163 1164
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(f);
1165 1166
      var new_receiver = needs_wrapper ? ToObject(receiver) : receiver;
      if (%_CallFunction(new_receiver, element, i, array, f)) {
1167
        accumulator[accumulator_length++] = element;
1168
      }
1169 1170
    }
  }
1171
  %MoveArrayContents(accumulator, result);
1172
  return result;
1173
}
1174 1175 1176


function ArrayForEach(f, receiver) {
1177
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.forEach");
1178

1179 1180 1181 1182 1183
  // 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);

1184
  if (!IS_SPEC_FUNCTION(f)) {
1185 1186
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1187
  var needs_wrapper = false;
1188 1189
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1190 1191
  } else {
    needs_wrapper = SHOULD_CREATE_WRAPPER(f, receiver);
1192
  }
1193

1194
  var is_array = IS_ARRAY(array);
1195
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(f);
1196
  for (var i = 0; i < length; i++) {
1197
    if (HAS_INDEX(array, i, is_array)) {
1198 1199 1200
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(f);
1201 1202
      var new_receiver = needs_wrapper ? ToObject(receiver) : receiver;
      %_CallFunction(new_receiver, element, i, array, f);
1203 1204
    }
  }
1205
}
1206 1207 1208 1209 1210


// Executes the function once for each element present in the
// array until it finds one where callback returns true.
function ArraySome(f, receiver) {
1211
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.some");
1212

1213 1214 1215 1216 1217
  // 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);

1218
  if (!IS_SPEC_FUNCTION(f)) {
1219 1220
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1221
  var needs_wrapper = false;
1222 1223
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1224 1225
  } else {
    needs_wrapper = SHOULD_CREATE_WRAPPER(f, receiver);
1226
  }
1227

1228
  var is_array = IS_ARRAY(array);
1229
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(f);
1230
  for (var i = 0; i < length; i++) {
1231
    if (HAS_INDEX(array, i, is_array)) {
1232 1233 1234
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(f);
1235 1236
      var new_receiver = needs_wrapper ? ToObject(receiver) : receiver;
      if (%_CallFunction(new_receiver, element, i, array, f)) return true;
1237
    }
1238 1239
  }
  return false;
1240
}
1241 1242 1243


function ArrayEvery(f, receiver) {
1244
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.every");
1245

1246 1247 1248 1249 1250
  // 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);

1251
  if (!IS_SPEC_FUNCTION(f)) {
1252 1253
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1254
  var needs_wrapper = false;
1255 1256
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1257 1258
  } else {
    needs_wrapper = SHOULD_CREATE_WRAPPER(f, receiver);
1259
  }
1260

1261
  var is_array = IS_ARRAY(array);
1262
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(f);
1263
  for (var i = 0; i < length; i++) {
1264
    if (HAS_INDEX(array, i, is_array)) {
1265 1266 1267
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(f);
1268 1269
      var new_receiver = needs_wrapper ? ToObject(receiver) : receiver;
      if (!%_CallFunction(new_receiver, element, i, array, f)) return false;
1270
    }
1271 1272
  }
  return true;
1273
}
1274 1275

function ArrayMap(f, receiver) {
1276
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");
1277

1278 1279 1280 1281 1282
  // 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);

1283
  if (!IS_SPEC_FUNCTION(f)) {
1284 1285
    throw MakeTypeError('called_non_callable', [ f ]);
  }
1286
  var needs_wrapper = false;
1287 1288
  if (IS_NULL_OR_UNDEFINED(receiver)) {
    receiver = %GetDefaultReceiver(f) || receiver;
1289 1290
  } else {
    needs_wrapper = SHOULD_CREATE_WRAPPER(f, receiver);
1291
  }
1292

1293 1294
  var result = new $Array();
  var accumulator = new InternalArray(length);
1295
  var is_array = IS_ARRAY(array);
1296
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(f);
1297
  for (var i = 0; i < length; i++) {
1298
    if (HAS_INDEX(array, i, is_array)) {
1299 1300 1301
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(f);
1302 1303
      var new_receiver = needs_wrapper ? ToObject(receiver) : receiver;
      accumulator[i] = %_CallFunction(new_receiver, element, i, array, f);
1304 1305
    }
  }
1306
  %MoveArrayContents(accumulator, result);
1307
  return result;
1308
}
1309 1310 1311


function ArrayIndexOf(element, index) {
1312
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.indexOf");
1313

1314 1315
  var length = TO_UINT32(this.length);
  if (length == 0) return -1;
1316
  if (IS_UNDEFINED(index)) {
1317 1318 1319 1320
    index = 0;
  } else {
    index = TO_INTEGER(index);
    // If index is negative, index from the end of the array.
1321 1322 1323 1324 1325
    if (index < 0) {
      index = length + index;
      // If index is still negative, search the entire array.
      if (index < 0) index = 0;
    }
1326
  }
1327 1328
  var min = index;
  var max = length;
1329 1330
  if (UseSparseVariant(this, length, IS_ARRAY(this), max - min)) {
    %NormalizeElements(this);
1331 1332 1333 1334
    var indices = %GetArrayKeys(this, length);
    if (IS_NUMBER(indices)) {
      // It's an interval.
      max = indices;  // Capped by length already.
1335 1336
      // Fall through to loop below.
    } else {
1337
      if (indices.length == 0) return -1;
1338
      // Get all the keys in sorted order.
1339
      var sortedKeys = GetSortedArrayKeys(this, indices);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
      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;
    }
  }
1351
  // Lookup through the array.
1352
  if (!IS_UNDEFINED(element)) {
1353
    for (var i = min; i < max; i++) {
1354 1355 1356 1357
      if (this[i] === element) return i;
    }
    return -1;
  }
1358 1359
  // Lookup through the array.
  for (var i = min; i < max; i++) {
1360 1361
    if (IS_UNDEFINED(this[i]) && i in this) {
      return i;
1362 1363 1364
    }
  }
  return -1;
1365
}
1366 1367 1368


function ArrayLastIndexOf(element, index) {
1369
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.lastIndexOf");
1370

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


1421
function ArrayReduce(callback, current) {
1422
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.reduce");
1423

1424 1425 1426 1427 1428
  // 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);

1429
  if (!IS_SPEC_FUNCTION(callback)) {
1430 1431
    throw MakeTypeError('called_non_callable', [callback]);
  }
1432

1433
  var is_array = IS_ARRAY(array);
1434 1435 1436
  var i = 0;
  find_initial: if (%_ArgumentsLength() < 2) {
    for (; i < length; i++) {
1437
      if (HAS_INDEX(array, i, is_array)) {
1438
        current = array[i++];
1439 1440 1441 1442 1443 1444
        break find_initial;
      }
    }
    throw MakeTypeError('reduce_no_initial', []);
  }

1445
  var receiver = %GetDefaultReceiver(callback);
1446
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(callback);
1447
  for (; i < length; i++) {
1448
    if (HAS_INDEX(array, i, is_array)) {
1449 1450 1451 1452
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(callback);
      current = %_CallFunction(receiver, current, element, i, array, callback);
1453
    }
1454 1455 1456 1457 1458
  }
  return current;
}

function ArrayReduceRight(callback, current) {
1459
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.reduceRight");
1460

1461 1462 1463 1464 1465
  // 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);

1466
  if (!IS_SPEC_FUNCTION(callback)) {
1467 1468 1469
    throw MakeTypeError('called_non_callable', [callback]);
  }

1470
  var is_array = IS_ARRAY(array);
1471
  var i = length - 1;
1472 1473
  find_initial: if (%_ArgumentsLength() < 2) {
    for (; i >= 0; i--) {
1474
      if (HAS_INDEX(array, i, is_array)) {
1475
        current = array[i--];
1476 1477 1478 1479 1480 1481
        break find_initial;
      }
    }
    throw MakeTypeError('reduce_no_initial', []);
  }

1482
  var receiver = %GetDefaultReceiver(callback);
1483
  var stepping = DEBUG_IS_ACTIVE && %DebugCallbackSupportsStepping(callback);
1484
  for (; i >= 0; i--) {
1485
    if (HAS_INDEX(array, i, is_array)) {
1486 1487 1488 1489
      var element = array[i];
      // Prepare break slots for debugger step in.
      if (stepping) %DebugPrepareStepInIfStepping(callback);
      current = %_CallFunction(receiver, current, element, i, array, callback);
1490 1491 1492 1493 1494
    }
  }
  return current;
}

1495 1496 1497 1498
// ES5, 15.4.3.2
function ArrayIsArray(obj) {
  return IS_ARRAY(obj);
}
1499

1500 1501

// -------------------------------------------------------------------
1502

1503 1504
function SetUpArray() {
  %CheckIsBootstrapping();
1505

1506
  // Set up non-enumerable constructor property on the Array.prototype
1507
  // object.
1508
  %AddNamedProperty($Array.prototype, "constructor", $Array, DONT_ENUM);
1509

1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
  // Set up unscopable properties on the Array.prototype object.
  var unscopables = {
    __proto__: null,
    copyWithin: true,
    entries: true,
    fill: true,
    find: true,
    findIndex: true,
    keys: true,
  };
  %AddNamedProperty($Array.prototype, symbolUnscopables, unscopables,
      DONT_ENUM | READ_ONLY);

1523
  // Set up non-enumerable functions on the Array object.
1524 1525 1526 1527
  InstallFunctions($Array, DONT_ENUM, $Array(
    "isArray", ArrayIsArray
  ));

1528
  var specialFunctions = %SpecialArrayFunctions();
1529

1530
  var getFunction = function(name, jsBuiltin, len) {
1531 1532 1533 1534
    var f = jsBuiltin;
    if (specialFunctions.hasOwnProperty(name)) {
      f = specialFunctions[name];
    }
1535
    if (!IS_UNDEFINED(len)) {
1536 1537 1538
      %FunctionSetLength(f, len);
    }
    return f;
1539
  };
1540

1541
  // Set up non-enumerable functions of the Array.prototype object and
1542
  // set their names.
1543 1544
  // Manipulate the length of some of the functions to meet
  // expectations set by ECMA-262 or Mozilla.
1545
  InstallFunctions($Array.prototype, DONT_ENUM, $Array(
1546 1547 1548 1549 1550
    "toString", getFunction("toString", ArrayToString),
    "toLocaleString", getFunction("toLocaleString", ArrayToLocaleString),
    "join", getFunction("join", ArrayJoin),
    "pop", getFunction("pop", ArrayPop),
    "push", getFunction("push", ArrayPush, 1),
1551
    "concat", getFunction("concat", ArrayConcatJS, 1),
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    "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)
1567
  ));
1568

1569
  %FinishArrayPrototypeSetup($Array.prototype);
1570 1571

  // The internal Array prototype doesn't need to be fancy, since it's never
1572 1573 1574
  // exposed to user code.
  // Adding only the functions that are actually used.
  SetUpLockedPrototype(InternalArray, $Array(), $Array(
1575
    "concat", getFunction("concat", ArrayConcatJS),
1576
    "indexOf", getFunction("indexOf", ArrayIndexOf),
1577 1578
    "join", getFunction("join", ArrayJoin),
    "pop", getFunction("pop", ArrayPop),
1579 1580
    "push", getFunction("push", ArrayPush),
    "splice", getFunction("splice", ArraySplice)
1581
  ));
1582 1583 1584 1585 1586 1587

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

1590
SetUpArray();