blob: 72237138924078e09fcbb137e3dd7e26aea97fad [file] [log] [blame]
// Copyright 2021 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 kBuiltinNameFindLastIndex: constexpr string =
'%TypedArray%.prototype.findIndexLast';
// https://tc39.es/proposal-array-find-from-last/index.html#sec-%typedarray%.prototype.findlastindex
transitioning macro FindLastIndexAllElements(
implicit context: Context)(
attachedArrayAndLength: typed_array::AttachedJSTypedArrayAndLength,
predicate: Callable, thisArg: JSAny): Number {
let witness =
typed_array::NewAttachedJSTypedArrayWitness(attachedArrayAndLength.array);
// 5. Let k be len - 1.
// 6. Repeat, while k ≥ 0
for (let k: uintptr = attachedArrayAndLength.length; k-- > 0;) {
// 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 was detached.
let value: JSAny;
try {
witness.RecheckIndex(k) otherwise goto IsDetachedOrOutOfBounds;
value = witness.Load(k);
} label IsDetachedOrOutOfBounds 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());
// 6d. If testResult is true, return 𝔽(k).
if (ToBoolean(result)) {
return indexNumber;
}
// 6e. Set k to k - 1. (done by the loop).
}
// 7. Return -1𝔽.
return -1;
}
// https://tc39.es/proposal-array-find-from-last/index.html#sec-%typedarray%.prototype.findlastindex
transitioning javascript builtin TypedArrayPrototypeFindLastIndex(
js-implicit context: NativeContext, receiver: JSAny)(...arguments): JSAny {
// arguments[0] = predicate
// arguments[1] = thisArg
try {
// 1. Let O be the this value.
// 2. Perform ? ValidateTypedArray(O).
// 3. Let len be IntegerIndexedObjectLength(O).
const array: JSTypedArray = Cast<JSTypedArray>(receiver)
otherwise NotTypedArray;
const attachedArrayAndLength = EnsureAttachedAndReadLength(array)
otherwise IsDetachedOrOutOfBounds;
// 4. If IsCallable(predicate) is false, throw a TypeError exception.
const predicate = Cast<Callable>(arguments[0]) otherwise NotCallable;
const thisArg = arguments[1];
return FindLastIndexAllElements(attachedArrayAndLength, predicate, thisArg);
} label NotCallable deferred {
ThrowCalledNonCallable(arguments[0]);
} label NotTypedArray deferred {
ThrowTypeError(MessageTemplate::kNotTypedArray, kBuiltinNameFindLastIndex);
} label IsDetachedOrOutOfBounds deferred {
ThrowTypeError(
MessageTemplate::kDetachedOperation, kBuiltinNameFindLastIndex);
}
}
}