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

#include "HTMLCollectionBinding.h"
#include "HTMLOptionsCollectionBinding.h"
#include "WrapperFactory.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/DOMJSProxyHandler.h"
#include "mozilla/dom/HTMLOptionElement.h"
#include "mozilla/dom/HTMLOptionsCollection.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/Nullable.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/UnionConversions.h"
#include "mozilla/dom/UnionTypes.h"
#include "mozilla/dom/XrayExpandoClass.h"

namespace mozilla {
namespace dom {

namespace HTMLOptionsCollectionBinding {

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

static bool
get_length(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::HTMLOptionsCollection* self, JSJitGetterCallArgs args)
{
  uint32_t result(self->Length());
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setNumber(result);
  return true;
}

static bool
set_length(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::HTMLOptionsCollection* self, JSJitSetterCallArgs args)
{
  uint32_t arg0;
  if (!ValueToPrimitive<uint32_t, eDefault>(cx, args[0], &arg0)) {
    return false;
  }
  self->SetLength(arg0);
  MOZ_ASSERT(!JS_IsExceptionPending(cx));

  return true;
}

static const JSJitInfo length_getterinfo = {
  { (JSJitGetterOp)get_length },
  { prototypes::id::HTMLOptionsCollection },
  { PrototypeTraits<prototypes::id::HTMLOptionsCollection>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_DOUBLE,  /* returnType.  Not relevant for setters. */
  true,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");
static const JSJitInfo length_setterinfo = {
  { (JSJitGetterOp)set_length },
  { prototypes::id::HTMLOptionsCollection },
  { PrototypeTraits<prototypes::id::HTMLOptionsCollection>::Depth },
  JSJitInfo::Setter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
add(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::HTMLOptionsCollection* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 1)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "HTMLOptionsCollection.add");
  }
  HTMLOptionElementOrHTMLOptGroupElement arg0;
  HTMLOptionElementOrHTMLOptGroupElementArgument arg0_holder(arg0);
  {
    bool done = false, failed = false, tryNext;
    if (args[0].isObject()) {
      done = (failed = !arg0_holder.TrySetToHTMLOptionElement(cx, args[0], tryNext, false)) || !tryNext ||
             (failed = !arg0_holder.TrySetToHTMLOptGroupElement(cx, args[0], tryNext, false)) || !tryNext;

    }
    if (failed) {
      return false;
    }
    if (!done) {
      ThrowErrorMessage(cx, MSG_NOT_IN_UNION, "Argument 1 of HTMLOptionsCollection.add", "HTMLOptionElement, HTMLOptGroupElement");
      return false;
    }
  }
  Nullable<HTMLElementOrLong > arg1;
  Maybe<HTMLElementOrLongArgument> arg1_holder;
  if (!(args.hasDefined(1)) || args[1].isNullOrUndefined()) {
    arg1.SetNull();
  } else {
    arg1_holder.emplace(arg1.SetValue());
    {
      bool done = false, failed = false, tryNext;
      if (args[1].isObject()) {
        done = (failed = !arg1_holder.ref().TrySetToHTMLElement(cx, args[1], tryNext, false)) || !tryNext;

      }
      if (!done) {
        do {
          done = (failed = !arg1_holder.ref().TrySetToLong(cx, args[1], tryNext)) || !tryNext;
          break;
        } while (0);
      }
      if (failed) {
        return false;
      }
      if (!done) {
        ThrowErrorMessage(cx, MSG_NOT_IN_UNION, "Argument 2 of HTMLOptionsCollection.add", "HTMLElement");
        return false;
      }
    }
  }
  binding_detail::FastErrorResult rv;
  self->Add(Constify(arg0), Constify(arg1), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo add_methodinfo = {
  { (JSJitGetterOp)add },
  { prototypes::id::HTMLOptionsCollection },
  { PrototypeTraits<prototypes::id::HTMLOptionsCollection>::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. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
remove(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::HTMLOptionsCollection* self, const JSJitMethodCallArgs& args)
{
  if (MOZ_UNLIKELY(args.length() < 1)) {
    return ThrowErrorMessage(cx, MSG_MISSING_ARGUMENTS, "HTMLOptionsCollection.remove");
  }
  int32_t arg0;
  if (!ValueToPrimitive<int32_t, eDefault>(cx, args[0], &arg0)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  self->Remove(arg0, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setUndefined();
  return true;
}

static const JSJitInfo remove_methodinfo = {
  { (JSJitGetterOp)remove },
  { prototypes::id::HTMLOptionsCollection },
  { PrototypeTraits<prototypes::id::HTMLOptionsCollection>::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. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static bool
get_selectedIndex(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::HTMLOptionsCollection* self, JSJitGetterCallArgs args)
{
  binding_detail::FastErrorResult rv;
  int32_t result(self->GetSelectedIndex(rv));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().setInt32(int32_t(result));
  return true;
}

static bool
set_selectedIndex(JSContext* cx, JS::Handle<JSObject*> obj, mozilla::dom::HTMLOptionsCollection* self, JSJitSetterCallArgs args)
{
  int32_t arg0;
  if (!ValueToPrimitive<int32_t, eDefault>(cx, args[0], &arg0)) {
    return false;
  }
  binding_detail::FastErrorResult rv;
  self->SetSelectedIndex(arg0, rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));

  return true;
}

static const JSJitInfo selectedIndex_getterinfo = {
  { (JSJitGetterOp)get_selectedIndex },
  { prototypes::id::HTMLOptionsCollection },
  { PrototypeTraits<prototypes::id::HTMLOptionsCollection>::Depth },
  JSJitInfo::Getter,
  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_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");
static const JSJitInfo selectedIndex_setterinfo = {
  { (JSJitGetterOp)set_selectedIndex },
  { prototypes::id::HTMLOptionsCollection },
  { PrototypeTraits<prototypes::id::HTMLOptionsCollection>::Depth },
  JSJitInfo::Setter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_UNDEFINED,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};
static_assert(0 <= JSJitInfo::maxSlotIndex, "We won't fit");
static_assert(0 < 1, "There is no slot for us");

static void
_objectMoved(JSObject* obj, const JSObject* old)
{
  mozilla::dom::HTMLOptionsCollection* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::HTMLOptionsCollection>(obj);
  if (self) {
    UpdateWrapper(self, self, obj, old);
  }
}

static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("add", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&add_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("remove", GenericBindingMethod, reinterpret_cast<const JSJitInfo*>(&remove_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_SYM_FNSPEC(iterator, nullptr, nullptr, 0, JSPROP_ENUMERATE, "ArrayValues"),
  JS_FS_END
};


// Can't be const because the pref-enabled boolean needs to be writable
static Prefable<const JSFunctionSpec> sMethods[] = {
  { nullptr, &sMethods_specs[0] },
  { nullptr, nullptr }
};

static jsid sMethods_ids[4];

static const JSPropertySpec sAttributes_specs[] = {
  { "length", JSPROP_SHARED | JSPROP_ENUMERATE, { { { { GenericBindingGetter, &length_getterinfo } }, { { GenericBindingSetter, &length_setterinfo } } } } },
  { "selectedIndex", JSPROP_SHARED | JSPROP_ENUMERATE, { { { { GenericBindingGetter, &selectedIndex_getterinfo } }, { { GenericBindingSetter, &selectedIndex_setterinfo } } } } },
  JS_PS_END
};


// Can't be const because the pref-enabled boolean needs to be writable
static Prefable<const JSPropertySpec> sAttributes[] = {
  { nullptr, &sAttributes_specs[0] },
  { nullptr, nullptr }
};

static jsid sAttributes_ids[3];


static const NativePropertiesN<2> sNativeProperties = {
  -1,
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  true,  1 /* sAttributes */,
  false, 0,
  false, 0,
  false, 0,
  {
    { sMethods, sMethods_ids, sMethods_specs },
    { sAttributes, sAttributes_ids, sAttributes_specs }
  }
};

static const DOMIfaceAndProtoJSClass sInterfaceObjectClass = {
  {
    "Function",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_SLOTS_BASE),
    &sBoringInterfaceObjectClassClassOps,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    &sInterfaceObjectClassObjectOps
  },
  eInterface,
  true,
  prototypes::id::HTMLOptionsCollection,
  PrototypeTraits<prototypes::id::HTMLOptionsCollection>::Depth,
  sNativePropertyHooks,
  "function HTMLOptionsCollection() {\n    [native code]\n}",
  HTMLCollectionBinding::GetConstructorObject
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "HTMLOptionsCollectionPrototype",
    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,
  false,
  prototypes::id::HTMLOptionsCollection,
  PrototypeTraits<prototypes::id::HTMLOptionsCollection>::Depth,
  sNativePropertyHooks,
  "[object HTMLOptionsCollectionPrototype]",
  HTMLCollectionBinding::GetProtoObject
};

JSObject*
DefineDOMInterface(JSContext* aCx, JS::Handle<JSObject*> aGlobal, JS::Handle<jsid> id, bool aDefineOnGlobal)
{
  return GetConstructorObjectHandle(aCx, aDefineOnGlobal);
}

static_assert(IsBaseOf<nsISupports, mozilla::dom::HTMLOptionsCollection >::value,
                  "We don't support non-nsISupports native classes for "
                  "proxy-based bindings yet");


class DOMProxyHandler : public mozilla::dom::DOMProxyHandler
{
public:
  explicit constexpr DOMProxyHandler()
  {
  }

  virtual bool
  getOwnPropDescriptor(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool ignoreNamedProps, JS::MutableHandle<JS::PropertyDescriptor> desc) const override;

  virtual bool
  defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, JS::Handle<JS::PropertyDescriptor> desc, JS::ObjectOpResult& opresult, bool* defined) const override;

  using mozilla::dom::DOMProxyHandler::defineProperty;

  virtual bool
  ownPropNames(JSContext* cx, JS::Handle<JSObject*> proxy, unsigned flags, JS::AutoIdVector& props) const override;

  virtual bool
  hasOwn(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp) const override;

  virtual bool
  get(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<JS::Value> receiver, JS::Handle<jsid> id, JS::MutableHandle<JS::Value> vp) const override;

  virtual const char*
  className(JSContext* cx, JS::Handle<JSObject*> proxy) const override;

  virtual bool
  finalizeInBackground(const JS::Value& priv) const override;

  virtual void
  finalize(JSFreeOp* fop, JSObject* proxy) const override;

  static const DOMProxyHandler*
  getInstance();

  virtual bool
  delete_(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, JS::ObjectOpResult& opresult) const override;

  virtual bool
  getElements(JSContext* cx, JS::Handle<JSObject*> proxy, uint32_t begin, uint32_t end, js::ElementAdder* adder) const override;

  virtual bool
  setCustom(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, JS::Handle<JS::Value> v, bool* done) const override;
};

MOZ_ALWAYS_INLINE bool
IsProxy(JSObject* obj)
{
  return js::IsProxy(obj) && js::GetProxyHandler(obj) == DOMProxyHandler::getInstance();
}

MOZ_ALWAYS_INLINE mozilla::dom::HTMLOptionsCollection*
UnwrapProxy(JSObject* obj)
{
  MOZ_ASSERT(js::IsProxy(obj));
  if (js::GetProxyHandler(obj) != DOMProxyHandler::getInstance()) {
    MOZ_ASSERT(xpc::WrapperFactory::IsXrayWrapper(obj));
    obj = js::UncheckedUnwrap(obj);
  }
  MOZ_ASSERT(IsProxy(obj));
  return static_cast<mozilla::dom::HTMLOptionsCollection*>(js::GetProxyPrivate(obj).toPrivate());
}

bool
DOMProxyHandler::getOwnPropDescriptor(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool ignoreNamedProps, JS::MutableHandle<JS::PropertyDescriptor> desc) const
{
  bool isXray = xpc::WrapperFactory::IsXrayWrapper(proxy);
  uint32_t index = GetArrayIndexFromId(cx, id);
  if (IsArrayIndex(index)) {
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    bool found = false;
    auto result(StrongOrRawPtr<mozilla::dom::Element>(self->IndexedGetter(index, found)));
    MOZ_ASSERT(!JS_IsExceptionPending(cx));

    if (found) {
      if (!result) {
        desc.value().setNull();
        FillPropertyDescriptor(desc, proxy, false);
        return true;
      }
      if (!GetOrCreateDOMReflector(cx, result, desc.value())) {
        MOZ_ASSERT(true || JS_IsExceptionPending(cx));
        return false;
      }
      FillPropertyDescriptor(desc, proxy, false);
      return true;
    }
  }

  JS::Rooted<JSObject*> expando(cx);
  if (!isXray && (expando = GetExpandoObject(proxy))) {
    if (!JS_GetOwnPropertyDescriptorById(cx, expando, id, desc)) {
      return false;
    }
    if (desc.object()) {
      // Pretend the property lives on the wrapper.
      desc.object().set(proxy);
      return true;
    }
  }

  bool callNamedGetter = false;
  if (!IsArrayIndex(index) && !ignoreNamedProps) {
    bool hasOnProto;
    if (!HasPropertyOnPrototype(cx, proxy, id, &hasOnProto)) {
      return false;
    }
    callNamedGetter = !hasOnProto;
  }
  if (callNamedGetter) {
    binding_detail::FakeString name;
    bool isSymbol;
    if (!ConvertIdToString(cx, id, name, isSymbol)) {
      return false;
    }
    if (!isSymbol) {
      mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
      bool found = false;
      auto result(StrongOrRawPtr<mozilla::dom::Element>(self->NamedGetter(NonNullHelper(Constify(name)), found)));
      MOZ_ASSERT(!JS_IsExceptionPending(cx));

      if (found) {
        if (!result) {
          desc.value().setNull();
          FillPropertyDescriptor(desc, proxy, true, false);
          return true;
        }
        if (!GetOrCreateDOMReflector(cx, result, desc.value())) {
          MOZ_ASSERT(true || JS_IsExceptionPending(cx));
          return false;
        }
        FillPropertyDescriptor(desc, proxy, true, false);
        return true;
      }
    }
  }

  desc.object().set(nullptr);
  return true;
}

bool
DOMProxyHandler::defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, JS::Handle<JS::PropertyDescriptor> desc, JS::ObjectOpResult& opresult, bool* defined) const
{
  uint32_t index = GetArrayIndexFromId(cx, id);
  if (IsArrayIndex(index)) {
    *defined = true;
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    JS::Rooted<JS::Value> rootedValue(cx, desc.value());
    mozilla::dom::HTMLOptionElement* option;
    if (desc.value().isObject()) {
      {
        nsresult rv = UnwrapObject<prototypes::id::HTMLOptionElement, mozilla::dom::HTMLOptionElement>(&rootedValue, option);
        if (NS_FAILED(rv)) {
          ThrowErrorMessage(cx, MSG_DOES_NOT_IMPLEMENT_INTERFACE, "Value being assigned to HTMLOptionsCollection setter", "HTMLOptionElement");
          return false;
        }
      }
    } else if (desc.value().isNullOrUndefined()) {
      option = nullptr;
    } else {
      ThrowErrorMessage(cx, MSG_NOT_OBJECT, "Value being assigned to HTMLOptionsCollection setter");
      return false;
    }
    binding_detail::FastErrorResult rv;
    self->IndexedSetter(index, Constify(option), rv);
    if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
      return false;
    }
    MOZ_ASSERT(!JS_IsExceptionPending(cx));
    return opresult.succeed();
  }
  bool found = false;
  binding_detail::FakeString name;
  bool isSymbol;
  if (!ConvertIdToString(cx, id, name, isSymbol)) {
    return false;
  }
  if (!isSymbol) {
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    auto result(StrongOrRawPtr<mozilla::dom::Element>(self->NamedGetter(NonNullHelper(Constify(name)), found)));
    MOZ_ASSERT(!JS_IsExceptionPending(cx));
    (void)result;
  }

  if (found) {
    *defined = true;
    return opresult.failNoNamedSetter();
  }
  return mozilla::dom::DOMProxyHandler::defineProperty(cx, proxy, id, desc, opresult, defined);
}


bool
DOMProxyHandler::ownPropNames(JSContext* cx, JS::Handle<JSObject*> proxy, unsigned flags, JS::AutoIdVector& props) const
{
  bool isXray = xpc::WrapperFactory::IsXrayWrapper(proxy);

  uint32_t length = UnwrapProxy(proxy)->Length();
  MOZ_ASSERT(int32_t(length) >= 0);
  for (int32_t i = 0; i < int32_t(length); ++i) {
    if (!props.append(INT_TO_JSID(i))) {
      return false;
    }
  }

  if (flags & JSITER_HIDDEN) {
    nsTArray<nsString> names;
    UnwrapProxy(proxy)->GetSupportedNames(names);
    if (!AppendNamedPropertyIds(cx, proxy, names, false, props)) {
      return false;
    }
  }

  JS::Rooted<JSObject*> expando(cx);
  if (!isXray && (expando = DOMProxyHandler::GetExpandoObject(proxy)) &&
      !js::GetPropertyKeys(cx, expando, flags, &props)) {
    return false;
  }

  return true;
}

bool
DOMProxyHandler::hasOwn(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp) const
{
  MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
            "Should not have a XrayWrapper here");

  uint32_t index = GetArrayIndexFromId(cx, id);
  if (IsArrayIndex(index)) {
    bool found = false;
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    auto result(StrongOrRawPtr<mozilla::dom::Element>(self->IndexedGetter(index, found)));
    MOZ_ASSERT(!JS_IsExceptionPending(cx));
    (void)result;

    *bp = found;
    return true;
  }


  JS::Rooted<JSObject*> expando(cx, GetExpandoObject(proxy));
  if (expando) {
    bool b = true;
    bool ok = JS_HasPropertyById(cx, expando, id, &b);
    *bp = !!b;
    if (!ok || *bp) {
      return ok;
    }
  }

  bool hasOnProto;
  if (!HasPropertyOnPrototype(cx, proxy, id, &hasOnProto)) {
    return false;
  }
  if (!hasOnProto) {
    bool found = false;
    binding_detail::FakeString name;
    bool isSymbol;
    if (!ConvertIdToString(cx, id, name, isSymbol)) {
      return false;
    }
    if (!isSymbol) {
      mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
      auto result(StrongOrRawPtr<mozilla::dom::Element>(self->NamedGetter(NonNullHelper(Constify(name)), found)));
      MOZ_ASSERT(!JS_IsExceptionPending(cx));
      (void)result;
    }

    *bp = found;
    return true;
  }
  *bp = false;
  return true;
}

bool
DOMProxyHandler::get(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<JS::Value> receiver, JS::Handle<jsid> id, JS::MutableHandle<JS::Value> vp) const
{
  MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
              "Should not have a XrayWrapper here");

  uint32_t index = GetArrayIndexFromId(cx, id);
  if (IsArrayIndex(index)) {
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    bool found = false;
    auto result(StrongOrRawPtr<mozilla::dom::Element>(self->IndexedGetter(index, found)));
    MOZ_ASSERT(!JS_IsExceptionPending(cx));

    if (found) {
      if (!result) {
        vp.setNull();
        return true;
      }
      if (!GetOrCreateDOMReflector(cx, result, vp)) {
        MOZ_ASSERT(true || JS_IsExceptionPending(cx));
        return false;
      }
      return true;
    }
    // Even if we don't have this index, we don't forward the
    // get on to our expando object.
  } else {
    { // Scope for expando
      JS::Rooted<JSObject*> expando(cx, DOMProxyHandler::GetExpandoObject(proxy));
      if (expando) {
        bool hasProp;
        if (!JS_HasPropertyById(cx, expando, id, &hasProp)) {
          return false;
        }

        if (hasProp) {
          // Forward the get to the expando object, but our receiver is whatever our
          // receiver is.
          return JS_ForwardGetPropertyTo(cx, expando, id, receiver, vp);
        }
      }
    }
  }

  bool foundOnPrototype;
  if (!GetPropertyOnPrototype(cx, proxy, receiver, id, &foundOnPrototype, vp)) {
    return false;
  }

  if (foundOnPrototype) {
    return true;
  }

  if (!IsArrayIndex(index)) {
    binding_detail::FakeString name;
    bool isSymbol;
    if (!ConvertIdToString(cx, id, name, isSymbol)) {
      return false;
    }
    if (!isSymbol) {
      mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
      bool found = false;
      auto result(StrongOrRawPtr<mozilla::dom::Element>(self->NamedGetter(NonNullHelper(Constify(name)), found)));
      MOZ_ASSERT(!JS_IsExceptionPending(cx));

      if (found) {
        if (!result) {
          vp.setNull();
          return true;
        }
        if (!GetOrCreateDOMReflector(cx, result, vp)) {
          MOZ_ASSERT(true || JS_IsExceptionPending(cx));
          return false;
        }
        return true;
      }
    }
  }

  vp.setUndefined();
  return true;
}

const char*
DOMProxyHandler::className(JSContext* cx, JS::Handle<JSObject*> proxy) const
{
  return "HTMLOptionsCollection";
}

bool
DOMProxyHandler::finalizeInBackground(const JS::Value& priv) const
{
  return false;
}

void
DOMProxyHandler::finalize(JSFreeOp* fop, JSObject* proxy) const
{
  mozilla::dom::HTMLOptionsCollection* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::HTMLOptionsCollection>(proxy);
  if (self) {
    ClearWrapper(self, self);
    AddForDeferredFinalization<mozilla::dom::HTMLOptionsCollection>(self);
  }
}

const DOMProxyHandler*
DOMProxyHandler::getInstance()
{
  static const DOMProxyHandler instance;
  return &instance;
}

bool
DOMProxyHandler::delete_(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, JS::ObjectOpResult& opresult) const
{
  MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
            "Should not have a XrayWrapper here");

  uint32_t index = GetArrayIndexFromId(cx, id);
  if (IsArrayIndex(index)) {
    bool deleteSucceeded;
    bool found = false;
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    auto result(StrongOrRawPtr<mozilla::dom::Element>(self->IndexedGetter(index, found)));
    MOZ_ASSERT(!JS_IsExceptionPending(cx));
    (void)result;
    deleteSucceeded = !found;
    return deleteSucceeded ? opresult.succeed() : opresult.failCantDelete();
  }
  // Try named delete only if the named property visibility
  // algorithm says the property is visible.
  bool tryNamedDelete = true;
  { // Scope for expando
    JS::Rooted<JSObject*> expando(cx, DOMProxyHandler::GetExpandoObject(proxy));
    if (expando) {
      bool hasProp;
      if (!JS_HasPropertyById(cx, expando, id, &hasProp)) {
        return false;
      }
      tryNamedDelete = !hasProp;
    }
  }
  if (tryNamedDelete) {
    bool hasOnProto;
    if (!HasPropertyOnPrototype(cx, proxy, id, &hasOnProto)) {
      return false;
    }
    tryNamedDelete = !hasOnProto;
  }
  if (tryNamedDelete) {
    bool found = false;
    bool deleteSucceeded;
    binding_detail::FakeString name;
    bool isSymbol;
    if (!ConvertIdToString(cx, id, name, isSymbol)) {
      return false;
    }
    if (!isSymbol) {
      mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
      auto result(StrongOrRawPtr<mozilla::dom::Element>(self->NamedGetter(NonNullHelper(Constify(name)), found)));
      MOZ_ASSERT(!JS_IsExceptionPending(cx));
      (void)result;
    }
    deleteSucceeded = !found;
    if (found) {
      return deleteSucceeded ? opresult.succeed() : opresult.failCantDelete();
    }
  }

  return dom::DOMProxyHandler::delete_(cx, proxy, id, opresult);
}

bool
DOMProxyHandler::getElements(JSContext* cx, JS::Handle<JSObject*> proxy, uint32_t begin, uint32_t end, js::ElementAdder* adder) const
{
  JS::Rooted<JS::Value> temp(cx);
  MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
             "Should not have a XrayWrapper here");

  mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
  uint32_t length = self->Length();
  // Compute the end of the indices we'll get ourselves
  uint32_t ourEnd = std::max(begin, std::min(end, length));

  for (uint32_t index = begin; index < ourEnd; ++index) {
    bool found = false;
    auto result(StrongOrRawPtr<mozilla::dom::Element>(self->IndexedGetter(index, found)));
    MOZ_ASSERT(!JS_IsExceptionPending(cx));

    MOZ_ASSERT(found);
    if (!result) {
      temp.setNull();
      if (!adder->append(cx, temp)) return false;
      continue;
    }
    if (!GetOrCreateDOMReflector(cx, result, &temp)) {
      MOZ_ASSERT(true || JS_IsExceptionPending(cx));
      return false;
    }
    if (!adder->append(cx, temp)) return false;
    continue;
  }

  if (end > ourEnd) {
    JS::Rooted<JSObject*> proto(cx);
    if (!js::GetObjectProto(cx, proxy, &proto)) {
      return false;
    }
    return js::GetElementsWithAdder(cx, proto, proxy, ourEnd, end, adder);
  }

  return true;
}

bool
DOMProxyHandler::setCustom(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, JS::Handle<JS::Value> v, bool* done) const
{
  MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
             "Should not have a XrayWrapper here");
  uint32_t index = GetArrayIndexFromId(cx, id);
  if (IsArrayIndex(index)) {
    mozilla::dom::HTMLOptionsCollection* self = UnwrapProxy(proxy);
    JS::Rooted<JS::Value> rootedValue(cx, v);
    mozilla::dom::HTMLOptionElement* option;
    if (v.isObject()) {
      {
        nsresult rv = UnwrapObject<prototypes::id::HTMLOptionElement, mozilla::dom::HTMLOptionElement>(&rootedValue, option);
        if (NS_FAILED(rv)) {
          ThrowErrorMessage(cx, MSG_DOES_NOT_IMPLEMENT_INTERFACE, "Value being assigned to HTMLOptionsCollection setter", "HTMLOptionElement");
          return false;
        }
      }
    } else if (v.isNullOrUndefined()) {
      option = nullptr;
    } else {
      ThrowErrorMessage(cx, MSG_NOT_OBJECT, "Value being assigned to HTMLOptionsCollection setter");
      return false;
    }
    binding_detail::FastErrorResult rv;
    self->IndexedSetter(index, Constify(option), rv);
    if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx))) {
      return false;
    }
    MOZ_ASSERT(!JS_IsExceptionPending(cx));
    *done = true;
    return true;
  }

