/* THIS FILE IS AUTOGENERATED FROM UniFFI.webidl BY Codegen.py - DO NOT EDIT */

#include <type_traits>
#include "AtomList.h"
#include "MainThreadUtils.h"
#include "UniFFIBinding.h"
#include "WrapperFactory.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.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/FloatingPoint.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/NonRefcountedDOMObject.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/dom/UniFFIPointer.h"
#include "mozilla/dom/UniFFIScaffolding.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsContentUtils.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<UniFFIScaffoldingCallCode>::Values[3];
} // namespace binding_detail

bool
ToJSValue(JSContext* aCx, UniFFIScaffoldingCallCode aArgument, JS::MutableHandle<JS::Value> aValue)
{
  MOZ_ASSERT(uint32_t(aArgument) < std::size(binding_detail::EnumStrings<UniFFIScaffoldingCallCode>::Values));
  JSString* resultStr =
    JS_NewStringCopyN(aCx, binding_detail::EnumStrings<UniFFIScaffoldingCallCode>::Values[uint32_t(aArgument)].BeginReading(),
                      binding_detail::EnumStrings<UniFFIScaffoldingCallCode>::Values[uint32_t(aArgument)].Length());
  if (!resultStr) {
    return false;
  }
  aValue.setString(resultStr);
  return true;
}


void
ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, OwningDoubleOrArrayBufferOrUniFFIPointer& aUnion, const char* aName, uint32_t aFlags)
{
  if (aUnion.IsUniFFIPointer()) {
    ImplCycleCollectionTraverse(aCallback, aUnion.GetAsUniFFIPointer(), "mUniFFIPointer", aFlags);
  }
}


void
ImplCycleCollectionUnlink(OwningDoubleOrArrayBufferOrUniFFIPointer& aUnion)
{
  aUnion.Uninit();
}


bool
DoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    double& memberSlot = RawSetAsDouble();
    if (!ValueToPrimitive<double, eDefault>(cx, value, "Double branch of (double or ArrayBuffer or UniFFIPointer)", &memberSlot)) {
      return false;
    } else if (!std::isfinite(memberSlot)) {
      cx.ThrowErrorMessage<MSG_NOT_FINITE>("Double branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
  }
  return true;
}

bool
DoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToDouble(cx, value, tryNext, passedToJSImpl);
}







bool
DoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    RootedSpiderMonkeyInterface<ArrayBuffer>& memberSlot = RawSetAsArrayBuffer(cx);
    if (!memberSlot.Init(&value.toObject())) {
      DestroyArrayBuffer();
      tryNext = true;
      return true;
    }
    if (JS::IsSharedArrayBufferObject(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
    if (JS::IsLargeArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
    if (JS::IsResizableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
    if (JS::IsImmutableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
  }
  return true;
}

bool
DoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl);
}







bool
DoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    NonNull<mozilla::dom::UniFFIPointer>& memberSlot = RawSetAsUniFFIPointer();
    {
      // Our JSContext should be in the right global to do unwrapping in.
      nsresult rv = UnwrapObject<prototypes::id::UniFFIPointer, mozilla::dom::UniFFIPointer>(value, memberSlot, cx);
      if (NS_FAILED(rv)) {
        DestroyUniFFIPointer();
        tryNext = true;
        return true;
      }
    }
  }
  return true;
}

bool
DoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl);
}







bool
DoubleOrArrayBufferOrUniFFIPointer::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 = !TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl)) || !tryNext ||
           (failed = !TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl)) || !tryNext;
  }
  if (!done) {
    do {
      done = (failed = !TrySetToDouble(cx, value, tryNext)) || !tryNext;
      break;
    } while (false);
  }
  if (failed) {
    return false;
  }
  if (!done) {
    cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "ArrayBuffer, UniFFIPointer");
    return false;
  }
  return true;
}

bool
DoubleOrArrayBufferOrUniFFIPointer::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, value, sourceDescription, passedToJSImpl);
}


