// 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 {
const kBuiltinNameFindIndex: constexpr string =
    '%TypedArray%.prototype.findIndex';

transitioning macro FindIndexAllElements(implicit context: Context)(
    array: typed_array::AttachedJSTypedArray, predicate: Callable,
    thisArg: JSAny): Number {
  let witness = typed_array::NewAttachedJSTypedArrayWitness(array);
  const length: uintptr = witness.Get().length;

  // 6. Repeat, while k < len
  for (let k: uintptr = 0; k < length; k++) {
    // 6a. Let Pk be ! ToString(𝔽(k)).
    // There is no need to cast ToString to load elements.

    // 6b. Let kValue be ! Get(O, Pk).
    // kValue must be undefined when the buffer is detached.
    let value: JSAny;
    try {
      witness.Recheck() otherwise goto IsDetached;
      value = witness.Load(k);
    } label IsDetached deferred {
      value = Undefined;
    }

    // 6c. Let testResult be ! ToBoolean(? Call(predicate, thisArg, « kValue,
    // 𝔽(k), O »)).
    // TODO(v8:4153): Consider versioning this loop for Smi and non-Smi
    // indices to optimize Convert<Number>(k) for the most common case.
    const indexNumber: Number = Convert<Number>(k);
    const result = Call(
        context, predicate, thisArg, value, indexNumber, witness.GetStable());
    if (ToBoolean(result)) {
      return indexNumber;
    }
  }
  return -1;
}

// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findIndex
transitioning javascript builtin
TypedArrayPrototypeFindIndex(
    js-implicit context: NativeContext, receiver: JSAny)(...arguments): JSAny {
  // arguments[0] = callback
  // arguments[1] = thisArg.
  try {
    const array: JSTypedArray = Cast<JSTypedArray>(receiver)
        otherwise NotTypedArray;
    const uarray = typed_array::EnsureAttached(array) otherwise IsDetached;

    const predicate = Cast<Callable>(arguments[0]) otherwise NotCallable;
    const thisArg = arguments[1];
    return FindIndexAllElements(uarray, predicate, thisArg);
  } label NotCallable deferred {
    ThrowTypeError(MessageTemplate::kCalledNonCallable, arguments[0]);
  } label NotTypedArray deferred {
    ThrowTypeError(MessageTemplate::kNotTypedArray, kBuiltinNameFindIndex);
  } label IsDetached deferred {
    ThrowTypeError(MessageTemplate::kDetachedOperation, kBuiltinNameFindIndex);
  }
}
}