  *done = false;
  return true;
}

static const js::ClassExtension sClassExtension = PROXY_MAKE_EXT(
    _objectMoved
);

static const DOMJSClass sClass = {
  PROXY_CLASS_WITH_EXT("HTMLOptionsCollection",
                       JSCLASS_IS_DOMJSCLASS,
                       &sClassExtension),
  { prototypes::id::HTMLCollection, prototypes::id::HTMLOptionsCollection, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
  IsBaseOf<nsISupports, mozilla::dom::HTMLOptionsCollection >::value,
  sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::HTMLOptionsCollection>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::HTMLOptionsCollection>::Get()
};

bool
Wrap(JSContext* aCx, mozilla::dom::HTMLOptionsCollection* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  MOZ_ASSERT(static_cast<mozilla::dom::HTMLOptionsCollection*>(aObject) ==
             reinterpret_cast<mozilla::dom::HTMLOptionsCollection*>(aObject),
             "Multiple inheritance for mozilla::dom::HTMLOptionsCollection is broken.");
  MOZ_ASSERT(static_cast<nsIHTMLCollection*>(aObject) ==
             reinterpret_cast<nsIHTMLCollection*>(aObject),
             "Multiple inheritance for nsIHTMLCollection is broken.");
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));
  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");

  JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
  if (!global) {
    return false;
  }
  MOZ_ASSERT(JS_IsGlobalObject(global));
  MOZ_ASSERT(!JS::ObjectIsMarkedGray(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
    binding_detail::AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
    return true;
  }

  JSAutoCompartment ac(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::GetObjectCompartment(proto)) {
      if (!JS_WrapObject(aCx, &proto)) {
        return false;
      }
    }
  } else {
    proto = canonicalProto;
  }