bool
DoubleOrArrayBufferOrUniFFIPointer::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eDouble: {
      rval.set(JS_NumberValue(double(mValue.mDouble.Value())));
      return true;
    }
    case eArrayBuffer: {
      rval.setObject(*mValue.mArrayBuffer.Value().Obj());
      if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
        return false;
      }
      return true;
    }
    case eUniFFIPointer: {
      if (!GetOrCreateDOMReflector(cx, mValue.mUniFFIPointer.Value(), rval)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}



OwningDoubleOrArrayBufferOrUniFFIPointer::OwningDoubleOrArrayBufferOrUniFFIPointer(OwningDoubleOrArrayBufferOrUniFFIPointer&& aOther)
  : mType(eUninitialized)
{
  switch (aOther.mType) {
    case eUninitialized: {
      MOZ_ASSERT(mType == eUninitialized,
                 "We need to destroy ourselves?");
      break;
    }
    case eDouble: {
      mType = eDouble;
      mValue.mDouble.SetValue(std::move(aOther.mValue.mDouble.Value()));
      break;
    }
    case eArrayBuffer: {
      mType = eArrayBuffer;
      mValue.mArrayBuffer.SetValue(std::move(aOther.mValue.mArrayBuffer.Value()));
      break;
    }
    case eUniFFIPointer: {
      mType = eUniFFIPointer;
      mValue.mUniFFIPointer.SetValue(std::move(aOther.mValue.mUniFFIPointer.Value()));
      break;
    }
  }
}


bool
OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    double& memberSlot = RawSetAsDouble();
    if (!ValueToPrimitive<double, eDefault>(cx, value, "Double branch of (double or ArrayBuffer or UniFFIPointer)", &memberSlot)) {
      return false;
    } else if (!std::isfinite(memberSlot)) {
      cx.ThrowErrorMessage<MSG_NOT_FINITE>("Double branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
  }
  return true;
}

bool
OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToDouble(cx, value, tryNext, passedToJSImpl);
}

[[nodiscard]] double&
OwningDoubleOrArrayBufferOrUniFFIPointer::RawSetAsDouble()
{
  if (mType == eDouble) {
    return mValue.mDouble.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eDouble;
  return mValue.mDouble.SetValue();
}

[[nodiscard]] double&
OwningDoubleOrArrayBufferOrUniFFIPointer::SetAsDouble()
{
  if (mType == eDouble) {
    return mValue.mDouble.Value();
  }
  Uninit();
  mType = eDouble;
  return mValue.mDouble.SetValue();
}


void
OwningDoubleOrArrayBufferOrUniFFIPointer::DestroyDouble()
{
  MOZ_RELEASE_ASSERT(IsDouble(), "Wrong type!");
  mValue.mDouble.Destroy();
  mType = eUninitialized;
}



bool
OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    ArrayBuffer& memberSlot = RawSetAsArrayBuffer();
    if (!memberSlot.Init(&value.toObject())) {
      DestroyArrayBuffer();
      tryNext = true;
      return true;
    }
    if (JS::IsSharedArrayBufferObject(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
    if (JS::IsLargeArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
    if (JS::IsResizableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
    if (JS::IsImmutableArrayBufferMaybeShared(memberSlot.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)");
      return false;
    }
  }
  return true;
}

bool
OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl);
}

[[nodiscard]] ArrayBuffer&
OwningDoubleOrArrayBufferOrUniFFIPointer::RawSetAsArrayBuffer()
{
  if (mType == eArrayBuffer) {
    return mValue.mArrayBuffer.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eArrayBuffer;
  return mValue.mArrayBuffer.SetValue();
}

[[nodiscard]] ArrayBuffer&
OwningDoubleOrArrayBufferOrUniFFIPointer::SetAsArrayBuffer()
{
  if (mType == eArrayBuffer) {
    return mValue.mArrayBuffer.Value();
  }
  Uninit();
  mType = eArrayBuffer;
  return mValue.mArrayBuffer.SetValue();
}


void
OwningDoubleOrArrayBufferOrUniFFIPointer::DestroyArrayBuffer()
{
  MOZ_RELEASE_ASSERT(IsArrayBuffer(), "Wrong type!");
  mValue.mArrayBuffer.Destroy();
  mType = eUninitialized;
}



bool
OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(BindingCallContext& cx, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  tryNext = false;
  { // scope for memberSlot
    OwningNonNull<mozilla::dom::UniFFIPointer>& memberSlot = RawSetAsUniFFIPointer();
    static_assert(IsRefcounted<mozilla::dom::UniFFIPointer>::value, "We can only store refcounted classes.");
    {
      // Our JSContext should be in the right global to do unwrapping in.
      nsresult rv = UnwrapObject<prototypes::id::UniFFIPointer, mozilla::dom::UniFFIPointer>(value, memberSlot, cx);
      if (NS_FAILED(rv)) {
        DestroyUniFFIPointer();
        tryNext = true;
        return true;
      }
    }
  }
  return true;
}

bool
OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(JSContext* cx_, JS::Handle<JS::Value> value, bool& tryNext, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl);
}

[[nodiscard]] OwningNonNull<mozilla::dom::UniFFIPointer>&
OwningDoubleOrArrayBufferOrUniFFIPointer::RawSetAsUniFFIPointer()
{
  if (mType == eUniFFIPointer) {
    return mValue.mUniFFIPointer.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eUniFFIPointer;
  return mValue.mUniFFIPointer.SetValue();
}

[[nodiscard]] OwningNonNull<mozilla::dom::UniFFIPointer>&
OwningDoubleOrArrayBufferOrUniFFIPointer::SetAsUniFFIPointer()
{
  if (mType == eUniFFIPointer) {
    return mValue.mUniFFIPointer.Value();
  }
  Uninit();
  mType = eUniFFIPointer;
  return mValue.mUniFFIPointer.SetValue();
}


void
OwningDoubleOrArrayBufferOrUniFFIPointer::DestroyUniFFIPointer()
{
  MOZ_RELEASE_ASSERT(IsUniFFIPointer(), "Wrong type!");
  mValue.mUniFFIPointer.Destroy();
  mType = eUninitialized;
}



bool
OwningDoubleOrArrayBufferOrUniFFIPointer::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 = !TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl)) || !tryNext ||
           (failed = !TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl)) || !tryNext;
  }
  if (!done) {
    do {
      done = (failed = !TrySetToDouble(cx, value, tryNext)) || !tryNext;
      break;
    } while (false);
  }
  if (failed) {
    return false;
  }
  if (!done) {
    cx.ThrowErrorMessage<MSG_NOT_IN_UNION>(sourceDescription, "ArrayBuffer, UniFFIPointer");
    return false;
  }
  return true;
}

