Copy as Markdown

Other Tools

/* THIS FILE IS AUTOGENERATED FROM ONNX.webidl BY Codegen.py - DO NOT EDIT */
#include <type_traits>
#include "AtomList.h"
#include "InferenceSession.h"
#include "MainThreadUtils.h"
#include "ONNXBinding.h"
#include "WrapperFactory.h"
#include "XrayWrapper.h"
#include "js/Array.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.h"
#include "js/ForOfIterator.h"
#include "js/MapAndSet.h"
#include "js/Object.h"
#include "js/PropertyAndElement.h"
#include "js/PropertyDescriptor.h"
#include "js/experimental/JitInfo.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "mozilla/Atomics.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/InferenceSession.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/Record.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SimpleGlobalObject.h"
#include "mozilla/dom/Tensor.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsThreadUtils.h"
namespace mozilla {
namespace dom {
namespace binding_detail {}; // Just to make sure it's known as a namespace
using namespace mozilla::dom::binding_detail;
namespace binding_detail {
constexpr nsLiteralCString EnumStrings<TensorDataLocation>::Values[6];
} // namespace binding_detail
bool
ToJSValue(JSContext* aCx, TensorDataLocation aArgument, JS::MutableHandle<JS::Value> aValue)
{
MOZ_ASSERT(uint32_t(aArgument) < std::size(binding_detail::EnumStrings<TensorDataLocation>::Values));
JSString* resultStr =
JS_NewStringCopyN(aCx, binding_detail::EnumStrings<TensorDataLocation>::Values[uint32_t(aArgument)].BeginReading(),
binding_detail::EnumStrings<TensorDataLocation>::Values[uint32_t(aArgument)].Length());
if (!resultStr) {
return false;
}
aValue.setString(resultStr);
return true;
}
bool
ArrayBufferViewOrAnySequence::TrySetToArrayBufferView(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
RootedSpiderMonkeyInterface<ArrayBufferView>& memberSlot = RawSetAsArrayBufferView(cx);
if (!memberSlot.Init(&value.toObject())) {
DestroyArrayBufferView();
tryNext = true;
return true;
}
if (JS::IsArrayBufferViewShared(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
if (JS::IsLargeArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
if (JS::IsResizableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
if (JS::IsImmutableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
}
return true;
}
bool
ArrayBufferViewOrAnySequence::TrySetToArrayBufferView(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl);
}
bool
ArrayBufferViewOrAnySequence::TrySetToAnySequence(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::RootedAutoSequence<JS::Value>& memberSlot = RawSetAsAnySequence(cx);
JS::ForOfIterator iter(cx);
if (!iter.init(value, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
DestroyAnySequence();
tryNext = true;
return true;
}
binding_detail::AutoSequence<JS::Value> &arr = memberSlot;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
JS::Value* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Value& slot = *slotPtr;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#pragma clang diagnostic ignored "-Wunreachable-code-return"
#endif // __clang__
if ((passedToJSImpl) && !CallerSubsumes(temp)) {
cx.ThrowErrorMessage<MSG_PERMISSION_DENIED_TO_PASS_ARG>("element of sequence<any> branch of (ArrayBufferView or sequence<any>)");
return false;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
slot = temp;
}
}
return true;
}
bool
ArrayBufferViewOrAnySequence::TrySetToAnySequence(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToAnySequence(cx, value, tryNext, passedToJSImpl);
}
bool
ArrayBufferViewOrAnySequence::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
MOZ_ASSERT(mType == eUninitialized);
bool done = false, failed = false, tryNext;
if (value.isObject()) {
done = (failed = !TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl)) || !tryNext;
if (!done) {
done = (failed = !TrySetToAnySequence(cx, value, tryNext, passedToJSImpl)) || !tryNext;
}
}
if (failed) {
return false;
}
if (!done) {
cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "ArrayBufferView, sequence<any>");
return false;
}
return true;
}
bool
ArrayBufferViewOrAnySequence::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return Init(cx, value, sourceDescription, passedToJSImpl);
}
bool
ArrayBufferViewOrAnySequence::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
switch (mType) {
case eUninitialized: {
return false;
}
case eArrayBufferView: {
rval.setObject(*mValue.mArrayBufferView.Value().Obj());
if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
return false;
}
return true;
}
case eAnySequence: {
uint32_t length = mValue.mAnySequence.Value().Length();
JS::Rooted<JSObject*> returnArray(cx, JS::NewArrayObject(cx, length));
if (!returnArray) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
// Control block to let us common up the JS_DefineElement calls when there
// are different ways to succeed at wrapping the object.
do {
JS::ExposeValueToActiveJS(mValue.mAnySequence.Value()[sequenceIdx0]);
tmp.set(mValue.mAnySequence.Value()[sequenceIdx0]);
if (!MaybeWrapValue(cx, &tmp)) {
return false;
}
break;
} while (false);
if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
rval.setObject(*returnArray);
return true;
}
default: {
return false;
}
}
}
OwningArrayBufferViewOrAnySequence::OwningArrayBufferViewOrAnySequence(OwningArrayBufferViewOrAnySequence&& aOther)
: mType(eUninitialized)
{
switch (aOther.mType) {
case eUninitialized: {
MOZ_ASSERT(mType == eUninitialized,
"We need to destroy ourselves?");
break;
}
case eArrayBufferView: {
mType = eArrayBufferView;
mValue.mArrayBufferView.SetValue(std::move(aOther.mValue.mArrayBufferView.Value()));
break;
}
case eAnySequence: {
mType = eAnySequence;
mValue.mAnySequence.SetValue(std::move(aOther.mValue.mAnySequence.Value()));
break;
}
}
}
bool
OwningArrayBufferViewOrAnySequence::TrySetToArrayBufferView(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
ArrayBufferView& memberSlot = RawSetAsArrayBufferView();
if (!memberSlot.Init(&value.toObject())) {
DestroyArrayBufferView();
tryNext = true;
return true;
}
if (JS::IsArrayBufferViewShared(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
if (JS::IsLargeArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
if (JS::IsResizableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
if (JS::IsImmutableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBufferView branch of (ArrayBufferView or sequence<any>)");
return false;
}
}
return true;
}
bool
OwningArrayBufferViewOrAnySequence::TrySetToArrayBufferView(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl);
}
[[nodiscard]] ArrayBufferView&
OwningArrayBufferViewOrAnySequence::RawSetAsArrayBufferView()
{
if (mType == eArrayBufferView) {
return mValue.mArrayBufferView.Value();
}
MOZ_ASSERT(mType == eUninitialized);
mType = eArrayBufferView;
return mValue.mArrayBufferView.SetValue();
}
[[nodiscard]] ArrayBufferView&
OwningArrayBufferViewOrAnySequence::SetAsArrayBufferView()
{
if (mType == eArrayBufferView) {
return mValue.mArrayBufferView.Value();
}
Uninit();
mType = eArrayBufferView;
return mValue.mArrayBufferView.SetValue();
}
void
OwningArrayBufferViewOrAnySequence::DestroyArrayBufferView()
{
MOZ_RELEASE_ASSERT(IsArrayBufferView(), "Wrong type!");
mValue.mArrayBufferView.Destroy();
mType = eUninitialized;
}
bool
OwningArrayBufferViewOrAnySequence::TrySetToAnySequence(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
Sequence<JS::Value>& memberSlot = RawSetAsAnySequence();
JS::ForOfIterator iter(cx);
if (!iter.init(value, JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
DestroyAnySequence();
tryNext = true;
return true;
}
Sequence<JS::Value> &arr = memberSlot;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
JS::Value* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Value& slot = *slotPtr;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#pragma clang diagnostic ignored "-Wunreachable-code-return"
#endif // __clang__
if ((passedToJSImpl) && !CallerSubsumes(temp)) {
cx.ThrowErrorMessage<MSG_PERMISSION_DENIED_TO_PASS_ARG>("element of sequence<any> branch of (ArrayBufferView or sequence<any>)");
return false;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
slot = temp;
}
}
return true;
}
bool
OwningArrayBufferViewOrAnySequence::TrySetToAnySequence(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToAnySequence(cx, value, tryNext, passedToJSImpl);
}
[[nodiscard]] Sequence<JS::Value>&
OwningArrayBufferViewOrAnySequence::RawSetAsAnySequence()
{
if (mType == eAnySequence) {
return mValue.mAnySequence.Value();
}
MOZ_ASSERT(mType == eUninitialized);
mType = eAnySequence;
return mValue.mAnySequence.SetValue();
}
[[nodiscard]] Sequence<JS::Value>&
OwningArrayBufferViewOrAnySequence::SetAsAnySequence()
{
if (mType == eAnySequence) {
return mValue.mAnySequence.Value();
}
Uninit();
mType = eAnySequence;
return mValue.mAnySequence.SetValue();
}
void
OwningArrayBufferViewOrAnySequence::DestroyAnySequence()
{
MOZ_RELEASE_ASSERT(IsAnySequence(), "Wrong type!");
mValue.mAnySequence.Destroy();
mType = eUninitialized;
}
bool
OwningArrayBufferViewOrAnySequence::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
MOZ_ASSERT(mType == eUninitialized);
bool done = false, failed = false, tryNext;
if (value.isObject()) {
done = (failed = !TrySetToArrayBufferView(cx, value, tryNext, passedToJSImpl)) || !tryNext;
if (!done) {
done = (failed = !TrySetToAnySequence(cx, value, tryNext, passedToJSImpl)) || !tryNext;
}
}
if (failed) {
return false;
}
if (!done) {
cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "ArrayBufferView, sequence<any>");
return false;
}
return true;
}
bool
OwningArrayBufferViewOrAnySequence::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return Init(cx, value, sourceDescription, passedToJSImpl);
}
void
OwningArrayBufferViewOrAnySequence::Uninit()
{
switch (mType) {
case eUninitialized: {
break;
}
case eArrayBufferView: {
DestroyArrayBufferView();
break;
}
case eAnySequence: {
DestroyAnySequence();
break;
}
}
}
bool
OwningArrayBufferViewOrAnySequence::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
switch (mType) {
case eUninitialized: {
return false;
}
case eArrayBufferView: {
rval.setObject(*mValue.mArrayBufferView.Value().Obj());
if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
return false;
}
return true;
}
case eAnySequence: {
uint32_t length = mValue.mAnySequence.Value().Length();
JS::Rooted<JSObject*> returnArray(cx, JS::NewArrayObject(cx, length));
if (!returnArray) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
// Control block to let us common up the JS_DefineElement calls when there
// are different ways to succeed at wrapping the object.
do {
JS::ExposeValueToActiveJS(mValue.mAnySequence.Value()[sequenceIdx0]);
tmp.set(mValue.mAnySequence.Value()[sequenceIdx0]);
if (!MaybeWrapValue(cx, &tmp)) {
return false;
}
break;
} while (false);
if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
rval.setObject(*returnArray);
return true;
}
default: {
return false;
}
}
}
void
OwningArrayBufferViewOrAnySequence::TraceUnion(JSTracer* trc)
{
switch (mType) {
case eArrayBufferView: {
mValue.mArrayBufferView.Value().TraceSelf(trc);
break;
}
case eAnySequence: {
DoTraceSequence(trc, mValue.mAnySequence.Value());
break;
}
default: {
}
}
}
OwningArrayBufferViewOrAnySequence&
OwningArrayBufferViewOrAnySequence::operator=(OwningArrayBufferViewOrAnySequence&& aOther)
{
this->~OwningArrayBufferViewOrAnySequence();
new (this) OwningArrayBufferViewOrAnySequence (std::move(aOther));
return *this;
}
InferenceSessionRunOptions::InferenceSessionRunOptions()
{
// Safe to pass a null context if we pass a null value
Init(nullptr, JS::NullHandleValue);
}
bool
InferenceSessionRunOptions::InitIds(JSContext* cx, InferenceSessionRunOptionsAtoms* atomsCache)
{
MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());
// Initialize these in reverse order so that any failure leaves the first one
// uninitialized.
if (!atomsCache->terminate_id.init(cx, "terminate") ||
!atomsCache->tag_id.init(cx, "tag") ||
!atomsCache->logVerbosityLevel_id.init(cx, "logVerbosityLevel") ||
!atomsCache->logSeverityLevel_id.init(cx, "logSeverityLevel")) {
return false;
}
return true;
}
bool
InferenceSessionRunOptions::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
// Passing a null JSContext is OK only if we're initing from null,
// Since in that case we will not have to do any property gets
// Also evaluate isNullOrUndefined in order to avoid false-positive
// checkers by static analysis tools
MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
InferenceSessionRunOptionsAtoms* atomsCache = nullptr;
if (cx) {
atomsCache = GetAtomCache<InferenceSessionRunOptionsAtoms>(cx);
if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
!InitIds(cx, atomsCache)) {
return false;
}
}
if (!IsConvertibleToDictionary(val)) {
return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
}
bool isNull = val.isNullOrUndefined();
// We only need these if !isNull, in which case we have |cx|.
Maybe<JS::Rooted<JSObject *> > object;
Maybe<JS::Rooted<JS::Value> > temp;
if (!isNull) {
MOZ_ASSERT(cx);
object.emplace(cx, &val.toObject());
temp.emplace(cx);
}
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->logSeverityLevel_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<uint16_t, eDefault>(cx, temp.ref(), "'logSeverityLevel' member of InferenceSessionRunOptions", &mLogSeverityLevel)) {
return false;
}
} else {
mLogSeverityLevel = 0;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->logVerbosityLevel_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<uint32_t, eDefault>(cx, temp.ref(), "'logVerbosityLevel' member of InferenceSessionRunOptions", &mLogVerbosityLevel)) {
return false;
}
} else {
mLogVerbosityLevel = 0U;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->tag_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mTag)) {
return false;
}
} else {
mTag.AssignLiteral("");
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->terminate_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'terminate' member of InferenceSessionRunOptions", &mTerminate)) {
return false;
}
} else {
mTerminate = true;
}
mIsAnyMemberPresent = true;
return true;
}
bool
InferenceSessionRunOptions::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
// We don't want to use sourceDescription for our context here;
// that's not really what it's formatted for.
BindingCallContext cx(cx_, nullptr);
return Init(cx, val, sourceDescription, passedToJSImpl);
}
void
InferenceSessionRunOptions::TraceDictionary(JSTracer* trc)
{
}
InferenceSessionRunOptions&
InferenceSessionRunOptions::operator=(const InferenceSessionRunOptions& aOther)
{
DictionaryBase::operator=(aOther);
mLogSeverityLevel = aOther.mLogSeverityLevel;
mLogVerbosityLevel = aOther.mLogVerbosityLevel;
mTag = aOther.mTag;
mTerminate = aOther.mTerminate;
return *this;
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToTensorDataLocation(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
TensorDataLocation& memberSlot = RawSetAsTensorDataLocation();
{
int index;
if (!binding_detail::FindEnumStringIndex<true>(cx, value,
binding_detail::EnumStrings<TensorDataLocation>::Values,
"TensorDataLocation", "TensorDataLocation branch of (TensorDataLocation or record<USVString, TensorDataLocation>)",
&index)) {
return false;
}
MOZ_ASSERT(index >= 0);
memberSlot = static_cast<TensorDataLocation>(index);
}
}
return true;
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToTensorDataLocation(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToTensorDataLocation(cx, value, tryNext, passedToJSImpl);
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToUTF8StringTensorDataLocationRecord(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
Record<nsCString, TensorDataLocation>& memberSlot = RawSetAsUTF8StringTensorDataLocationRecord();
auto& recordEntries = memberSlot.Entries();
JS::Rooted<JSObject*> recordObj(cx, &value.toObject());
JS::RootedVector<jsid> ids(cx);
if (!js::GetPropertyKeys(cx, recordObj,
JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) {
return false;
}
if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx);
JS::Rooted<JS::Value> idVal(cx);
// Use a hashset to keep track of ids seen, to avoid
// introducing nasty O(N^2) behavior scanning for them all the
// time. Ideally we'd use a data structure with O(1) lookup
// _and_ ordering for the MozMap, but we don't have one lying
// around.
nsTHashtable<nsCStringHashKey> idsSeen;
for (size_t i = 0; i < ids.length(); ++i) {
curId = ids[i];
JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(cx);
if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId,
&desc)) {
return false;
}
if (desc.isNothing() || !desc->enumerable()) {
continue;
}
idVal = js::IdToValue(curId);
nsCString propName;
// This will just throw if idVal is a Symbol, like the spec says
// to do.
if (!ConvertJSValueToString(cx, idVal, "key of record<USVString, TensorDataLocation> branch of (TensorDataLocation or record<USVString, TensorDataLocation>)", propName)) {
return false;
}
if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) {
return false;
}
Record<nsCString, TensorDataLocation>::EntryType* entry;
if (!idsSeen.EnsureInserted(propName)) {
// Find the existing entry.
auto idx = recordEntries.IndexOf(propName);
MOZ_ASSERT(idx != recordEntries.NoIndex,
"Why is it not found?");
// Now blow it away to make it look like it was just added
// to the array, because it's not obvious that it's
// safe to write to its already-initialized mValue via our
// normal codegen conversions. For example, the value
// could be a union and this would change its type, but
// codegen assumes we won't do that.
entry = recordEntries.ReconstructElementAt(idx);
} else {
// Safe to do an infallible append here, because we did a
// SetCapacity above to the right capacity.
entry = recordEntries.AppendElement();
}
entry->mKey = propName;
TensorDataLocation& slot = entry->mValue;
{
int index;
if (!binding_detail::FindEnumStringIndex<true>(cx, temp,
binding_detail::EnumStrings<TensorDataLocation>::Values,
"TensorDataLocation", "value in record<USVString, TensorDataLocation> branch of (TensorDataLocation or record<USVString, TensorDataLocation>)",
&index)) {
return false;
}
MOZ_ASSERT(index >= 0);
slot = static_cast<TensorDataLocation>(index);
}
}
}
return true;
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToUTF8StringTensorDataLocationRecord(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToUTF8StringTensorDataLocationRecord(cx, value, tryNext, passedToJSImpl);
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
MOZ_ASSERT(mType == eUninitialized);
bool done = false, failed = false, tryNext;
if (value.isObject()) {
if (!done) {
done = (failed = !TrySetToUTF8StringTensorDataLocationRecord(cx, value, tryNext, passedToJSImpl)) || !tryNext;
}
}
if (!done) {
do {
done = (failed = !TrySetToTensorDataLocation(cx, value, tryNext)) || !tryNext;
break;
} while (false);
}
if (failed) {
return false;
}
if (!done) {
cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "record<USVString, TensorDataLocation>");
return false;
}
return true;
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return Init(cx, value, sourceDescription, passedToJSImpl);
}
bool
TensorDataLocationOrUTF8StringTensorDataLocationRecord::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
switch (mType) {
case eUninitialized: {
return false;
}
case eTensorDataLocation: {
if (!ToJSValue(cx, mValue.mTensorDataLocation.Value(), rval)) {
return false;
}
return true;
}
case eUTF8StringTensorDataLocationRecord: {
JS::Rooted<JSObject*> returnObj(cx, JS_NewPlainObject(cx));
if (!returnObj) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (auto& entry : mValue.mUTF8StringTensorDataLocationRecord.Value().Entries()) {
auto& recordValue0 = entry.mValue;
// Control block to let us common up the JS_DefineUCProperty calls when there
// are different ways to succeed at wrapping the value.
do {
if (!ToJSValue(cx, recordValue0, &tmp)) {
return false;
}
break;
} while (false);
NS_ConvertUTF8toUTF16 expandedKey(entry.mKey);
if (!JS_DefineUCProperty(cx, returnObj,
expandedKey.BeginReading(),
expandedKey.Length(), tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
rval.setObject(*returnObj);
return true;
}
default: {
return false;
}
}
}
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord(OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord&& aOther)
: mType(eUninitialized)
{
switch (aOther.mType) {
case eUninitialized: {
MOZ_ASSERT(mType == eUninitialized,
"We need to destroy ourselves?");
break;
}
case eTensorDataLocation: {
mType = eTensorDataLocation;
mValue.mTensorDataLocation.SetValue(std::move(aOther.mValue.mTensorDataLocation.Value()));
break;
}
case eUTF8StringTensorDataLocationRecord: {
mType = eUTF8StringTensorDataLocationRecord;
mValue.mUTF8StringTensorDataLocationRecord.SetValue(std::move(aOther.mValue.mUTF8StringTensorDataLocationRecord.Value()));
break;
}
}
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToTensorDataLocation(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
TensorDataLocation& memberSlot = RawSetAsTensorDataLocation();
{
int index;
if (!binding_detail::FindEnumStringIndex<true>(cx, value,
binding_detail::EnumStrings<TensorDataLocation>::Values,
"TensorDataLocation", "TensorDataLocation branch of (TensorDataLocation or record<USVString, TensorDataLocation>)",
&index)) {
return false;
}
MOZ_ASSERT(index >= 0);
memberSlot = static_cast<TensorDataLocation>(index);
}
}
return true;
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToTensorDataLocation(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToTensorDataLocation(cx, value, tryNext, passedToJSImpl);
}
[[nodiscard]] TensorDataLocation&
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::RawSetAsTensorDataLocation()
{
if (mType == eTensorDataLocation) {
return mValue.mTensorDataLocation.Value();
}
MOZ_ASSERT(mType == eUninitialized);
mType = eTensorDataLocation;
return mValue.mTensorDataLocation.SetValue();
}
[[nodiscard]] TensorDataLocation&
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::SetAsTensorDataLocation()
{
if (mType == eTensorDataLocation) {
return mValue.mTensorDataLocation.Value();
}
Uninit();
mType = eTensorDataLocation;
return mValue.mTensorDataLocation.SetValue();
}
void
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::DestroyTensorDataLocation()
{
MOZ_RELEASE_ASSERT(IsTensorDataLocation(), "Wrong type!");
mValue.mTensorDataLocation.Destroy();
mType = eUninitialized;
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToUTF8StringTensorDataLocationRecord(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
Record<nsCString, TensorDataLocation>& memberSlot = RawSetAsUTF8StringTensorDataLocationRecord();
auto& recordEntries = memberSlot.Entries();
JS::Rooted<JSObject*> recordObj(cx, &value.toObject());
JS::RootedVector<jsid> ids(cx);
if (!js::GetPropertyKeys(cx, recordObj,
JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) {
return false;
}
if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx);
JS::Rooted<JS::Value> idVal(cx);
// Use a hashset to keep track of ids seen, to avoid
// introducing nasty O(N^2) behavior scanning for them all the
// time. Ideally we'd use a data structure with O(1) lookup
// _and_ ordering for the MozMap, but we don't have one lying
// around.
nsTHashtable<nsCStringHashKey> idsSeen;
for (size_t i = 0; i < ids.length(); ++i) {
curId = ids[i];
JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(cx);
if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId,
&desc)) {
return false;
}
if (desc.isNothing() || !desc->enumerable()) {
continue;
}
idVal = js::IdToValue(curId);
nsCString propName;
// This will just throw if idVal is a Symbol, like the spec says
// to do.
if (!ConvertJSValueToString(cx, idVal, "key of record<USVString, TensorDataLocation> branch of (TensorDataLocation or record<USVString, TensorDataLocation>)", propName)) {
return false;
}
if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) {
return false;
}
Record<nsCString, TensorDataLocation>::EntryType* entry;
if (!idsSeen.EnsureInserted(propName)) {
// Find the existing entry.
auto idx = recordEntries.IndexOf(propName);
MOZ_ASSERT(idx != recordEntries.NoIndex,
"Why is it not found?");
// Now blow it away to make it look like it was just added
// to the array, because it's not obvious that it's
// safe to write to its already-initialized mValue via our
// normal codegen conversions. For example, the value
// could be a union and this would change its type, but
// codegen assumes we won't do that.
entry = recordEntries.ReconstructElementAt(idx);
} else {
// Safe to do an infallible append here, because we did a
// SetCapacity above to the right capacity.
entry = recordEntries.AppendElement();
}
entry->mKey = propName;
TensorDataLocation& slot = entry->mValue;
{
int index;
if (!binding_detail::FindEnumStringIndex<true>(cx, temp,
binding_detail::EnumStrings<TensorDataLocation>::Values,
"TensorDataLocation", "value in record<USVString, TensorDataLocation> branch of (TensorDataLocation or record<USVString, TensorDataLocation>)",
&index)) {
return false;
}
MOZ_ASSERT(index >= 0);
slot = static_cast<TensorDataLocation>(index);
}
}
}
return true;
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::TrySetToUTF8StringTensorDataLocationRecord(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToUTF8StringTensorDataLocationRecord(cx, value, tryNext, passedToJSImpl);
}
[[nodiscard]] Record<nsCString, TensorDataLocation>&
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::RawSetAsUTF8StringTensorDataLocationRecord()
{
if (mType == eUTF8StringTensorDataLocationRecord) {
return mValue.mUTF8StringTensorDataLocationRecord.Value();
}
MOZ_ASSERT(mType == eUninitialized);
mType = eUTF8StringTensorDataLocationRecord;
return mValue.mUTF8StringTensorDataLocationRecord.SetValue();
}
[[nodiscard]] Record<nsCString, TensorDataLocation>&
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::SetAsUTF8StringTensorDataLocationRecord()
{
if (mType == eUTF8StringTensorDataLocationRecord) {
return mValue.mUTF8StringTensorDataLocationRecord.Value();
}
Uninit();
mType = eUTF8StringTensorDataLocationRecord;
return mValue.mUTF8StringTensorDataLocationRecord.SetValue();
}
void
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::DestroyUTF8StringTensorDataLocationRecord()
{
MOZ_RELEASE_ASSERT(IsUTF8StringTensorDataLocationRecord(), "Wrong type!");
mValue.mUTF8StringTensorDataLocationRecord.Destroy();
mType = eUninitialized;
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
MOZ_ASSERT(mType == eUninitialized);
bool done = false, failed = false, tryNext;
if (value.isObject()) {
if (!done) {
done = (failed = !TrySetToUTF8StringTensorDataLocationRecord(cx, value, tryNext, passedToJSImpl)) || !tryNext;
}
}
if (!done) {
do {
done = (failed = !TrySetToTensorDataLocation(cx, value, tryNext)) || !tryNext;
break;
} while (false);
}
if (failed) {
return false;
}
if (!done) {
cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "record<USVString, TensorDataLocation>");
return false;
}
return true;
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return Init(cx, value, sourceDescription, passedToJSImpl);
}
void
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::Uninit()
{
switch (mType) {
case eUninitialized: {
break;
}
case eTensorDataLocation: {
DestroyTensorDataLocation();
break;
}
case eUTF8StringTensorDataLocationRecord: {
DestroyUTF8StringTensorDataLocationRecord();
break;
}
}
}
bool
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
switch (mType) {
case eUninitialized: {
return false;
}
case eTensorDataLocation: {
if (!ToJSValue(cx, mValue.mTensorDataLocation.Value(), rval)) {
return false;
}
return true;
}
case eUTF8StringTensorDataLocationRecord: {
JS::Rooted<JSObject*> returnObj(cx, JS_NewPlainObject(cx));
if (!returnObj) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (auto& entry : mValue.mUTF8StringTensorDataLocationRecord.Value().Entries()) {
auto& recordValue0 = entry.mValue;
// Control block to let us common up the JS_DefineUCProperty calls when there
// are different ways to succeed at wrapping the value.
do {
if (!ToJSValue(cx, recordValue0, &tmp)) {
return false;
}
break;
} while (false);
NS_ConvertUTF8toUTF16 expandedKey(entry.mKey);
if (!JS_DefineUCProperty(cx, returnObj,
expandedKey.BeginReading(),
expandedKey.Length(), tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
rval.setObject(*returnObj);
return true;
}
default: {
return false;
}
}
}
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord&
OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord::operator=(OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord&& aOther)
{
this->~OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord();
new (this) OwningTensorDataLocationOrUTF8StringTensorDataLocationRecord (std::move(aOther));
return *this;
}
bool
UTF8StringOrUint8Array::TrySetToUTF8String(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
binding_detail::FakeString<char>& memberSlot = RawSetAsUTF8String();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
bool
UTF8StringOrUint8Array::TrySetToUint8Array(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
RootedSpiderMonkeyInterface<Uint8Array>& memberSlot = RawSetAsUint8Array(cx);
if (!memberSlot.Init(&value.toObject())) {
DestroyUint8Array();
tryNext = true;
return true;
}
if (JS::IsArrayBufferViewShared(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
if (JS::IsLargeArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
if (JS::IsResizableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
if (JS::IsImmutableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
}
return true;
}
bool
UTF8StringOrUint8Array::TrySetToUint8Array(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToUint8Array(cx, value, tryNext, passedToJSImpl);
}
bool
UTF8StringOrUint8Array::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
MOZ_ASSERT(mType == eUninitialized);
bool done = false, failed = false, tryNext;
if (value.isObject()) {
done = (failed = !TrySetToUint8Array(cx, value, tryNext, passedToJSImpl)) || !tryNext;
}
if (!done) {
do {
done = (failed = !TrySetToUTF8String(cx, value, tryNext)) || !tryNext;
break;
} while (false);
}
if (failed) {
return false;
}
if (!done) {
cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "Uint8Array");
return false;
}
return true;
}
bool
UTF8StringOrUint8Array::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return Init(cx, value, sourceDescription, passedToJSImpl);
}
bool
UTF8StringOrUint8Array::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
switch (mType) {
case eUninitialized: {
return false;
}
case eUTF8String: {
if (!NonVoidUTF8StringToJsval(cx, mValue.mUTF8String.Value(), rval)) {
return false;
}
return true;
}
case eUint8Array: {
rval.setObject(*mValue.mUint8Array.Value().Obj());
if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
return false;
}
return true;
}
default: {
return false;
}
}
}
OwningUTF8StringOrUint8Array::OwningUTF8StringOrUint8Array(OwningUTF8StringOrUint8Array&& aOther)
: mType(eUninitialized)
{
switch (aOther.mType) {
case eUninitialized: {
MOZ_ASSERT(mType == eUninitialized,
"We need to destroy ourselves?");
break;
}
case eUTF8String: {
mType = eUTF8String;
mValue.mUTF8String.SetValue(std::move(aOther.mValue.mUTF8String.Value()));
break;
}
case eUint8Array: {
mType = eUint8Array;
mValue.mUint8Array.SetValue(std::move(aOther.mValue.mUint8Array.Value()));
break;
}
}
}
bool
OwningUTF8StringOrUint8Array::TrySetToUTF8String(JSContext* cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
nsCString& memberSlot = RawSetAsUTF8String();
if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) {
return false;
}
}
return true;
}
[[nodiscard]] nsCString&
OwningUTF8StringOrUint8Array::RawSetAsUTF8String()
{
if (mType == eUTF8String) {
return mValue.mUTF8String.Value();
}
MOZ_ASSERT(mType == eUninitialized);
mType = eUTF8String;
return mValue.mUTF8String.SetValue();
}
[[nodiscard]] nsCString&
OwningUTF8StringOrUint8Array::SetAsUTF8String()
{
if (mType == eUTF8String) {
return mValue.mUTF8String.Value();
}
Uninit();
mType = eUTF8String;
return mValue.mUTF8String.SetValue();
}
void
OwningUTF8StringOrUint8Array::DestroyUTF8String()
{
MOZ_RELEASE_ASSERT(IsUTF8String(), "Wrong type!");
mValue.mUTF8String.Destroy();
mType = eUninitialized;
}
bool
OwningUTF8StringOrUint8Array::TrySetToUint8Array(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
tryNext = false;
{ // scope for memberSlot
Uint8Array& memberSlot = RawSetAsUint8Array();
if (!memberSlot.Init(&value.toObject())) {
DestroyUint8Array();
tryNext = true;
return true;
}
if (JS::IsArrayBufferViewShared(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
if (JS::IsLargeArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
if (JS::IsResizableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
if (JS::IsImmutableArrayBufferView(memberSlot.Obj())) {
cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("Uint8Array branch of (USVString or Uint8Array)");
return false;
}
}
return true;
}
bool
OwningUTF8StringOrUint8Array::TrySetToUint8Array(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return TrySetToUint8Array(cx, value, tryNext, passedToJSImpl);
}
[[nodiscard]] Uint8Array&
OwningUTF8StringOrUint8Array::RawSetAsUint8Array()
{
if (mType == eUint8Array) {
return mValue.mUint8Array.Value();
}
MOZ_ASSERT(mType == eUninitialized);
mType = eUint8Array;
return mValue.mUint8Array.SetValue();
}
[[nodiscard]] Uint8Array&
OwningUTF8StringOrUint8Array::SetAsUint8Array()
{
if (mType == eUint8Array) {
return mValue.mUint8Array.Value();
}
Uninit();
mType = eUint8Array;
return mValue.mUint8Array.SetValue();
}
void
OwningUTF8StringOrUint8Array::DestroyUint8Array()
{
MOZ_RELEASE_ASSERT(IsUint8Array(), "Wrong type!");
mValue.mUint8Array.Destroy();
mType = eUninitialized;
}
bool
OwningUTF8StringOrUint8Array::Init(BindingCallContext& cx, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
MOZ_ASSERT(mType == eUninitialized);
bool done = false, failed = false, tryNext;
if (value.isObject()) {
done = (failed = !TrySetToUint8Array(cx, value, tryNext, passedToJSImpl)) || !tryNext;
}
if (!done) {
do {
done = (failed = !TrySetToUTF8String(cx, value, tryNext)) || !tryNext;
break;
} while (false);
}
if (failed) {
return false;
}
if (!done) {
cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "Uint8Array");
return false;
}
return true;
}
bool
OwningUTF8StringOrUint8Array::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
BindingCallContext cx(cx_, nullptr);
return Init(cx, value, sourceDescription, passedToJSImpl);
}
void
OwningUTF8StringOrUint8Array::Uninit()
{
switch (mType) {
case eUninitialized: {
break;
}
case eUTF8String: {
DestroyUTF8String();
break;
}
case eUint8Array: {
DestroyUint8Array();
break;
}
}
}
bool
OwningUTF8StringOrUint8Array::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
switch (mType) {
case eUninitialized: {
return false;
}
case eUTF8String: {
if (!NonVoidUTF8StringToJsval(cx, mValue.mUTF8String.Value(), rval)) {
return false;
}
return true;
}
case eUint8Array: {
rval.setObject(*mValue.mUint8Array.Value().Obj());
if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
return false;
}
return true;
}
default: {
return false;
}
}
}
void
OwningUTF8StringOrUint8Array::TraceUnion(JSTracer* trc)
{
switch (mType) {
case eUint8Array: {
mValue.mUint8Array.Value().TraceSelf(trc);
break;
}
default: {
}
}
}
OwningUTF8StringOrUint8Array&
OwningUTF8StringOrUint8Array::operator=(OwningUTF8StringOrUint8Array&& aOther)
{
this->~OwningUTF8StringOrUint8Array();
new (this) OwningUTF8StringOrUint8Array (std::move(aOther));
return *this;
}
InferenceSessionSessionOptions::InferenceSessionSessionOptions()
{
// Safe to pass a null context if we pass a null value
Init(nullptr, JS::NullHandleValue);
}
bool
InferenceSessionSessionOptions::InitIds(JSContext* cx, InferenceSessionSessionOptionsAtoms* atomsCache)
{
MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());
// Initialize these in reverse order so that any failure leaves the first one
// uninitialized.
if (!atomsCache->profileFilePrefix_id.init(cx, "profileFilePrefix") ||
!atomsCache->preferredOutputLocation_id.init(cx, "preferredOutputLocation") ||
!atomsCache->optimizedModelFilePath_id.init(cx, "optimizedModelFilePath") ||
!atomsCache->logVerbosityLevel_id.init(cx, "logVerbosityLevel") ||
!atomsCache->logSeverityLevel_id.init(cx, "logSeverityLevel") ||
!atomsCache->logId_id.init(cx, "logId") ||
!atomsCache->intraOpNumThreads_id.init(cx, "intraOpNumThreads") ||
!atomsCache->interOpNumThreads_id.init(cx, "interOpNumThreads") ||
!atomsCache->graphOptimizationLevel_id.init(cx, "graphOptimizationLevel") ||
!atomsCache->freeDimensionOverrides_id.init(cx, "freeDimensionOverrides") ||
!atomsCache->extra_id.init(cx, "extra") ||
!atomsCache->executionProviders_id.init(cx, "executionProviders") ||
!atomsCache->executionMode_id.init(cx, "executionMode") ||
!atomsCache->enableProfiling_id.init(cx, "enableProfiling") ||
!atomsCache->enableMemPattern_id.init(cx, "enableMemPattern") ||
!atomsCache->enableGraphCapture_id.init(cx, "enableGraphCapture") ||
!atomsCache->enableCpuMemArena_id.init(cx, "enableCpuMemArena")) {
return false;
}
return true;
}
bool
InferenceSessionSessionOptions::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
// Passing a null JSContext is OK only if we're initing from null,
// Since in that case we will not have to do any property gets
// Also evaluate isNullOrUndefined in order to avoid false-positive
// checkers by static analysis tools
MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
InferenceSessionSessionOptionsAtoms* atomsCache = nullptr;
if (cx) {
atomsCache = GetAtomCache<InferenceSessionSessionOptionsAtoms>(cx);
if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
!InitIds(cx, atomsCache)) {
return false;
}
}
if (!IsConvertibleToDictionary(val)) {
return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
}
bool isNull = val.isNullOrUndefined();
// We only need these if !isNull, in which case we have |cx|.
Maybe<JS::Rooted<JSObject *> > object;
Maybe<JS::Rooted<JS::Value> > temp;
if (!isNull) {
MOZ_ASSERT(cx);
object.emplace(cx, &val.toObject());
temp.emplace(cx);
}
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->enableCpuMemArena_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'enableCpuMemArena' member of InferenceSessionSessionOptions", &mEnableCpuMemArena)) {
return false;
}
} else {
mEnableCpuMemArena = true;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->enableGraphCapture_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'enableGraphCapture' member of InferenceSessionSessionOptions", &mEnableGraphCapture)) {
return false;
}
} else {
mEnableGraphCapture = false;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->enableMemPattern_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'enableMemPattern' member of InferenceSessionSessionOptions", &mEnableMemPattern)) {
return false;
}
} else {
mEnableMemPattern = true;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->enableProfiling_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'enableProfiling' member of InferenceSessionSessionOptions", &mEnableProfiling)) {
return false;
}
} else {
mEnableProfiling = false;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->executionMode_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mExecutionMode)) {
return false;
}
} else {
mExecutionMode.AssignLiteral("sequential");
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->executionProviders_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
mExecutionProviders.Construct();
if (temp.ref().isObject()) {
JS::ForOfIterator iter(cx);
if (!iter.init(temp.ref(), JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("'executionProviders' member of InferenceSessionSessionOptions", "sequence");
return false;
}
Sequence<JS::Value> &arr = (mExecutionProviders.Value());
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
JS::Value* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Value& slot = *slotPtr;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#pragma clang diagnostic ignored "-Wunreachable-code-return"
#endif // __clang__
if ((passedToJSImpl) && !CallerSubsumes(temp)) {
cx.ThrowErrorMessage<MSG_PERMISSION_DENIED_TO_PASS_ARG>("element of 'executionProviders' member of InferenceSessionSessionOptions");
return false;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
slot = temp;
}
} else {
cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("'executionProviders' member of InferenceSessionSessionOptions", "sequence");
return false;
}
mIsAnyMemberPresent = true;
}
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->extra_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
mExtra.Construct();
if (temp.ref().isObject()) {
auto& recordEntries = (mExtra.Value()).Entries();
JS::Rooted<JSObject*> recordObj(cx, &temp.ref().toObject());
JS::RootedVector<jsid> ids(cx);
if (!js::GetPropertyKeys(cx, recordObj,
JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) {
return false;
}
if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx);
JS::Rooted<JS::Value> idVal(cx);
// Use a hashset to keep track of ids seen, to avoid
// introducing nasty O(N^2) behavior scanning for them all the
// time. Ideally we'd use a data structure with O(1) lookup
// _and_ ordering for the MozMap, but we don't have one lying
// around.
nsTHashtable<nsCStringHashKey> idsSeen;
for (size_t i = 0; i < ids.length(); ++i) {
curId = ids[i];
JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(cx);
if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId,
&desc)) {
return false;
}
if (desc.isNothing() || !desc->enumerable()) {
continue;
}
idVal = js::IdToValue(curId);
nsCString propName;
// This will just throw if idVal is a Symbol, like the spec says
// to do.
if (!ConvertJSValueToString(cx, idVal, "key of 'extra' member of InferenceSessionSessionOptions", propName)) {
return false;
}
if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) {
return false;
}
Record<nsCString, JS::Value>::EntryType* entry;
if (!idsSeen.EnsureInserted(propName)) {
// Find the existing entry.
auto idx = recordEntries.IndexOf(propName);
MOZ_ASSERT(idx != recordEntries.NoIndex,
"Why is it not found?");
// Now blow it away to make it look like it was just added
// to the array, because it's not obvious that it's
// safe to write to its already-initialized mValue via our
// normal codegen conversions. For example, the value
// could be a union and this would change its type, but
// codegen assumes we won't do that.
entry = recordEntries.ReconstructElementAt(idx);
} else {
// Safe to do an infallible append here, because we did a
// SetCapacity above to the right capacity.
entry = recordEntries.AppendElement();
}
entry->mKey = propName;
JS::Value& slot = entry->mValue;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#pragma clang diagnostic ignored "-Wunreachable-code-return"
#endif // __clang__
if ((passedToJSImpl) && !CallerSubsumes(temp)) {
cx.ThrowErrorMessage<MSG_PERMISSION_DENIED_TO_PASS_ARG>("value in 'extra' member of InferenceSessionSessionOptions");
return false;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
slot = temp;
}
} else {
cx.ThrowErrorMessage<MSG_NOT_OBJECT>("'extra' member of InferenceSessionSessionOptions");
return false;
}
mIsAnyMemberPresent = true;
}
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->freeDimensionOverrides_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
mFreeDimensionOverrides.Construct();
if (temp.ref().isObject()) {
auto& recordEntries = (mFreeDimensionOverrides.Value()).Entries();
JS::Rooted<JSObject*> recordObj(cx, &temp.ref().toObject());
JS::RootedVector<jsid> ids(cx);
if (!js::GetPropertyKeys(cx, recordObj,
JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) {
return false;
}
if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx);
JS::Rooted<JS::Value> idVal(cx);
// Use a hashset to keep track of ids seen, to avoid
// introducing nasty O(N^2) behavior scanning for them all the
// time. Ideally we'd use a data structure with O(1) lookup
// _and_ ordering for the MozMap, but we don't have one lying
// around.
nsTHashtable<nsCStringHashKey> idsSeen;
for (size_t i = 0; i < ids.length(); ++i) {
curId = ids[i];
JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(cx);
if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId,
&desc)) {
return false;
}
if (desc.isNothing() || !desc->enumerable()) {
continue;
}
idVal = js::IdToValue(curId);
nsCString propName;
// This will just throw if idVal is a Symbol, like the spec says
// to do.
if (!ConvertJSValueToString(cx, idVal, "key of 'freeDimensionOverrides' member of InferenceSessionSessionOptions", propName)) {
return false;
}
if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) {
return false;
}
Record<nsCString, uint32_t>::EntryType* entry;
if (!idsSeen.EnsureInserted(propName)) {
// Find the existing entry.
auto idx = recordEntries.IndexOf(propName);
MOZ_ASSERT(idx != recordEntries.NoIndex,
"Why is it not found?");
// Now blow it away to make it look like it was just added
// to the array, because it's not obvious that it's
// safe to write to its already-initialized mValue via our
// normal codegen conversions. For example, the value
// could be a union and this would change its type, but
// codegen assumes we won't do that.
entry = recordEntries.ReconstructElementAt(idx);
} else {
// Safe to do an infallible append here, because we did a
// SetCapacity above to the right capacity.
entry = recordEntries.AppendElement();
}
entry->mKey = propName;
uint32_t& slot = entry->mValue;
if (!ValueToPrimitive<uint32_t, eDefault>(cx, temp, "Value in 'freeDimensionOverrides' member of InferenceSessionSessionOptions", &slot)) {
return false;
}
}
} else {
cx.ThrowErrorMessage<MSG_NOT_OBJECT>("'freeDimensionOverrides' member of InferenceSessionSessionOptions");
return false;
}
mIsAnyMemberPresent = true;
}
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->graphOptimizationLevel_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mGraphOptimizationLevel)) {
return false;
}
} else {
mGraphOptimizationLevel.AssignLiteral("all");
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->interOpNumThreads_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<uint32_t, eDefault>(cx, temp.ref(), "'interOpNumThreads' member of InferenceSessionSessionOptions", &mInterOpNumThreads)) {
return false;
}
} else {
mInterOpNumThreads = 0U;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->intraOpNumThreads_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<uint32_t, eDefault>(cx, temp.ref(), "'intraOpNumThreads' member of InferenceSessionSessionOptions", &mIntraOpNumThreads)) {
return false;
}
} else {
mIntraOpNumThreads = 0U;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->logId_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mLogId)) {
return false;
}
} else {
mLogId.AssignLiteral("");
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->logSeverityLevel_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<uint16_t, eDefault>(cx, temp.ref(), "'logSeverityLevel' member of InferenceSessionSessionOptions", &mLogSeverityLevel)) {
return false;
}
} else {
mLogSeverityLevel = 4;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->logVerbosityLevel_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ValueToPrimitive<uint32_t, eDefault>(cx, temp.ref(), "'logVerbosityLevel' member of InferenceSessionSessionOptions", &mLogVerbosityLevel)) {
return false;
}
} else {
mLogVerbosityLevel = 0U;
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->optimizedModelFilePath_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mOptimizedModelFilePath)) {
return false;
}
} else {
mOptimizedModelFilePath.AssignLiteral("");
}
mIsAnyMemberPresent = true;
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->preferredOutputLocation_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
mPreferredOutputLocation.Construct();
if (!(mPreferredOutputLocation.Value()).Init(cx, temp.ref(), "'preferredOutputLocation' member of InferenceSessionSessionOptions", passedToJSImpl)) {
return false;
}
mIsAnyMemberPresent = true;
}
if (!isNull) {
if (!JS_GetPropertyById(cx, *object, atomsCache->profileFilePrefix_id, temp.ptr())) {
return false;
}
}
if (!isNull && !temp->isUndefined()) {
if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mProfileFilePrefix)) {
return false;
}
} else {
mProfileFilePrefix.AssignLiteral("");
}
mIsAnyMemberPresent = true;
return true;
}
bool
InferenceSessionSessionOptions::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
// We don't want to use sourceDescription for our context here;
// that's not really what it's formatted for.
BindingCallContext cx(cx_, nullptr);
return Init(cx, val, sourceDescription, passedToJSImpl);
}
void
InferenceSessionSessionOptions::TraceDictionary(JSTracer* trc)
{
if (mExecutionProviders.WasPassed()) {
DoTraceSequence(trc, mExecutionProviders.Value());
}
if (mExtra.WasPassed()) {
TraceRecord(trc, mExtra.Value());
}
}
namespace InferenceSession_Binding {
MOZ_CAN_RUN_SCRIPT static bool
run(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
BindingCallContext cx(cx_, "InferenceSession.run");
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "run", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::InferenceSession*>(void_self);
if (!args.requireAtLeast(cx, "InferenceSession.run", 1)) {
return false;
}
Record<nsCString, OwningNonNull<mozilla::dom::Tensor>> arg0;
if (args[0].isObject()) {
auto& recordEntries = arg0.Entries();
JS::Rooted<JSObject*> recordObj(cx, &args[0].toObject());
JS::RootedVector<jsid> ids(cx);
if (!js::GetPropertyKeys(cx, recordObj,
JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) {
return false;
}
if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) {
JS_ReportOutOfMemory(cx);
return false;
}
JS::Rooted<JS::Value> propNameValue(cx);
JS::Rooted<JS::Value> temp(cx);
JS::Rooted<jsid> curId(cx);
JS::Rooted<JS::Value> idVal(cx);
// Use a hashset to keep track of ids seen, to avoid
// introducing nasty O(N^2) behavior scanning for them all the
// time. Ideally we'd use a data structure with O(1) lookup
// _and_ ordering for the MozMap, but we don't have one lying
// around.
nsTHashtable<nsCStringHashKey> idsSeen;
for (size_t i = 0; i < ids.length(); ++i) {
curId = ids[i];
JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(cx);
if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId,
&desc)) {
return false;
}
if (desc.isNothing() || !desc->enumerable()) {
continue;
}
idVal = js::IdToValue(curId);
nsCString propName;
// This will just throw if idVal is a Symbol, like the spec says
// to do.
if (!ConvertJSValueToString(cx, idVal, "key of argument 1", propName)) {
return false;
}
if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) {
return false;
}
Record<nsCString, OwningNonNull<mozilla::dom::Tensor>>::EntryType* entry;
if (!idsSeen.EnsureInserted(propName)) {
// Find the existing entry.
auto idx = recordEntries.IndexOf(propName);
MOZ_ASSERT(idx != recordEntries.NoIndex,
"Why is it not found?");
// Now blow it away to make it look like it was just added
// to the array, because it's not obvious that it's
// safe to write to its already-initialized mValue via our
// normal codegen conversions. For example, the value
// could be a union and this would change its type, but
// codegen assumes we won't do that.
entry = recordEntries.ReconstructElementAt(idx);
} else {
// Safe to do an infallible append here, because we did a
// SetCapacity above to the right capacity.
entry = recordEntries.AppendElement();
}
entry->mKey = propName;
OwningNonNull<mozilla::dom::Tensor>& slot = entry->mValue;
if (temp.isObject()) {
static_assert(IsRefcounted<mozilla::dom::Tensor>::value, "We can only store refcounted classes.");
{
// Our JSContext should be in the right global to do unwrapping in.
nsresult rv = UnwrapObject<prototypes::id::Tensor, mozilla::dom::Tensor>(&temp, slot, cx);
if (NS_FAILED(rv)) {
cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Value in argument 1", "Tensor");
return false;
}
}
} else {
cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Value in argument 1");
return false;
}
}
} else {
cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
return false;
}
binding_detail::FastInferenceSessionRunOptions arg1;
if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
return false;
}
FastErrorResult rv;
auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Run(Constify(arg0), Constify(arg1), rv)));
if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "InferenceSession.run"))) {
return false;
}
MOZ_ASSERT(!JS_IsExceptionPending(cx));
static_assert(!std::is_pointer_v<decltype(result)>,
"NewObject implies that we need to keep the object alive with a strong reference.");
if (!ToJSValue(cx, result, args.rval())) {
return false;
}
return true;
}
MOZ_CAN_RUN_SCRIPT static bool
run_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
bool ok = run(cx, obj, void_self, args);
if (ok) {
return true;
}
return ConvertExceptionToPromise(cx, args.rval());
}
static const JSJitInfo run_methodinfo = {
{ (JSJitGetterOp)run_promiseWrapper },
{ prototypes::id::InferenceSession },
{ PrototypeTraits<prototypes::id::InferenceSession>::Depth },
JSJitInfo::Method,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
create(JSContext* cx_, unsigned argc, JS::Value* vp)
{
BindingCallContext cx(cx_, "InferenceSession.create");
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "create", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::Rooted<JSObject*> obj(cx, &args.callee());
if (!args.requireAtLeast(cx, "InferenceSession.create", 1)) {
return false;
}
GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
if (global.Failed()) {
return false;
}
UTF8StringOrUint8Array arg0;
if (!arg0.Init(cx, args[0], "Argument 1", false)) {
return false;
}
RootedDictionary<binding_detail::FastInferenceSessionSessionOptions> arg1(cx);
if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
return false;
}
FastErrorResult rv;
auto result(StrongOrRawPtr<Promise>(mozilla::dom::InferenceSession::Create(global, Constify(arg0), Constify(arg1), rv)));
if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "InferenceSession.create"))) {
return false;
}
MOZ_ASSERT(!JS_IsExceptionPending(cx));
static_assert(!std::is_pointer_v<decltype(result)>,
"NewObject implies that we need to keep the object alive with a strong reference.");
if (!ToJSValue(cx, result, args.rval())) {
return false;
}
return true;
}
static const JSJitInfo create_methodinfo = {
{ (JSJitGetterOp)create },
{ prototypes::id::_ID_Count }, { 0 }, JSJitInfo::StaticMethod,
JSJitInfo::AliasEverything, JSVAL_TYPE_OBJECT, false, false,
false, false, 0
};
MOZ_CAN_RUN_SCRIPT static bool
release(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "release", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::InferenceSession*>(void_self);
auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->ReleaseSession()));
MOZ_ASSERT(!JS_IsExceptionPending(cx));
if (!ToJSValue(cx, result, args.rval())) {
return false;
}
return true;
}
MOZ_CAN_RUN_SCRIPT static bool
release_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
bool ok = release(cx, obj, void_self, args);
if (ok) {
return true;
}
return ConvertExceptionToPromise(cx, args.rval());
}
static const JSJitInfo release_methodinfo = {
{ (JSJitGetterOp)release_promiseWrapper },
{ prototypes::id::InferenceSession },
{ PrototypeTraits<prototypes::id::InferenceSession>::Depth },
JSJitInfo::Method,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
startProfiling(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "startProfiling", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::InferenceSession*>(void_self);
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->StartProfiling())>, "Should be returning void here");
MOZ_KnownLive(self)->StartProfiling();
MOZ_ASSERT(!JS_IsExceptionPending(cx));
args.rval().setUndefined();
return true;
}
static const JSJitInfo startProfiling_methodinfo = {
{ (JSJitGetterOp)startProfiling },
{ prototypes::id::InferenceSession },
{ PrototypeTraits<prototypes::id::InferenceSession>::Depth },
JSJitInfo::Method,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_UNDEFINED, /* returnType. Not relevant for setters. */
true, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
endProfiling(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "endProfiling", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::InferenceSession*>(void_self);
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->EndProfiling())>, "Should be returning void here");
MOZ_KnownLive(self)->EndProfiling();
MOZ_ASSERT(!JS_IsExceptionPending(cx));
args.rval().setUndefined();
return true;
}
static const JSJitInfo endProfiling_methodinfo = {
{ (JSJitGetterOp)endProfiling },
{ prototypes::id::InferenceSession },
{ PrototypeTraits<prototypes::id::InferenceSession>::Depth },
JSJitInfo::Method,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_UNDEFINED, /* returnType. Not relevant for setters. */
true, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
get_inputNames(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "inputNames", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::InferenceSession*>(void_self);
// Have to either root across the getter call or reget after.
bool isXray;
JS::Rooted<JSObject*> slotStorage(cx, GetCachedSlotStorageObject(cx, obj, &isXray));
if (!slotStorage) {
return false;
}
const size_t slotIndex = isXray ? (DOM_EXPANDO_RESERVED_SLOTS + 0) : (DOM_INSTANCE_RESERVED_SLOTS + 0);
MOZ_ASSERT(slotIndex < JSCLASS_RESERVED_SLOTS(JS::GetClass(slotStorage)));
{
// Scope for cachedVal
JS::Value cachedVal = JS::GetReservedSlot(slotStorage, slotIndex);
if (!cachedVal.isUndefined()) {
args.rval().set(cachedVal);
// The cached value is in the compartment of slotStorage,
// so wrap into the caller compartment as needed.
return MaybeWrapNonDOMObjectValue(cx, args.rval());
}
}
nsTArray<nsCString> result;
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetInputNames(result))>, "Should be returning void here");
MOZ_KnownLive(self)->GetInputNames(result);
MOZ_ASSERT(!JS_IsExceptionPending(cx));
{
JS::Rooted<JSObject*> conversionScope(cx, isXray ? JS::CurrentGlobalOrNull(cx) : slotStorage);
JSAutoRealm ar(cx, conversionScope);
do { // block we break out of when done wrapping
uint32_t length = result.Length();
JS::Rooted<JSObject*> returnArray(cx, JS::NewArrayObject(cx, length));
if (!returnArray) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
// Control block to let us common up the JS_DefineElement calls when there
// are different ways to succeed at wrapping the object.
do {
if (!NonVoidUTF8StringToJsval(cx, result[sequenceIdx0], &tmp)) {
return false;
}
break;
} while (false);
if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
args.rval().setObject(*returnArray);
break;
} while (false);
}
{ // And now store things in the realm of our slotStorage.
JSAutoRealm ar(cx, slotStorage);
// Make a copy so that we don't do unnecessary wrapping on args.rval().
JS::Rooted<JS::Value> storedVal(cx, args.rval());
if (!MaybeWrapNonDOMObjectValue(cx, &storedVal)) {
return false;
}
JS::SetReservedSlot(slotStorage, slotIndex, storedVal);
if (!isXray) {
// In the Xray case we don't need to do this, because getting the
// expando object already preserved our wrapper.
PreserveWrapper(self);
}
}
// And now make sure args.rval() is in the caller realm.
return MaybeWrapNonDOMObjectValue(cx, args.rval());
}
static const JSJitInfo inputNames_getterinfo = {
{ get_inputNames },
{ prototypes::id::InferenceSession },
{ PrototypeTraits<prototypes::id::InferenceSession>::Depth },
JSJitInfo::Getter,
JSJitInfo::AliasDOMSets, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
true, /* isMovable. Not relevant for setters. */
true, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
true, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
(DOM_INSTANCE_RESERVED_SLOTS + 0) /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) < 3, "There is no slot for us");
MOZ_CAN_RUN_SCRIPT static bool
get_outputNames(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"InferenceSession", "outputNames", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::InferenceSession*>(void_self);
// Have to either root across the getter call or reget after.
bool isXray;
JS::Rooted<JSObject*> slotStorage(cx, GetCachedSlotStorageObject(cx, obj, &isXray));
if (!slotStorage) {
return false;
}
const size_t slotIndex = isXray ? (DOM_EXPANDO_RESERVED_SLOTS + 1) : (DOM_INSTANCE_RESERVED_SLOTS + 1);
MOZ_ASSERT(slotIndex < JSCLASS_RESERVED_SLOTS(JS::GetClass(slotStorage)));
{
// Scope for cachedVal
JS::Value cachedVal = JS::GetReservedSlot(slotStorage, slotIndex);
if (!cachedVal.isUndefined()) {
args.rval().set(cachedVal);
// The cached value is in the compartment of slotStorage,
// so wrap into the caller compartment as needed.
return MaybeWrapNonDOMObjectValue(cx, args.rval());
}
}
nsTArray<nsCString> result;
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetOutputNames(result))>, "Should be returning void here");
MOZ_KnownLive(self)->GetOutputNames(result);
MOZ_ASSERT(!JS_IsExceptionPending(cx));
{
JS::Rooted<JSObject*> conversionScope(cx, isXray ? JS::CurrentGlobalOrNull(cx) : slotStorage);
JSAutoRealm ar(cx, conversionScope);
do { // block we break out of when done wrapping
uint32_t length = result.Length();
JS::Rooted<JSObject*> returnArray(cx, JS::NewArrayObject(cx, length));
if (!returnArray) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
// Control block to let us common up the JS_DefineElement calls when there
// are different ways to succeed at wrapping the object.
do {
if (!NonVoidUTF8StringToJsval(cx, result[sequenceIdx0], &tmp)) {
return false;
}
break;
} while (false);
if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
args.rval().setObject(*returnArray);
break;
} while (false);
}
{ // And now store things in the realm of our slotStorage.
JSAutoRealm ar(cx, slotStorage);
// Make a copy so that we don't do unnecessary wrapping on args.rval().
JS::Rooted<JS::Value> storedVal(cx, args.rval());
if (!MaybeWrapNonDOMObjectValue(cx, &storedVal)) {
return false;
}
JS::SetReservedSlot(slotStorage, slotIndex, storedVal);
if (!isXray) {
// In the Xray case we don't need to do this, because getting the
// expando object already preserved our wrapper.
PreserveWrapper(self);
}
}
// And now make sure args.rval() is in the caller realm.
return MaybeWrapNonDOMObjectValue(cx, args.rval());
}
static const JSJitInfo outputNames_getterinfo = {
{ get_outputNames },
{ prototypes::id::InferenceSession },
{ PrototypeTraits<prototypes::id::InferenceSession>::Depth },
JSJitInfo::Getter,
JSJitInfo::AliasDOMSets, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
true, /* isMovable. Not relevant for setters. */
true, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
true, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
(DOM_INSTANCE_RESERVED_SLOTS + 1) /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 1) <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 1) < 3, "There is no slot for us");
static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
mozilla::dom::InferenceSession* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::InferenceSession>(obj);
if (self) {
JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue());
ClearWrapper(self, self, obj);
if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) {
JS::RemoveAssociatedMemory(obj, mallocBytes,
JS::MemoryUse::DOMBinding);
}
AddForDeferredFinalization<mozilla::dom::InferenceSession>(self);
}
}
MOZ_GLOBINIT static const JSFunctionSpec sStaticMethods_specs[] = {
JS_FNSPEC("create", StaticMethodPromiseWrapper, &create_methodinfo, 1, JSPROP_ENUMERATE, nullptr),
JS_FS_END
};
static const Prefable<const JSFunctionSpec> sStaticMethods[] = {
{ nullptr, &sStaticMethods_specs[0] },
{ nullptr, nullptr }
};
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
"We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
"We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");
MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
JS_FNSPEC("run", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&run_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
JS_FNSPEC("release", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&release_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
JS_FNSPEC("startProfiling", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&startProfiling_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
JS_FNSPEC("endProfiling", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&endProfiling_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
JS_FS_END
};
static const Prefable<const JSFunctionSpec> sMethods[] = {
{ nullptr, &sMethods_specs[0] },
{ nullptr, nullptr }
};
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
"We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(4 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
"We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");
MOZ_GLOBINIT static const JSPropertySpec sAttributes_specs[] = {
JSPropertySpec::nativeAccessors("inputNames", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &inputNames_getterinfo, nullptr, nullptr),
JSPropertySpec::nativeAccessors("outputNames", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &outputNames_getterinfo, nullptr, nullptr),
JS_PS_END
};
static const Prefable<const JSPropertySpec> sAttributes[] = {
{ nullptr, &sAttributes_specs[0] },
{ nullptr, nullptr }
};
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
"We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(2 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
"We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");
static uint16_t sNativeProperties_sortedPropertyIndices[7];
static PropertyInfo sNativeProperties_propertyInfos[7];
static const NativePropertiesN<3> sNativeProperties = {
true, 0 /* sStaticMethods */,
false, 0,
true, 1 /* sMethods */,
true, 2 /* sAttributes */,
false, 0,
false, 0,
false, 0,
-1,
7,
sNativeProperties_sortedPropertyIndices,
{
{ sStaticMethods, &sNativeProperties_propertyInfos[0] },
{ sMethods, &sNativeProperties_propertyInfos[1] },
{ sAttributes, &sNativeProperties_propertyInfos[5] }
}
};
static_assert(7 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
"We have a property info count that is oversized");
// This may allocate too many slots, because we only really need
// slots for our non-interface-typed members that we cache. But
// allocating slots only for those would make the slot index
// computations much more complicated, so let's do this the simple
// way for now.
DEFINE_XRAY_EXPANDO_CLASS_WITH_OPS(static, sXrayExpandoObjectClass, 2,
&xpc::XrayExpandoObjectClassOps);
bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
nullptr,
{ sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
prototypes::id::InferenceSession,
constructors::id::InferenceSession,
&sXrayExpandoObjectClass
};
static const DOMInterfaceInfo sInterfaceObjectInfo = {
{ ThrowingConstructor, &sNativePropertyHooks },
JS::GetRealmFunctionPrototypeHandle,
PrototypeTraits<prototypes::id::InferenceSession>::Depth,
prototypes::id::InferenceSession,
true,
0,
"InferenceSession",
};
static const DOMIfaceAndProtoJSClass sPrototypeClass = {
{
"InferenceSessionPrototype",
JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
JS_NULL_CLASS_OPS,
JS_NULL_CLASS_SPEC,
JS_NULL_CLASS_EXT,
JS_NULL_OBJECT_OPS
},
eInterfacePrototype,
prototypes::id::InferenceSession,
PrototypeTraits<prototypes::id::InferenceSession>::Depth,
&sNativePropertyHooks,
JS::GetRealmObjectPrototype
};
bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
if (!NS_IsMainThread()) {
const char* name = JS::GetClass(aObj)->name;
if (strcmp(name, "DedicatedWorkerGlobalScope")) {
return false;
}
}
return InferenceSession::InInferenceProcess(aCx, aObj);
}
static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx);
static const JSClassOps sClassOps = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
_finalize, /* finalize */
nullptr, /* call */
nullptr, /* construct */
nullptr, /* trace */
};
static const DOMJSClass sClass = {
{ "InferenceSession",
JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(3) | JSCLASS_PRESERVES_WRAPPER,
&sClassOps,
JS_NULL_CLASS_SPEC,
&NativeTypeHelpers<mozilla::dom::InferenceSession>::sClassExtension,
JS_NULL_OBJECT_OPS
},
{ prototypes::id::InferenceSession, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
std::is_base_of_v<nsISupports, mozilla::dom::InferenceSession>,
&sNativePropertyHooks,
FindAssociatedGlobalForNative<mozilla::dom::InferenceSession>::Get,
GetProtoObjectHandle,
GetCCParticipant<mozilla::dom::InferenceSession>::Get(),
nullptr,
NativeTypeHelpers<mozilla::dom::InferenceSession>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
"Must have the right minimal number of reserved slots.");
static_assert(3 >= 3,
"Must have enough reserved slots.");
bool
Wrap(JSContext* aCx, mozilla::dom::InferenceSession* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::InferenceSession>,
"Shouldn't have wrappercached things that are not refcounted.");
static_assert(std::is_same_v<decltype(aObject), mozilla::dom::InferenceSession*>);
MOZ_ASSERT(ToSupportsIsCorrect(aObject));
MOZ_ASSERT_IF(aGivenProto, js::IsObjectInContextCompartment(aGivenProto, aCx));
MOZ_ASSERT(!aCache->GetWrapper(),
"You should probably not be using Wrap() directly; use "
"GetOrCreateDOMReflector instead");
MOZ_ASSERT(ToSupportsIsOnPrimaryInheritanceChain(aObject, aCache),
"nsISupports must be on our primary inheritance chain");
// If the wrapper cache contains a dead reflector then finalize that
// now, ensuring that the finalizer for the old reflector always
// runs before the new reflector is created and attached. This
// avoids the awkward situation where there are multiple reflector
// objects that contain pointers to the same native.
if (JSObject* oldReflector = aCache->GetWrapperMaybeDead()) {
_finalize(nullptr /* unused */, oldReflector);
MOZ_ASSERT(!aCache->GetWrapperMaybeDead());
}
JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
if (!global) {
return false;
}
MOZ_ASSERT(JS_IsGlobalObject(global));
JS::AssertObjectIsNotGray(global);
// That might have ended up wrapping us already, due to the wonders
// of XBL. Check for that, and bail out as needed.
aReflector.set(aCache->GetWrapper());
if (aReflector) {
#ifdef DEBUG
AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
return true;
}
JSAutoRealm ar(aCx, global);
JS::Handle<JSObject*> canonicalProto = GetProtoObjectHandle(aCx);
if (!canonicalProto) {
return false;
}
JS::Rooted<JSObject*> proto(aCx);
if (aGivenProto) {
proto = aGivenProto;
// Unfortunately, while aGivenProto was in the compartment of aCx
// coming in, we changed compartments to that of "parent" so may need
// to wrap the proto here.
if (js::GetContextCompartment(aCx) != JS::GetCompartment(proto)) {
if (!JS_WrapObject(aCx, &proto)) {
return false;
}
}
} else {
proto = canonicalProto;
}
BindingJSObjectCreator<mozilla::dom::InferenceSession> creator(aCx);
creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
if (!aReflector) {
return false;
}
aCache->SetWrapper(aReflector);
creator.InitializationSucceeded();
MOZ_ASSERT(aCache->GetWrapperPreserveColor() &&
aCache->GetWrapperPreserveColor() == aReflector);
// If proto != canonicalProto, we have to preserve our wrapper;
// otherwise we won't be able to properly recreate it later, since
// we won't know what proto to use. Note that we don't check
// aGivenProto here, since it's entirely possible (and even
// somewhat common) to have a non-null aGivenProto which is the
// same as canonicalProto.
if (proto != canonicalProto) {
PreserveWrapper(aObject);
}
return true;
}
void
ClearCachedInputNamesValue(mozilla::dom::InferenceSession* aObject)
{
JSObject* obj;
obj = aObject->GetWrapper();
if (!obj) {
return;
}
JS::SetReservedSlot(obj, (DOM_INSTANCE_RESERVED_SLOTS + 0), JS::UndefinedValue());
ClearXrayExpandoSlots(RootingCx(), obj, (DOM_EXPANDO_RESERVED_SLOTS + 0));
}
void
ClearCachedOutputNamesValue(mozilla::dom::InferenceSession* aObject)
{
JSObject* obj;
obj = aObject->GetWrapper();
if (!obj) {
return;
}
JS::SetReservedSlot(obj, (DOM_INSTANCE_RESERVED_SLOTS + 1), JS::UndefinedValue());
ClearXrayExpandoSlots(RootingCx(), obj, (DOM_EXPANDO_RESERVED_SLOTS + 1));
}
void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::InferenceSession);
JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::InferenceSession);
JS::Handle<JSObject*> parentProto(JS::GetRealmObjectPrototypeHandle(aCx));
if (!parentProto) {
return;
}
JS::Handle<JSObject*> constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx));
if (!constructorProto) {
return;
}
dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
&sPrototypeClass, protoCache,
constructorProto, &sInterfaceObjectInfo, 0, false, Span<const LegacyFactoryFunction, 0>{},
interfaceCache,
sNativeProperties.Upcast(),
nullptr,
"InferenceSession",
ShouldExpose<InferenceSession_Binding::ConstructorEnabled>(aCx, aGlobal, aDefineOnGlobal),
nullptr,
false,
nullptr);
}
static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
/* Get the interface prototype object for this class. This will create the
object as needed. */
return GetPerInterfaceObjectHandle(aCx, prototypes::id::InferenceSession,
&CreateInterfaceObjects,
DefineInterfaceProperty::CheckExposure);
}
JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx)
{
/* Get the interface object for this class. This will create the object as
needed. */
return GetPerInterfaceObjectHandle(aCx, constructors::id::InferenceSession,
&CreateInterfaceObjects,
DefineInterfaceProperty::CheckExposure);
}
} // namespace InferenceSession_Binding
namespace Tensor_Binding {
MOZ_CAN_RUN_SCRIPT static bool
get_dims(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "dims", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
// Have to either root across the getter call or reget after.
bool isXray;
JS::Rooted<JSObject*> slotStorage(cx, GetCachedSlotStorageObject(cx, obj, &isXray));
if (!slotStorage) {
return false;
}
const size_t slotIndex = isXray ? (DOM_EXPANDO_RESERVED_SLOTS + 0) : (DOM_INSTANCE_RESERVED_SLOTS + 0);
MOZ_ASSERT(slotIndex < JSCLASS_RESERVED_SLOTS(JS::GetClass(slotStorage)));
{
// Scope for cachedVal
JS::Value cachedVal = JS::GetReservedSlot(slotStorage, slotIndex);
if (!cachedVal.isUndefined()) {
args.rval().set(cachedVal);
// The cached value is in the compartment of slotStorage,
// so wrap into the caller compartment as needed.
return MaybeWrapNonDOMObjectValue(cx, args.rval());
}
}
nsTArray<int32_t> result;
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetDims(result))>, "Should be returning void here");
MOZ_KnownLive(self)->GetDims(result);
MOZ_ASSERT(!JS_IsExceptionPending(cx));
{
JS::Rooted<JSObject*> conversionScope(cx, isXray ? JS::CurrentGlobalOrNull(cx) : slotStorage);
JSAutoRealm ar(cx, conversionScope);
do { // block we break out of when done wrapping
uint32_t length = result.Length();
JS::Rooted<JSObject*> returnArray(cx, JS::NewArrayObject(cx, length));
if (!returnArray) {
return false;
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) {
// Control block to let us common up the JS_DefineElement calls when there
// are different ways to succeed at wrapping the object.
do {
tmp.setInt32(int32_t(result[sequenceIdx0]));
break;
} while (false);
if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp,
JSPROP_ENUMERATE)) {
return false;
}
}
}
args.rval().setObject(*returnArray);
break;
} while (false);
}
{ // And now store things in the realm of our slotStorage.
JSAutoRealm ar(cx, slotStorage);
// Make a copy so that we don't do unnecessary wrapping on args.rval().
JS::Rooted<JS::Value> storedVal(cx, args.rval());
if (!MaybeWrapNonDOMObjectValue(cx, &storedVal)) {
return false;
}
JS::SetReservedSlot(slotStorage, slotIndex, storedVal);
if (!isXray) {
// In the Xray case we don't need to do this, because getting the
// expando object already preserved our wrapper.
PreserveWrapper(self);
}
}
// And now make sure args.rval() is in the caller realm.
return MaybeWrapNonDOMObjectValue(cx, args.rval());
}
MOZ_CAN_RUN_SCRIPT static bool
set_dims(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, JSJitSetterCallArgs args)
{
BindingCallContext cx(cx_, "Tensor.dims setter");
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "dims", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_SETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
binding_detail::AutoSequence<int32_t> arg0;
if (args[0].isObject()) {
JS::ForOfIterator iter(cx);
if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Value being assigned", "sequence");
return false;
}
binding_detail::AutoSequence<int32_t> &arr = arg0;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
int32_t* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
int32_t& slot = *slotPtr;
if (!ValueToPrimitive<int32_t, eDefault>(cx, temp, "Element of value being assigned", &slot)) {
return false;
}
}
} else {
cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Value being assigned", "sequence");
return false;
}
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->SetDims(Constify(arg0)))>, "Should be returning void here");
MOZ_KnownLive(self)->SetDims(Constify(arg0));
MOZ_ASSERT(!JS_IsExceptionPending(cx));
ClearCachedDimsValue(self);
return true;
}
static const JSJitInfo dims_getterinfo = {
{ get_dims },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Getter,
JSJitInfo::AliasDOMSets, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
true, /* isMovable. Not relevant for setters. */
true, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
true, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
(DOM_INSTANCE_RESERVED_SLOTS + 0) /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert((DOM_INSTANCE_RESERVED_SLOTS + 0) < 2, "There is no slot for us");
static const JSJitInfo dims_setterinfo = {
{ (JSJitGetterOp)set_dims },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Setter,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_UNDEFINED, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
get_type(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "type", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
nsAutoCString result;
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetType(result))>, "Should be returning void here");
MOZ_KnownLive(self)->GetType(result);
MOZ_ASSERT(!JS_IsExceptionPending(cx));
if (!NonVoidUTF8StringToJsval(cx, result, args.rval())) {
return false;
}
return true;
}
static const JSJitInfo type_getterinfo = {
{ get_type },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Getter,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_STRING, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
get_data(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "data", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
JS::Rooted<JSObject*> result(cx);
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetData(cx, &result))>, "Should be returning void here");
MOZ_KnownLive(self)->GetData(cx, &result);
MOZ_ASSERT(!JS_IsExceptionPending(cx));
JS::ExposeObjectToActiveJS(result);
args.rval().setObject(*result);
if (!MaybeWrapNonDOMObjectValue(cx, args.rval())) {
return false;
}
return true;
}
static const JSJitInfo data_getterinfo = {
{ get_data },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Getter,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
get_location(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "location", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
TensorDataLocation result(MOZ_KnownLive(self)->Location());
MOZ_ASSERT(!JS_IsExceptionPending(cx));
if (!ToJSValue(cx, result, args.rval())) {
return false;
}
return true;
}
static const JSJitInfo location_getterinfo = {
{ get_location },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Getter,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_STRING, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
getData(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "getData", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
Optional<bool> arg0;
if (args.hasDefined(0)) {
arg0.Construct();
if (!ValueToPrimitive<bool, eDefault>(cx, args[0], "Argument 1", &arg0.Value())) {
return false;
}
}
auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->GetData(Constify(arg0))));
MOZ_ASSERT(!JS_IsExceptionPending(cx));
if (!ToJSValue(cx, result, args.rval())) {
return false;
}
return true;
}
MOZ_CAN_RUN_SCRIPT static bool
getData_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
bool ok = getData(cx, obj, void_self, args);
if (ok) {
return true;
}
return ConvertExceptionToPromise(cx, args.rval());
}
static const JSJitInfo getData_methodinfo = {
{ (JSJitGetterOp)getData_promiseWrapper },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Method,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_OBJECT, /* returnType. Not relevant for setters. */
false, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
MOZ_CAN_RUN_SCRIPT static bool
dispose(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "dispose", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
auto* self = static_cast<mozilla::dom::Tensor*>(void_self);
// NOTE: This assert does NOT call the function.
static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->Dispose())>, "Should be returning void here");
MOZ_KnownLive(self)->Dispose();
MOZ_ASSERT(!JS_IsExceptionPending(cx));
args.rval().setUndefined();
return true;
}
static const JSJitInfo dispose_methodinfo = {
{ (JSJitGetterOp)dispose },
{ prototypes::id::Tensor },
{ PrototypeTraits<prototypes::id::Tensor>::Depth },
JSJitInfo::Method,
JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */
JSVAL_TYPE_UNDEFINED, /* returnType. Not relevant for setters. */
true, /* isInfallible. False in setters. */
false, /* isMovable. Not relevant for setters. */
false, /* isEliminatable. Not relevant for setters. */
false, /* isAlwaysInSlot. Only relevant for getters. */
false, /* isLazilyCachedInSlot. Only relevant for getters. */
false, /* isTypedMethod. Only relevant for methods. */
0 /* Reserved slot index, if we're stored in a slot, else 0. */
};
static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
mozilla::dom::Tensor* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::Tensor>(obj);
if (self) {
JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue());
ClearWrapper(self, self, obj);
if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) {
JS::RemoveAssociatedMemory(obj, mallocBytes,
JS::MemoryUse::DOMBinding);
}
AddForDeferredFinalization<mozilla::dom::Tensor>(self);
}
}
MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
JS_FNSPEC("getData", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&getData_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
JS_FNSPEC("dispose", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&dispose_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
JS_FS_END
};
static const Prefable<const JSFunctionSpec> sMethods[] = {
{ nullptr, &sMethods_specs[0] },
{ nullptr, nullptr }
};
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
"We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(2 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
"We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");
MOZ_GLOBINIT static const JSPropertySpec sAttributes_specs[] = {
JSPropertySpec::nativeAccessors("dims", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &dims_getterinfo, GenericSetter<NormalThisPolicy>, &dims_setterinfo),
JSPropertySpec::nativeAccessors("type", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &type_getterinfo, nullptr, nullptr),
JSPropertySpec::nativeAccessors("data", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &data_getterinfo, nullptr, nullptr),
JSPropertySpec::nativeAccessors("location", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &location_getterinfo, nullptr, nullptr),
JS_PS_END
};
static const Prefable<const JSPropertySpec> sAttributes[] = {
{ nullptr, &sAttributes_specs[0] },
{ nullptr, nullptr }
};
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
"We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(4 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
"We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");
static uint16_t sNativeProperties_sortedPropertyIndices[6];
static PropertyInfo sNativeProperties_propertyInfos[6];
static const NativePropertiesN<2> sNativeProperties = {
false, 0,
false, 0,
true, 0 /* sMethods */,
true, 1 /* sAttributes */,
false, 0,
false, 0,
false, 0,
-1,
6,
sNativeProperties_sortedPropertyIndices,
{
{ sMethods, &sNativeProperties_propertyInfos[0] },
{ sAttributes, &sNativeProperties_propertyInfos[2] }
}
};
static_assert(6 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
"We have a property info count that is oversized");
// This may allocate too many slots, because we only really need
// slots for our non-interface-typed members that we cache. But
// allocating slots only for those would make the slot index
// computations much more complicated, so let's do this the simple
// way for now.
DEFINE_XRAY_EXPANDO_CLASS_WITH_OPS(static, sXrayExpandoObjectClass, 1,
&xpc::XrayExpandoObjectClassOps);
bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
nullptr,
{ sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
prototypes::id::Tensor,
constructors::id::Tensor,
&sXrayExpandoObjectClass
};
static bool
_constructor(JSContext* cx_, unsigned argc, JS::Value* vp)
{
BindingCallContext cx(cx_, "Tensor constructor");
AUTO_PROFILER_LABEL_DYNAMIC_FAST(
"Tensor", "constructor", DOM, cx,
uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::Rooted<JSObject*> obj(cx, &args.callee());
if (!args.isConstructing()) {
return ThrowConstructorWithoutNew(cx, "Tensor");
}
JS::Rooted<JSObject*> desiredProto(cx);
if (!GetDesiredProto(cx, args,
prototypes::id::Tensor,
CreateInterfaceObjects,
&desiredProto)) {
return false;
}
if (!args.requireAtLeast(cx, "Tensor constructor", 3)) {
return false;
}
GlobalObject global(cx, obj);
if (global.Failed()) {
return false;
}
bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
binding_detail::FakeString<char> arg0;
if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
return false;
}
ArrayBufferViewOrAnySequence arg1;
if (!arg1.Init(cx, args[1], "Argument 2", false)) {
return false;
}
binding_detail::AutoSequence<int32_t> arg2;
if (args[2].isObject()) {
JS::ForOfIterator iter(cx);
if (!iter.init(args[2], JS::ForOfIterator::AllowNonIterable)) {
return false;
}
if (!iter.valueIsIterable()) {
cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Argument 3", "sequence");
return false;
}
binding_detail::AutoSequence<int32_t> &arr = arg2;
JS::Rooted<JS::Value> temp(cx);
while (true) {
bool done;
if (!iter.next(&temp, &done)) {
return false;
}
if (done) {
break;
}
int32_t* slotPtr = arr.AppendElement(mozilla::fallible);
if (!slotPtr) {
JS_ReportOutOfMemory(cx);
return false;
}
int32_t& slot = *slotPtr;
if (!ValueToPrimitive<int32_t, eDefault>(cx, temp, "Element of argument 3", &slot)) {
return false;
}
}
} else {
cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Argument 3", "sequence");
return false;
}
Maybe<JSAutoRealm> ar;
if (objIsXray) {
// Since our object is an Xray, we can just CheckedUnwrapStatic:
// we know Xrays have no dynamic unwrap behavior.
obj = js::CheckedUnwrapStatic(obj);
if (!obj) {
return false;
}
ar.emplace(cx, obj);
if (!JS_WrapObject(cx, &desiredProto)) {
return false;
}
if (arg1.IsArrayBufferView()) {
if (!arg1.GetAsArrayBufferView().WrapIntoNewCompartment(cx)) {
return false;
}
}
else if (arg1.IsAnySequence()) {
for (uint32_t indexName0 = 0; indexName0 < arg1.GetAsAnySequence().Length(); ++indexName0) {
if (!JS_WrapValue(cx, JS::MutableHandle<JS::Value>::fromMarkedLocation(&arg1.GetAsAnySequence()[indexName0]))) {
return false;
}
}
}
}
FastErrorResult rv;
auto result(StrongOrRawPtr<mozilla::dom::Tensor>(mozilla::dom::Tensor::Constructor(global, Constify(arg0), Constify(arg1), Constify(arg2), rv)));
if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "Tensor constructor"))) {
return false;
}
MOZ_ASSERT(!JS_IsExceptionPending(cx));
static_assert(!std::is_pointer_v<decltype(result)>,
"NewObject implies that we need to keep the object alive with a strong reference.");
if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) {
MOZ_ASSERT(JS_IsExceptionPending(cx));
return false;
}
return true;
}
static const DOMInterfaceInfo sInterfaceObjectInfo = {
{ _constructor, &sNativePropertyHooks },
JS::GetRealmFunctionPrototypeHandle,
PrototypeTraits<prototypes::id::Tensor>::Depth,
prototypes::id::Tensor,
true,
3,
"Tensor",
};
static const DOMIfaceAndProtoJSClass sPrototypeClass = {
{
"TensorPrototype",
JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
JS_NULL_CLASS_OPS,
JS_NULL_CLASS_SPEC,
JS_NULL_CLASS_EXT,
JS_NULL_OBJECT_OPS
},
eInterfacePrototype,
prototypes::id::Tensor,
PrototypeTraits<prototypes::id::Tensor>::Depth,
&sNativePropertyHooks,
JS::GetRealmObjectPrototype
};
bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
if (!NS_IsMainThread()) {
const char* name = JS::GetClass(aObj)->name;
if (strcmp(name, "DedicatedWorkerGlobalScope")) {
return false;
}
}
return InferenceSession::InInferenceProcess(aCx, aObj);
}
static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx);
static const JSClassOps sClassOps = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
_finalize, /* finalize */
nullptr, /* call */
nullptr, /* construct */
nullptr, /* trace */
};
static const DOMJSClass sClass = {
{ "Tensor",
JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(2) | JSCLASS_PRESERVES_WRAPPER,
&sClassOps,
JS_NULL_CLASS_SPEC,
&NativeTypeHelpers<mozilla::dom::Tensor>::sClassExtension,
JS_NULL_OBJECT_OPS
},
{ prototypes::id::Tensor, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
std::is_base_of_v<nsISupports, mozilla::dom::Tensor>,
&sNativePropertyHooks,
FindAssociatedGlobalForNative<mozilla::dom::Tensor>::Get,
GetProtoObjectHandle,
GetCCParticipant<mozilla::dom::Tensor>::Get(),
nullptr,
NativeTypeHelpers<mozilla::dom::Tensor>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
"Must have the right minimal number of reserved slots.");
static_assert(2 >= 2,
"Must have enough reserved slots.");
bool
Wrap(JSContext* aCx, mozilla::dom::Tensor* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::Tensor>,
"Shouldn't have wrappercached things that are not refcounted.");
static_assert(std::is_same_v<decltype(aObject), mozilla::dom::Tensor*>);
MOZ_ASSERT(ToSupportsIsCorrect(aObject));
MOZ_ASSERT_IF(aGivenProto, js::IsObjectInContextCompartment(aGivenProto, aCx));
MOZ_ASSERT(!aCache->GetWrapper(),
"You should probably not be using Wrap() directly; use "
"GetOrCreateDOMReflector instead");
MOZ_ASSERT(ToSupportsIsOnPrimaryInheritanceChain(aObject, aCache),
"nsISupports must be on our primary inheritance chain");
// If the wrapper cache contains a dead reflector then finalize that
// now, ensuring that the finalizer for the old reflector always
// runs before the new reflector is created and attached. This
// avoids the awkward situation where there are multiple reflector
// objects that contain pointers to the same native.
if (JSObject* oldReflector = aCache->GetWrapperMaybeDead()) {
_finalize(nullptr /* unused */, oldReflector);
MOZ_ASSERT(!aCache->GetWrapperMaybeDead());
}
JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
if (!global) {
return false;
}
MOZ_ASSERT(JS_IsGlobalObject(global));
JS::AssertObjectIsNotGray(global);
// That might have ended up wrapping us already, due to the wonders
// of XBL. Check for that, and bail out as needed.
aReflector.set(aCache->GetWrapper());
if (aReflector) {
#ifdef DEBUG
AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
return true;
}
JSAutoRealm ar(aCx, global);
JS::Handle<JSObject*> canonicalProto = GetProtoObjectHandle(aCx);
if (!canonicalProto) {
return false;
}
JS::Rooted<JSObject*> proto(aCx);
if (aGivenProto) {
proto = aGivenProto;
// Unfortunately, while aGivenProto was in the compartment of aCx
// coming in, we changed compartments to that of "parent" so may need
// to wrap the proto here.
if (js::GetContextCompartment(aCx) != JS::GetCompartment(proto)) {
if (!JS_WrapObject(aCx, &proto)) {
return false;
}
}
} else {
proto = canonicalProto;
}
BindingJSObjectCreator<mozilla::dom::Tensor> creator(aCx);
creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
if (!aReflector) {
return false;
}
aCache->SetWrapper(aReflector);
creator.InitializationSucceeded();
MOZ_ASSERT(aCache->GetWrapperPreserveColor() &&
aCache->GetWrapperPreserveColor() == aReflector);
// If proto != canonicalProto, we have to preserve our wrapper;
// otherwise we won't be able to properly recreate it later, since
// we won't know what proto to use. Note that we don't check
// aGivenProto here, since it's entirely possible (and even
// somewhat common) to have a non-null aGivenProto which is the
// same as canonicalProto.
if (proto != canonicalProto) {
PreserveWrapper(aObject);
}
return true;
}
void
ClearCachedDimsValue(mozilla::dom::Tensor* aObject)
{
JSObject* obj;
obj = aObject->GetWrapper();
if (!obj) {
return;
}
JS::SetReservedSlot(obj, (DOM_INSTANCE_RESERVED_SLOTS + 0), JS::UndefinedValue());
ClearXrayExpandoSlots(RootingCx(), obj, (DOM_EXPANDO_RESERVED_SLOTS + 0));
}
void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::Tensor);
JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::Tensor);
JS::Handle<JSObject*> parentProto(JS::GetRealmObjectPrototypeHandle(aCx));
if (!parentProto) {
return;
}
JS::Handle<JSObject*> constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx));
if (!constructorProto) {
return;
}
dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
&sPrototypeClass, protoCache,
constructorProto, &sInterfaceObjectInfo, 3, false, Span<const LegacyFactoryFunction, 0>{},
interfaceCache,
sNativeProperties.Upcast(),
nullptr,
"Tensor",
ShouldExpose<Tensor_Binding::ConstructorEnabled>(aCx, aGlobal, aDefineOnGlobal),
nullptr,
false,
nullptr);
}
static JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
/* Get the interface prototype object for this class. This will create the
object as needed. */
return GetPerInterfaceObjectHandle(aCx, prototypes::id::Tensor,
&CreateInterfaceObjects,
DefineInterfaceProperty::CheckExposure);
}
JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx)
{
/* Get the interface object for this class. This will create the object as
needed. */
return GetPerInterfaceObjectHandle(aCx, constructors::id::Tensor,
&CreateInterfaceObjects,
DefineInterfaceProperty::CheckExposure);
}
} // namespace Tensor_Binding
} // namespace dom
} // namespace mozilla