  BindingJSObjectCreator<mozilla::dom::HTMLOptionsCollection> creator(aCx);
  creator.CreateProxyObject(aCx, &sClass.mBase, DOMProxyHandler::getInstance(),
                            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) {
    // For DOM proxies, the only reliable way to preserve the wrapper
    // is to force creation of the expando object.
    JS::Rooted<JSObject*> unused(aCx,
      DOMProxyHandler::EnsureExpandoObject(aCx, aReflector));
  }

  return true;
}

static bool
ResolveOwnProperty(JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj, JS::Handle<jsid> id, JS::MutableHandle<JS::PropertyDescriptor> desc)
{
  return js::GetProxyHandler(obj)->getOwnPropertyDescriptor(cx, wrapper, id, desc);
}

static bool
EnumerateOwnProperties(JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj, JS::AutoIdVector& props)
{
  return js::GetProxyHandler(obj)->ownPropertyKeys(cx, wrapper, props);
}

const NativePropertyHooks sNativePropertyHooks[] = { {
  ResolveOwnProperty,
  EnumerateOwnProperties,
  nullptr,
  { sNativeProperties.Upcast(), nullptr },
  prototypes::id::HTMLOptionsCollection,
  constructors::id::HTMLOptionsCollection,
  HTMLCollectionBinding::sNativePropertyHooks,
  &DefaultXrayExpandoObjectClass
} };

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, bool aDefineOnGlobal)
{
  JS::Handle<JSObject*> parentProto(HTMLCollectionBinding::GetProtoObjectHandle(aCx));
  if (!parentProto) {
    return;
  }

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

  static bool sIdsInited = false;
  if (!sIdsInited && NS_IsMainThread()) {
    if (!InitIds(aCx, sMethods, sMethods_ids)) {
      return;
    }
    if (!InitIds(aCx, sAttributes, sAttributes_ids)) {
      return;
    }
    sIdsInited = true;
  }

  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::HTMLOptionsCollection);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::HTMLOptionsCollection);
  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass.mBase, protoCache,
                              constructorProto, &sInterfaceObjectClass.mBase, 0, nullptr,
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "HTMLOptionsCollection", aDefineOnGlobal,
                              nullptr,
                              false);
}

JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  bool aDefineOnGlobal = true;

  /* Make sure our global is sane.  Hopefully we can remove this sometime */
  JSObject* global = JS::CurrentGlobalOrNull(aCx);
  if (!(js::GetObjectClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
    return nullptr;
  }

  /* Check to see whether the interface objects are already installed */
  ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
  if (!protoAndIfaceCache.EntrySlotIfExists(prototypes::id::HTMLOptionsCollection)) {
    JS::Rooted<JSObject*> rootedGlobal(aCx, global);
    CreateInterfaceObjects(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
  }

  /*
   * The object might _still_ be null, but that's OK.
   *
   * Calling fromMarkedLocation() is safe because protoAndIfaceCache is
   * traced by TraceProtoAndIfaceCache() and its contents are never
   * changed after they have been set.
   *
   * Calling address() avoids the read read barrier that does gray
   * unmarking, but it's not possible for the object to be gray here.
   */

  const JS::Heap<JSObject*>& entrySlot = protoAndIfaceCache.EntrySlotMustExist(prototypes::id::HTMLOptionsCollection);
  MOZ_ASSERT_IF(entrySlot, !JS::ObjectIsMarkedGray(entrySlot));
  return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
}

JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx, bool aDefineOnGlobal)
{
  /* Get the interface object for this class.  This will create the object as
     needed. */

  /* Make sure our global is sane.  Hopefully we can remove this sometime */
  JSObject* global = JS::CurrentGlobalOrNull(aCx);
  if (!(js::GetObjectClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
    return nullptr;
  }

  /* Check to see whether the interface objects are already installed */
  ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
  if (!protoAndIfaceCache.EntrySlotIfExists(constructors::id::HTMLOptionsCollection)) {
    JS::Rooted<JSObject*> rootedGlobal(aCx, global);
    CreateInterfaceObjects(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
  }

  /*
   * The object might _still_ be null, but that's OK.
   *
   * Calling fromMarkedLocation() is safe because protoAndIfaceCache is
   * traced by TraceProtoAndIfaceCache() and its contents are never
   * changed after they have been set.
   *
   * Calling address() avoids the read read barrier that does gray
   * unmarking, but it's not possible for the object to be gray here.
   */

  const JS::Heap<JSObject*>& entrySlot = protoAndIfaceCache.EntrySlotMustExist(constructors::id::HTMLOptionsCollection);
  MOZ_ASSERT_IF(entrySlot, !JS::ObjectIsMarkedGray(entrySlot));
  return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
}

JSObject*
GetConstructorObject(JSContext* aCx)
{
  return GetConstructorObjectHandle(aCx);
}

} // namespace HTMLOptionsCollectionBinding



} // namespace dom
} // namespace mozilla