bool
OwningDoubleOrArrayBufferOrUniFFIPointer::Init(JSContext* cx_, JS::Handle<JS::Value> value, const char* sourceDescription, bool passedToJSImpl)
{
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, value, sourceDescription, passedToJSImpl);
}

void
OwningDoubleOrArrayBufferOrUniFFIPointer::Uninit()
{
  switch (mType) {
    case eUninitialized: {
      break;
    }
    case eDouble: {
      DestroyDouble();
      break;
    }
    case eArrayBuffer: {
      DestroyArrayBuffer();
      break;
    }
    case eUniFFIPointer: {
      DestroyUniFFIPointer();
      break;
    }
  }
}

bool
OwningDoubleOrArrayBufferOrUniFFIPointer::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eDouble: {
      rval.set(JS_NumberValue(double(mValue.mDouble.Value())));
      return true;
    }
    case eArrayBuffer: {
      rval.setObject(*mValue.mArrayBuffer.Value().Obj());
      if (!MaybeWrapNonDOMObjectValue(cx, rval)) {
        return false;
      }
      return true;
    }
    case eUniFFIPointer: {
      if (!GetOrCreateDOMReflector(cx, mValue.mUniFFIPointer.Value(), rval)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}

void
OwningDoubleOrArrayBufferOrUniFFIPointer::TraceUnion(JSTracer* trc)
{
  switch (mType) {
    case eArrayBuffer: {
      mValue.mArrayBuffer.Value().TraceSelf(trc);
      break;
    }
    default: {
    }
  }
}

OwningDoubleOrArrayBufferOrUniFFIPointer&
OwningDoubleOrArrayBufferOrUniFFIPointer::operator=(OwningDoubleOrArrayBufferOrUniFFIPointer&& aOther)
{
  this->~OwningDoubleOrArrayBufferOrUniFFIPointer();
  new (this) OwningDoubleOrArrayBufferOrUniFFIPointer (std::move(aOther));
  return *this;
}




UniFFIScaffoldingCallResult::UniFFIScaffoldingCallResult()
{
  // Safe to pass a null context if we pass a null value
  Init(nullptr, JS::NullHandleValue);
}



bool
UniFFIScaffoldingCallResult::InitIds(JSContext* cx, UniFFIScaffoldingCallResultAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->data_id.init(cx, "data") ||
      !atomsCache->code_id.init(cx, "code")) {
    return false;
  }
  return true;
}

