typed-array-reduce.tq 2.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include 'src/builtins/builtins-typed-array-gen.h'

namespace typed_array_reduce {
  const kBuiltinName: constexpr string = '%TypedArray%.prototype.reduce';

  transitioning macro ReduceAllElements(implicit context: Context)(
      array: typed_array::AttachedJSTypedArray, callbackfn: Callable,
12
      initialValue: JSAny | TheHole): JSAny {
13
    let witness = typed_array::NewAttachedJSTypedArrayWitness(array);
14 15 16
    // TODO(v8:4153): Support huge TypedArrays here.
    const length =
        Cast<Smi>(Convert<Number>(witness.Get().length)) otherwise unreachable;
17 18 19 20
    let accumulator = initialValue;
    for (let k: Smi = 0; k < length; k++) {
      // BUG(4895): We should throw on detached buffers rather than simply exit.
      witness.Recheck() otherwise break;
21 22 23 24 25 26 27 28 29 30
      const value: JSAny = witness.Load(k);
      typeswitch (accumulator) {
        case (TheHole): {
          accumulator = value;
        }
        case (accumulatorNotHole: JSAny): {
          accumulator = Call(
              context, callbackfn, Undefined, accumulatorNotHole, value, k,
              witness.GetStable());
        }
31 32
      }
    }
33 34 35 36 37 38 39
    typeswitch (accumulator) {
      case (TheHole): {
        ThrowTypeError(kReduceNoInitial, kBuiltinName);
      }
      case (accumulator: JSAny): {
        return accumulator;
      }
40 41 42 43 44
    }
  }

  // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce
  transitioning javascript builtin
45 46
  TypedArrayPrototypeReduce(js-implicit context: Context, receiver: JSAny)(
      ...arguments): JSAny {
47 48 49 50 51 52 53 54
    // arguments[0] = callback
    // arguments[1] = initialValue.
    try {
      const array: JSTypedArray = Cast<JSTypedArray>(receiver)
          otherwise NotTypedArray;
      const uarray = typed_array::EnsureAttached(array) otherwise IsDetached;

      const callbackfn = Cast<Callable>(arguments[0]) otherwise NotCallable;
55
      const initialValue = arguments.length >= 2 ? arguments[1] : TheHole;
56 57 58 59 60 61 62 63 64 65 66 67 68
      return ReduceAllElements(uarray, callbackfn, initialValue);
    }
    label NotCallable deferred {
      ThrowTypeError(kCalledNonCallable, arguments[0]);
    }
    label NotTypedArray deferred {
      ThrowTypeError(kNotTypedArray, kBuiltinName);
    }
    label IsDetached deferred {
      ThrowTypeError(kDetachedOperation, kBuiltinName);
    }
  }
}