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

#include <type_traits>
#include "AtomList.h"
#include "CSSStyleSheetBinding.h"
#include "MainThreadUtils.h"
#include "StyleSheetBinding.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 "mozilla/Atomics.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/css/Rule.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/CSSRuleList.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/MediaList.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/Nullable.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsContentUtils.h"
#include "nsJSPrincipals.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<CSSStyleSheetParsingMode>::Values[3];
} // namespace binding_detail

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


void
ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, OwningMediaListOrUTF8String& aUnion, const char* aName, uint32_t aFlags)
{
  if (aUnion.IsMediaList()) {
    ImplCycleCollectionTraverse(aCallback, aUnion.GetAsMediaList(), "mMediaList", aFlags);
  }
}


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


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

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







bool
MediaListOrUTF8String::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
MediaListOrUTF8String::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 = !TrySetToMediaList(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, "MediaList");
    return false;
  }
  return true;
}

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


bool
MediaListOrUTF8String::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eMediaList: {
      if (!GetOrCreateDOMReflector(cx, mValue.mMediaList.Value(), rval)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    case eUTF8String: {
      if (!NonVoidUTF8StringToJsval(cx, mValue.mUTF8String.Value(), rval)) {
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}



OwningMediaListOrUTF8String::OwningMediaListOrUTF8String(OwningMediaListOrUTF8String&& aOther)
  : mType(eUninitialized)
{
  switch (aOther.mType) {
    case eUninitialized: {
      MOZ_ASSERT(mType == eUninitialized,
                 "We need to destroy ourselves?");
      break;
    }
    case eMediaList: {
      mType = eMediaList;
      mValue.mMediaList.SetValue(std::move(aOther.mValue.mMediaList.Value()));
      break;
    }
    case eUTF8String: {
      mType = eUTF8String;
      mValue.mUTF8String.SetValue(std::move(aOther.mValue.mUTF8String.Value()));
      break;
    }
  }
}



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

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

[[nodiscard]] OwningNonNull<mozilla::dom::MediaList>&
OwningMediaListOrUTF8String::RawSetAsMediaList()
{
  if (mType == eMediaList) {
    return mValue.mMediaList.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eMediaList;
  return mValue.mMediaList.SetValue();
}

[[nodiscard]] OwningNonNull<mozilla::dom::MediaList>&
OwningMediaListOrUTF8String::SetAsMediaList()
{
  if (mType == eMediaList) {
    return mValue.mMediaList.Value();
  }
  Uninit();
  mType = eMediaList;
  return mValue.mMediaList.SetValue();
}


void
OwningMediaListOrUTF8String::DestroyMediaList()
{
  MOZ_RELEASE_ASSERT(IsMediaList(), "Wrong type!");
  mValue.mMediaList.Destroy();
  mType = eUninitialized;
}



bool
OwningMediaListOrUTF8String::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&
OwningMediaListOrUTF8String::RawSetAsUTF8String()
{
  if (mType == eUTF8String) {
    return mValue.mUTF8String.Value();
  }
  MOZ_ASSERT(mType == eUninitialized);
  mType = eUTF8String;
  return mValue.mUTF8String.SetValue();
}

[[nodiscard]] nsCString&
OwningMediaListOrUTF8String::SetAsUTF8String()
{
  if (mType == eUTF8String) {
    return mValue.mUTF8String.Value();
  }
  Uninit();
  mType = eUTF8String;
  return mValue.mUTF8String.SetValue();
}



void
OwningMediaListOrUTF8String::DestroyUTF8String()
{
  MOZ_RELEASE_ASSERT(IsUTF8String(), "Wrong type!");
  mValue.mUTF8String.Destroy();
  mType = eUninitialized;
}



bool
OwningMediaListOrUTF8String::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 = !TrySetToMediaList(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, "MediaList");
    return false;
  }
  return true;
}

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

void
OwningMediaListOrUTF8String::Uninit()
{
  switch (mType) {
    case eUninitialized: {
      break;
    }
    case eMediaList: {
      DestroyMediaList();
      break;
    }
    case eUTF8String: {
      DestroyUTF8String();
      break;
    }
  }
}

bool
OwningMediaListOrUTF8String::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
{
  switch (mType) {
    case eUninitialized: {
      return false;
    }
    case eMediaList: {
      if (!GetOrCreateDOMReflector(cx, mValue.mMediaList.Value(), rval)) {
        MOZ_ASSERT(JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    case eUTF8String: {
      if (!NonVoidUTF8StringToJsval(cx, mValue.mUTF8String.Value(), rval)) {
        return false;
      }
      return true;
    }
    default: {
      return false;
    }
  }
}

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


OwningMediaListOrUTF8String&
OwningMediaListOrUTF8String::operator=(const OwningMediaListOrUTF8String& aOther)
{
  switch (aOther.mType) {
    case eUninitialized: {
      MOZ_ASSERT(mType == eUninitialized,
                 "We need to destroy ourselves?");
      break;
    }
    case eMediaList: {
      SetAsMediaList() = aOther.GetAsMediaList();
      break;
    }
    case eUTF8String: {
      SetAsUTF8String() = aOther.GetAsUTF8String();
      break;
    }
  }
  return *this;
}



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




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

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->media_id.init(cx, "media") ||
      !atomsCache->disabled_id.init(cx, "disabled") ||
      !atomsCache->baseURL_id.init(cx, "baseURL")) {
    return false;
  }
  return true;
}

bool
CSSStyleSheetInit::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());
  CSSStyleSheetInitAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<CSSStyleSheetInitAtoms>(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->baseURL_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    mBaseURL.Construct();
    if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, (mBaseURL.Value()))) {
      return false;
    }
    mIsAnyMemberPresent = true;
  }

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->disabled_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'disabled' member of CSSStyleSheetInit", &mDisabled)) {
      return false;
    }
  } else {
    mDisabled = false;
  }
  mIsAnyMemberPresent = true;

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->media_id, temp.ptr())) {
      return false;
    }
  }
  mMedia.Uninit();
  if (!(!isNull && !temp->isUndefined())) {
    mMedia.SetStringLiteral("");
  } else {
    if (!mMedia.Init(cx, temp.ref(), "'media' member of CSSStyleSheetInit", passedToJSImpl)) {
      return false;
    }
  }
  mIsAnyMemberPresent = true;
  return true;
}