bool
UniFFIScaffoldingCallResult::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());
  UniFFIScaffoldingCallResultAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<UniFFIScaffoldingCallResultAtoms>(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->code_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    {
      int index;
      if (!binding_detail::FindEnumStringIndex<true>(cx, temp.ref(),
                                                                         binding_detail::EnumStrings<UniFFIScaffoldingCallCode>::Values,
                                                                         "UniFFIScaffoldingCallCode", "'code' member of UniFFIScaffoldingCallResult",
                                                                         &index)) {
        return false;
      }
      MOZ_ASSERT(index >= 0);
      mCode = static_cast<UniFFIScaffoldingCallCode>(index);
    }
    mIsAnyMemberPresent = true;
  } else if (cx) {
    // Don't error out if we have no cx.  In that
    // situation the caller is default-constructing us and we'll
    // just assume they know what they're doing.
    return cx.ThrowErrorMessage<MSG_MISSING_REQUIRED_DICTIONARY_MEMBER>("'code' member of UniFFIScaffoldingCallResult");
  }

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->data_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    mData.Construct();
    if (!(mData.Value()).Init(cx, temp.ref(), "'data' member of UniFFIScaffoldingCallResult", passedToJSImpl)) {
      return false;
    }
    mIsAnyMemberPresent = true;
  }
  return true;
}

bool
UniFFIScaffoldingCallResult::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);
}

bool
UniFFIScaffoldingCallResult::ToObjectInternal(JSContext* cx, JS::MutableHandle<JS::Value> rval) const
{
  UniFFIScaffoldingCallResultAtoms* atomsCache = GetAtomCache<UniFFIScaffoldingCallResultAtoms>(cx);
  if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
      !InitIds(cx, atomsCache)) {
    return false;
  }

  JS::Rooted<JSObject*> obj(cx, JS_NewPlainObject(cx));
  if (!obj) {
    return false;
  }
  rval.set(JS::ObjectValue(*obj));

  do {
    // block for our 'break' successCode and scope for 'temp' and 'currentValue'
    JS::Rooted<JS::Value> temp(cx);
    UniFFIScaffoldingCallCode const & currentValue = mCode;
    if (!ToJSValue(cx, currentValue, &temp)) {
      return false;
    }
    if (!JS_DefinePropertyById(cx, obj, atomsCache->code_id, temp, JSPROP_ENUMERATE)) {
      return false;
    }
    break;
  } while(false);

  if (mData.WasPassed()) {
    do {
      // block for our 'break' successCode and scope for 'temp' and 'currentValue'
      JS::Rooted<JS::Value> temp(cx);
      OwningDoubleOrArrayBufferOrUniFFIPointer const & currentValue = mData.InternalValue();
      if (!currentValue.ToJSVal(cx, obj, &temp)) {
        return false;
      }
      if (!JS_DefinePropertyById(cx, obj, atomsCache->data_id, temp, JSPROP_ENUMERATE)) {
        return false;
      }
      break;
    } while(false);
  }

  return true;
}

void
UniFFIScaffoldingCallResult::TraceDictionary(JSTracer* trc)
{
  if (mData.WasPassed()) {
    mData.Value().TraceUnion(trc);
  }
}




namespace UniFFIPointer_Binding {

static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
  mozilla::dom::UniFFIPointer* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::UniFFIPointer>(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::UniFFIPointer>(self);
  }
}

bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
  nullptr,
  { nullptr, nullptr, &sNativePropertiesInited },
  prototypes::id::UniFFIPointer,
  constructors::id::UniFFIPointer,
  &DefaultXrayExpandoObjectClass
};

static const DOMInterfaceInfo sInterfaceObjectInfo = {
  { ThrowingConstructor, &sNativePropertyHooks },
  JS::GetRealmFunctionPrototypeHandle,
  PrototypeTraits<prototypes::id::UniFFIPointer>::Depth,
  prototypes::id::UniFFIPointer,
  true,
  0,
  "UniFFIPointer",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "UniFFIPointerPrototype",
    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::UniFFIPointer,
  PrototypeTraits<prototypes::id::UniFFIPointer>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmObjectPrototype
};

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return nsContentUtils::ThreadsafeIsSystemCaller(aCx);
}

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 = {
  { "UniFFIPointer",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::UniFFIPointer>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::UniFFIPointer, 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::UniFFIPointer>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::UniFFIPointer>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::UniFFIPointer>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::UniFFIPointer>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(1 >= 1,
              "Must have enough reserved slots.");

bool
Wrap(JSContext* aCx, mozilla::dom::UniFFIPointer* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::UniFFIPointer>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::UniFFIPointer*>);
  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::UniFFIPointer> 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
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::UniFFIPointer);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::UniFFIPointer);

  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,
                              nullptr,
                              nullptr,
                              "UniFFIPointer",
                              ShouldExpose<UniFFIPointer_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::UniFFIPointer,
                                     &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::UniFFIPointer,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace UniFFIPointer_Binding



namespace UniFFIScaffolding_Binding {

MOZ_CAN_RUN_SCRIPT static bool
callSync(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "UniFFIScaffolding.callSync");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "callSync", 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, "UniFFIScaffolding.callSync", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint64_t arg0;
  if (!ValueToPrimitive<uint64_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  AutoSequence<OwningDoubleOrArrayBufferOrUniFFIPointer> arg1;
  SequenceRooter<OwningDoubleOrArrayBufferOrUniFFIPointer> arg1_holder(cx, &arg1);
  if (args.length() > 1) {
    if (!arg1.SetCapacity(args.length() - 1, mozilla::fallible)) {
      JS_ReportOutOfMemory(cx);
      return false;
    }
    for (uint32_t variadicArg = 1; variadicArg < args.length(); ++variadicArg) {
      // OK to do infallible append here, since we ensured capacity already.
      OwningDoubleOrArrayBufferOrUniFFIPointer& slot = *arg1.AppendElement();
      if (!slot.Init(cx, args[variadicArg], "Argument 2", false)) {
        return false;
      }
    }
  }
  FastErrorResult rv;
  RootedDictionary<UniFFIScaffoldingCallResult> result(cx);
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(mozilla::dom::UniFFIScaffolding::CallSync(global, arg0, Constify(arg1), result, rv))>, "Should be returning void here");
  mozilla::dom::UniFFIScaffolding::CallSync(global, arg0, Constify(arg1), result, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.callSync"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!result.ToObjectInternal(cx, args.rval())) {
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
callAsync(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "UniFFIScaffolding.callAsync");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "callAsync", 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, "UniFFIScaffolding.callAsync", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint64_t arg0;
  if (!ValueToPrimitive<uint64_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  AutoSequence<OwningDoubleOrArrayBufferOrUniFFIPointer> arg1;
  SequenceRooter<OwningDoubleOrArrayBufferOrUniFFIPointer> arg1_holder(cx, &arg1);
  if (args.length() > 1) {
    if (!arg1.SetCapacity(args.length() - 1, mozilla::fallible)) {
      JS_ReportOutOfMemory(cx);
      return false;
    }
    for (uint32_t variadicArg = 1; variadicArg < args.length(); ++variadicArg) {
      // OK to do infallible append here, since we ensured capacity already.
      OwningDoubleOrArrayBufferOrUniFFIPointer& slot = *arg1.AppendElement();
      if (!slot.Init(cx, args[variadicArg], "Argument 2", false)) {
        return false;
      }
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(mozilla::dom::UniFFIScaffolding::CallAsync(global, arg0, Constify(arg1), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.callAsync"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}


static const JSJitInfo callAsync_methodinfo = {
  { (JSJitGetterOp)callAsync },
  { prototypes::id::_ID_Count }, { 0 }, JSJitInfo::StaticMethod,
  JSJitInfo::AliasEverything, JSVAL_TYPE_OBJECT, false, false,
  false, false, 0
};

MOZ_CAN_RUN_SCRIPT static bool
callAsyncWrapper(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "UniFFIScaffolding.callAsyncWrapper");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "callAsyncWrapper", 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, "UniFFIScaffolding.callAsyncWrapper", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint64_t arg0;
  if (!ValueToPrimitive<uint64_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  AutoSequence<OwningDoubleOrArrayBufferOrUniFFIPointer> arg1;
  SequenceRooter<OwningDoubleOrArrayBufferOrUniFFIPointer> arg1_holder(cx, &arg1);
  if (args.length() > 1) {
    if (!arg1.SetCapacity(args.length() - 1, mozilla::fallible)) {
      JS_ReportOutOfMemory(cx);
      return false;
    }
    for (uint32_t variadicArg = 1; variadicArg < args.length(); ++variadicArg) {
      // OK to do infallible append here, since we ensured capacity already.
      OwningDoubleOrArrayBufferOrUniFFIPointer& slot = *arg1.AppendElement();
      if (!slot.Init(cx, args[variadicArg], "Argument 2", false)) {
        return false;
      }
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(mozilla::dom::UniFFIScaffolding::CallAsyncWrapper(global, arg0, Constify(arg1), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.callAsyncWrapper"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}


static const JSJitInfo callAsyncWrapper_methodinfo = {
  { (JSJitGetterOp)callAsyncWrapper },
  { prototypes::id::_ID_Count }, { 0 }, JSJitInfo::StaticMethod,
  JSJitInfo::AliasEverything, JSVAL_TYPE_OBJECT, false, false,
  false, false, 0
};

MOZ_CAN_RUN_SCRIPT static bool
readPointer(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "UniFFIScaffolding.readPointer");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "readPointer", 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, "UniFFIScaffolding.readPointer", 3)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint64_t arg0;
  if (!ValueToPrimitive<uint64_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  RootedSpiderMonkeyInterface<ArrayBuffer> arg1(cx);
  if (args[1].isObject()) {
    if (!arg1.Init(&args[1].toObject())) {
      cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Argument 2", "ArrayBuffer");
      return false;
    }
    if (JS::IsSharedArrayBufferObject(arg1.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("Argument 2");
      return false;
    }
    if (JS::IsLargeArrayBufferMaybeShared(arg1.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("Argument 2");
      return false;
    }
    if (JS::IsResizableArrayBufferMaybeShared(arg1.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("Argument 2");
      return false;
    }
    if (JS::IsImmutableArrayBufferMaybeShared(arg1.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("Argument 2");
      return false;
    }
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 2");
    return false;
  }
  int32_t arg2;
  if (!ValueToPrimitive<int32_t, eDefault>(cx, args[2], "Argument 3", &arg2)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::UniFFIPointer>(mozilla::dom::UniFFIScaffolding::ReadPointer(global, arg0, Constify(arg1), arg2, rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.readPointer"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!GetOrCreateDOMReflector(cx, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
writePointer(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "UniFFIScaffolding.writePointer");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "writePointer", 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, "UniFFIScaffolding.writePointer", 4)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint64_t arg0;
  if (!ValueToPrimitive<uint64_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  NonNull<mozilla::dom::UniFFIPointer> arg1;
  if (args[1].isObject()) {
    {
      // Our JSContext should be in the right global to do unwrapping in.
      nsresult rv = UnwrapObject<prototypes::id::UniFFIPointer, mozilla::dom::UniFFIPointer>(args[1], arg1, cx);
      if (NS_FAILED(rv)) {
        cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Argument 2", "UniFFIPointer");
        return false;
      }
    }
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 2");
    return false;
  }
  RootedSpiderMonkeyInterface<ArrayBuffer> arg2(cx);
  if (args[2].isObject()) {
    if (!arg2.Init(&args[2].toObject())) {
      cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Argument 3", "ArrayBuffer");
      return false;
    }
    if (JS::IsSharedArrayBufferObject(arg2.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_SHARED>("Argument 3");
      return false;
    }
    if (JS::IsLargeArrayBufferMaybeShared(arg2.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_LARGE>("Argument 3");
      return false;
    }
    if (JS::IsResizableArrayBufferMaybeShared(arg2.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_RESIZABLE>("Argument 3");
      return false;
    }
    if (JS::IsImmutableArrayBufferMaybeShared(arg2.Obj())) {
      cx.ThrowErrorMessage<MSG_TYPEDARRAY_IS_IMMUTABLE>("Argument 3");
      return false;
    }
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 3");
    return false;
  }
  int32_t arg3;
  if (!ValueToPrimitive<int32_t, eDefault>(cx, args[3], "Argument 4", &arg3)) {
    return false;
  }
  FastErrorResult rv;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(mozilla::dom::UniFFIScaffolding::WritePointer(global, arg0, MOZ_KnownLive(NonNullHelper(arg1)), Constify(arg2), arg3, rv))>, "Should be returning void here");
  mozilla::dom::UniFFIScaffolding::WritePointer(global, arg0, MOZ_KnownLive(NonNullHelper(arg1)), Constify(arg2), arg3, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.writePointer"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
registerCallbackHandler(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "UniFFIScaffolding.registerCallbackHandler");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "registerCallbackHandler", 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, "UniFFIScaffolding.registerCallbackHandler", 2)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint32_t arg0;
  if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  RootedCallback<OwningNonNull<binding_detail::FastUniFFICallbackHandler>> arg1(cx);
  if (args[1].isObject()) {
    { // scope for tempRoot and tempGlobalRoot if needed
      arg1 = new binding_detail::FastUniFFICallbackHandler(&args[1].toObject(), JS::CurrentGlobalOrNull(cx));
    }
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 2");
    return false;
  }
  FastErrorResult rv;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(mozilla::dom::UniFFIScaffolding::RegisterCallbackHandler(global, arg0, MOZ_KnownLive(NonNullHelper(arg1)), rv))>, "Should be returning void here");
  mozilla::dom::UniFFIScaffolding::RegisterCallbackHandler(global, arg0, MOZ_KnownLive(NonNullHelper(arg1)), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.registerCallbackHandler"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
deregisterCallbackHandler(JSContext* cx, unsigned argc, JS::Value* vp)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "UniFFIScaffolding", "deregisterCallbackHandler", 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, "UniFFIScaffolding.deregisterCallbackHandler", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  uint32_t arg0;
  if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  FastErrorResult rv;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(mozilla::dom::UniFFIScaffolding::DeregisterCallbackHandler(global, arg0, rv))>, "Should be returning void here");
  mozilla::dom::UniFFIScaffolding::DeregisterCallbackHandler(global, arg0, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "UniFFIScaffolding.deregisterCallbackHandler"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

MOZ_GLOBINIT static const JSFunctionSpec sStaticMethods_specs[] = {
  JS_FNSPEC("callSync", callSync, nullptr, 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("callAsync", StaticMethodPromiseWrapper, &callAsync_methodinfo, 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("callAsyncWrapper", StaticMethodPromiseWrapper, &callAsyncWrapper_methodinfo, 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("readPointer", readPointer, nullptr, 3, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("writePointer", writePointer, nullptr, 4, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("registerCallbackHandler", registerCallbackHandler, nullptr, 2, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("deregisterCallbackHandler", deregisterCallbackHandler, nullptr, 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(7 <= 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<1> sNativeProperties = {
  true,  0 /* sStaticMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  -1,
  7,
  sNativeProperties_sortedPropertyIndices,
  {
    { sStaticMethods, &sNativeProperties_propertyInfos[0] }
  }
};
static_assert(7 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
  nullptr,
  { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
  prototypes::id::_ID_Count,
  constructors::id::UniFFIScaffolding,
  &DefaultXrayExpandoObjectClass
};

static const DOMIfaceAndProtoJSClass sNamespaceObjectClass = {
  {
    "UniFFIScaffolding",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS,
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  eNamespace,
  prototypes::id::_ID_Count,
  0,
  &sNativePropertyHooks,
  // This isn't strictly following the spec (see
  // https://console.spec.whatwg.org/#ref-for-dfn-namespace-object),
  // but should be ok for Xrays.
  JS::GetRealmObjectPrototype
};

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return nsContentUtils::ThreadsafeIsSystemCaller(aCx);
}

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
  JS::Rooted<JSObject*> constructorProto(aCx, JS::GetRealmObjectPrototype(aCx));
  if (!constructorProto) {
    return;
  }

  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::UniFFIScaffolding);
  dom::CreateNamespaceObject(aCx, aGlobal, constructorProto,
                             sNamespaceObjectClass,
                             interfaceCache,
                             sNativeProperties.Upcast(),
                             nullptr,
                             "UniFFIScaffolding",
                             ShouldExpose<UniFFIScaffolding_Binding::ConstructorEnabled>(aCx, aGlobal, aDefineOnGlobal));
}

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::UniFFIScaffolding,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace UniFFIScaffolding_Binding



already_AddRefed<Promise>
UniFFICallbackHandler::CallAsync(uint64_t objectHandle, uint32_t methodIndex, const nsTArray<OwningDoubleOrArrayBufferOrUniFFIPointer>& args, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "UniFFICallbackHandler.callAsync", aExceptionHandling, aRealm);
  if (aRv.Failed()) {
    return nullptr;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);
  JS::RootedVector<JS::Value> argv(cx);
  if (!argv.resize((3 - 1) + args.Length())) {
    // That threw an exception on the JSContext, and our CallSetup will do
    // the right thing with that.
    return nullptr;
  }
  unsigned argc = (3 - 1) + args.Length();

  do {
    for (uint32_t idx = 0; idx < args.Length(); ++idx) {
      JS::Rooted<JSObject*> callbackObj(cx, CallbackKnownNotGray());
      if (!args[idx].ToJSVal(cx, callbackObj, argv[2 + idx])) {
        aRv.Throw(NS_ERROR_UNEXPECTED);
        return nullptr;
      }
      continue;
    }
    break;
  } while (false);

  do {
    argv[1].setNumber(methodIndex);
    break;
  } while (false);

  do {
    argv[0].set(JS_NumberValue(double(objectHandle)));
    break;
  } while (false);

  JS::Rooted<JS::Value> callable(cx);
  UniFFICallbackHandlerAtoms* atomsCache = GetAtomCache<UniFFICallbackHandlerAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->callAsync_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::subarray(argv, 0, argc), &rval)) {
    aRv.NoteJSContextException(cx);
    return nullptr;
  }
  RefPtr<Promise> rvalDecl;
  { // Scope for our GlobalObject, FastErrorResult, JSAutoRealm,
    // etc.

    JS::Rooted<JSObject*> globalObj(cx);
    // We basically want our entry global here.  Play it safe
    // and use GetEntryGlobal() to get it, with whatever
    // principal-clamping it ends up doing.
    globalObj = GetEntryGlobal()->GetGlobalJSObject();
    JSAutoRealm ar(cx, globalObj);
    GlobalObject promiseGlobal(cx, globalObj);
    if (promiseGlobal.Failed()) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    JS::Rooted<JS::Value> valueToResolve(cx, rval);
    if (!JS_WrapValue(cx, &valueToResolve)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    binding_detail::FastErrorResult promiseRv;
    nsCOMPtr<nsIGlobalObject> global =
      do_QueryInterface(promiseGlobal.GetAsSupports());
    if (!global) {
      promiseRv.Throw(NS_ERROR_UNEXPECTED);
      MOZ_ALWAYS_TRUE(promiseRv.MaybeSetPendingException(cx));
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
    rvalDecl = Promise::Resolve(global, cx, valueToResolve,
                                    promiseRv);
    if (promiseRv.MaybeSetPendingException(cx)) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }
  }
  return rvalDecl.forget();
}

void
UniFFICallbackHandler::CallSync(uint64_t objectHandle, uint32_t methodIndex, const nsTArray<OwningDoubleOrArrayBufferOrUniFFIPointer>& args, UniFFIScaffoldingCallResult& aRetVal, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "UniFFICallbackHandler.callSync", aExceptionHandling, aRealm);
  if (aRv.Failed()) {
    return;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);
  JS::RootedVector<JS::Value> argv(cx);
  if (!argv.resize((3 - 1) + args.Length())) {
    // That threw an exception on the JSContext, and our CallSetup will do
    // the right thing with that.
    return;
  }
  unsigned argc = (3 - 1) + args.Length();

  do {
    for (uint32_t idx = 0; idx < args.Length(); ++idx) {
      JS::Rooted<JSObject*> callbackObj(cx, CallbackKnownNotGray());
      if (!args[idx].ToJSVal(cx, callbackObj, argv[2 + idx])) {
        aRv.Throw(NS_ERROR_UNEXPECTED);
        return;
      }
      continue;
    }
    break;
  } while (false);

  do {
    argv[1].setNumber(methodIndex);
    break;
  } while (false);

  do {
    argv[0].set(JS_NumberValue(double(objectHandle)));
    break;
  } while (false);

  JS::Rooted<JS::Value> callable(cx);
  UniFFICallbackHandlerAtoms* atomsCache = GetAtomCache<UniFFICallbackHandlerAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->callSync_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::subarray(argv, 0, argc), &rval)) {
    aRv.NoteJSContextException(cx);
    return;
  }
  UniFFIScaffoldingCallResult& rvalDecl(aRetVal);
  if (!rvalDecl.Init(cx, rval, "Return value of UniFFICallbackHandler.callSync", false)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
}

void
UniFFICallbackHandler::Destroy(uint64_t objectHandle, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm)
{
  CallSetup s(this, aRv, "UniFFICallbackHandler.destroy", aExceptionHandling, aRealm);
  if (aRv.Failed()) {
    return;
  }
  MOZ_ASSERT(s.GetContext());
  BindingCallContext& cx = s.GetCallContext();

  JS::Rooted<JS::Value> rval(cx);
  JS::RootedVector<JS::Value> argv(cx);
  if (!argv.resize(1)) {
    // That threw an exception on the JSContext, and our CallSetup will do
    // the right thing with that.
    return;
  }
  unsigned argc = 1;

  do {
    argv[0].set(JS_NumberValue(double(objectHandle)));
    break;
  } while (false);

  JS::Rooted<JS::Value> callable(cx);
  UniFFICallbackHandlerAtoms* atomsCache = GetAtomCache<UniFFICallbackHandlerAtoms>(cx);
  if ((reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
       !InitIds(cx, atomsCache)) ||
      !GetCallableProperty(cx, atomsCache->destroy_id, &callable)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return;
  }
  JS::Rooted<JS::Value> thisValue(cx, JS::ObjectValue(*mCallback));
  if (!JS::Call(cx, thisValue, callable,
                JS::HandleValueArray::subarray(argv, 0, argc), &rval)) {
    aRv.NoteJSContextException(cx);
    return;
  }
}

bool
UniFFICallbackHandler::InitIds(JSContext* cx, UniFFICallbackHandlerAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->destroy_id.init(cx, "destroy") ||
      !atomsCache->callSync_id.init(cx, "callSync") ||
      !atomsCache->callAsync_id.init(cx, "callAsync")) {
    return false;
  }
  return true;
}



} // namespace dom


} // namespace mozilla