bool
CSSStyleSheetInit::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
CSSStyleSheetInit::TraceDictionary(JSTracer* trc)
{
}



CSSStyleSheetInit&
CSSStyleSheetInit::operator=(const CSSStyleSheetInit& aOther)
{
  DictionaryBase::operator=(aOther);
  mBaseURL.Reset();
  if (aOther.mBaseURL.WasPassed()) {
    mBaseURL.Construct(aOther.mBaseURL.Value());
  }
  mDisabled = aOther.mDisabled;
  mMedia = aOther.mMedia;
  return *this;
}


namespace CSSStyleSheet_Binding {

static_assert(IsRefcounted<NativeType>::value == IsRefcounted<StyleSheet_Binding::NativeType>::value,
              "Can't inherit from an interface with a different ownership model.");

MOZ_CAN_RUN_SCRIPT static bool
get_ownerRule(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "ownerRule", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  auto result(StrongOrRawPtr<mozilla::css::Rule>(MOZ_KnownLive(self)->GetDOMOwnerRule()));
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!result) {
    args.rval().setNull();
    return true;
  }
  if (!GetOrCreateDOMReflector(cx, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo ownerRule_getterinfo = {
  { get_ownerRule },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasDOMSets, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNKNOWN,  /* 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. */
  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_cssRules(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "cssRules", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  auto result(StrongOrRawPtr<mozilla::dom::CSSRuleList>(MOZ_KnownLive(self)->GetCssRules(MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.cssRules getter"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!GetOrCreateDOMReflector(cx, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo cssRules_getterinfo = {
  { get_cssRules },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::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_parsingMode(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "parsingMode", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  CSSStyleSheetParsingMode result(MOZ_KnownLive(self)->ParsingModeDOM());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo parsingMode_getterinfo = {
  { get_parsingMode },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::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
insertRule(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "insertRule", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  if (!args.requireAtLeast(cx, "CSSStyleSheet.insertRule", 1)) {
    return false;
  }
  binding_detail::FakeString<char> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  uint32_t arg1;
  if (args.hasDefined(1)) {
    if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[1], "Argument 2", &arg1)) {
      return false;
    }
  } else {
    arg1 = 0U;
  }
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  uint32_t result(MOZ_KnownLive(self)->InsertRule(Constify(arg0), arg1, MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.insertRule"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setNumber(result);
  return true;
}

static const JSJitInfo insertRule_methodinfo = {
  { (JSJitGetterOp)insertRule },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_DOUBLE,  /* 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
deleteRule(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "deleteRule", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  if (!args.requireAtLeast(cx, "CSSStyleSheet.deleteRule", 1)) {
    return false;
  }
  uint32_t arg0;
  if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
    return false;
  }
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->DeleteRule(arg0, MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv))>, "Should be returning void here");
  MOZ_KnownLive(self)->DeleteRule(arg0, MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.deleteRule"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo deleteRule_methodinfo = {
  { (JSJitGetterOp)deleteRule },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth },
  JSJitInfo::Method,
  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
replace(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "replace", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  if (!args.requireAtLeast(cx, "CSSStyleSheet.replace", 1)) {
    return false;
  }
  binding_detail::FakeString<char> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->Replace(Constify(arg0), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.replace"))) {
    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
replace_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = replace(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo replace_methodinfo = {
  { (JSJitGetterOp)replace_promiseWrapper },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::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
replaceSync(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "replaceSync", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  if (!args.requireAtLeast(cx, "CSSStyleSheet.replaceSync", 1)) {
    return false;
  }
  binding_detail::FakeString<char> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  FastErrorResult rv;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->ReplaceSync(Constify(arg0), rv))>, "Should be returning void here");
  MOZ_KnownLive(self)->ReplaceSync(Constify(arg0), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.replaceSync"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo replaceSync_methodinfo = {
  { (JSJitGetterOp)replaceSync },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth },
  JSJitInfo::Method,
  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_rules(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "rules", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  auto result(StrongOrRawPtr<mozilla::dom::CSSRuleList>(MOZ_KnownLive(self)->GetCssRules(MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.rules getter"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!GetOrCreateDOMReflector(cx, result, args.rval())) {
    MOZ_ASSERT(JS_IsExceptionPending(cx));
    return false;
  }
  return true;
}

static const JSJitInfo rules_getterinfo = {
  { get_rules },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::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
removeRule(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "removeRule", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  uint32_t arg0;
  if (args.hasDefined(0)) {
    if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[0], "Argument 1", &arg0)) {
      return false;
    }
  } else {
    arg0 = 0U;
  }
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->DeleteRule(arg0, MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv))>, "Should be returning void here");
  MOZ_KnownLive(self)->DeleteRule(arg0, MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.removeRule"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo removeRule_methodinfo = {
  { (JSJitGetterOp)removeRule },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth },
  JSJitInfo::Method,
  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
addRule(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "addRule", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::StyleSheet*>(void_self);
  binding_detail::FakeString<char> arg0;
  if (args.hasDefined(0)) {
    if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
      return false;
    }
  } else {
    arg0.AssignLiteral("undefined");
  }
  binding_detail::FakeString<char> arg1;
  if (args.hasDefined(1)) {
    if (!ConvertJSValueToString(cx, args[1], eStringify, eStringify, arg1)) {
      return false;
    }
  } else {
    arg1.AssignLiteral("undefined");
  }
  Optional<uint32_t> arg2;
  if (args.hasDefined(2)) {
    arg2.Construct();
    if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[2], "Argument 3", &arg2.Value())) {
      return false;
    }
  }
  FastErrorResult rv;
  NonNull<nsIPrincipal> subjectPrincipal;
  {
    JS::Realm* realm = js::GetContextRealm(cx);
    MOZ_ASSERT(realm);
    JSPrincipals* principals = JS::GetRealmPrincipals(realm);
    nsIPrincipal* principal = nsJSPrincipals::get(principals);

    subjectPrincipal = principal;
  }
  int32_t result(MOZ_KnownLive(self)->AddRule(Constify(arg0), Constify(arg1), Constify(arg2), MOZ_KnownLive(NonNullHelper(subjectPrincipal)), rv));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet.addRule"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setInt32(int32_t(result));
  return true;
}

static const JSJitInfo addRule_methodinfo = {
  { (JSJitGetterOp)addRule },
  { prototypes::id::CSSStyleSheet },
  { PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_INT32,  /* 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. */
};

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

MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("insertRule", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&insertRule_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("deleteRule", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&deleteRule_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("replace", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&replace_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("replaceSync", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&replaceSync_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("removeRule", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&removeRule_methodinfo), 0, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("addRule", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&addRule_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(6 <= 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("ownerRule", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &ownerRule_getterinfo, nullptr, nullptr),
  JSPropertySpec::nativeAccessors("cssRules", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &cssRules_getterinfo, nullptr, nullptr),
  JSPropertySpec::nativeAccessors("rules", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &rules_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(3 <= 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 sChromeAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("parsingMode", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &parsingMode_getterinfo, nullptr, nullptr),
  JS_PS_END
};


static const Prefable<const JSPropertySpec> sChromeAttributes[] = {
  { nullptr, &sChromeAttributes_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)");


static uint16_t sNativeProperties_sortedPropertyIndices[9];
static PropertyInfo sNativeProperties_propertyInfos[9];

static const NativePropertiesN<2> sNativeProperties = {
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  true,  1 /* sAttributes */,
  false, 0,
  false, 0,
  false, 0,
  -1,
  9,
  sNativeProperties_sortedPropertyIndices,
  {
    { sMethods, &sNativeProperties_propertyInfos[0] },
    { sAttributes, &sNativeProperties_propertyInfos[6] }
  }
};
static_assert(9 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

static uint16_t sChromeOnlyNativeProperties_sortedPropertyIndices[1];
static PropertyInfo sChromeOnlyNativeProperties_propertyInfos[1];

static const NativePropertiesN<1> sChromeOnlyNativeProperties = {
  false, 0,
  false, 0,
  false, 0,
  true,  0 /* sChromeAttributes */,
  false, 0,
  false, 0,
  false, 0,
  -1,
  1,
  sChromeOnlyNativeProperties_sortedPropertyIndices,
  {
    { sChromeAttributes, &sChromeOnlyNativeProperties_propertyInfos[0] }
  }
};
static_assert(1 < 1ull << (CHAR_BIT * sizeof(sChromeOnlyNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

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

static bool
_constructor(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "CSSStyleSheet constructor");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "CSSStyleSheet", "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, "CSSStyleSheet");
  }

  JS::Rooted<JSObject*> desiredProto(cx);
  if (!GetDesiredProto(cx, args,
                       prototypes::id::CSSStyleSheet,
                       CreateInterfaceObjects,
                       &desiredProto)) {
    return false;
  }

  GlobalObject global(cx, obj);
  if (global.Failed()) {
    return false;
  }

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  binding_detail::FastCSSStyleSheetInit arg0;
  if (!arg0.Init(cx, (args.hasDefined(0)) ? args[0] : JS::NullHandleValue, "Argument 1", false)) {
    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;
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::StyleSheet>(mozilla::StyleSheet::Constructor(global, Constify(arg0), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "CSSStyleSheet 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 },
  StyleSheet_Binding::GetConstructorObjectHandle,
  PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth,
  prototypes::id::CSSStyleSheet,
  true,
  0,
  "CSSStyleSheet",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "CSSStyleSheetPrototype",
    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::CSSStyleSheet,
  PrototypeTraits<prototypes::id::CSSStyleSheet>::Depth,
  &sNativePropertyHooks,
  StyleSheet_Binding::GetProtoObject
};

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 = {
  { "CSSStyleSheet",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::StyleSheet>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::StyleSheet, prototypes::id::CSSStyleSheet, 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::StyleSheet>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::StyleSheet>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::StyleSheet>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::StyleSheet>::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::StyleSheet* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::StyleSheet>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::StyleSheet*>);
  MOZ_ASSERT(static_cast<mozilla::StyleSheet*>(aObject) ==
             reinterpret_cast<mozilla::StyleSheet*>(aObject),
             "Multiple inheritance for mozilla::StyleSheet is broken.");
  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::StyleSheet> 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::CSSStyleSheet);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::CSSStyleSheet);

  JS::Handle<JSObject*> parentProto(StyleSheet_Binding::GetProtoObjectHandle(aCx));
  if (!parentProto) {
    return;
  }

  JS::Handle<JSObject*> constructorProto(StyleSheet_Binding::GetConstructorObjectHandle(aCx));
  if (!constructorProto) {
    return;
  }

  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass, protoCache,
                              constructorProto, &sInterfaceObjectInfo, 0, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              sChromeOnlyNativeProperties.Upcast(),
                              "CSSStyleSheet",
                              aDefineOnGlobal != DefineInterfaceProperty::No,
                              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::CSSStyleSheet,
                                     &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::CSSStyleSheet,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace CSSStyleSheet_Binding



} // namespace dom


} // namespace mozilla
