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

#include <type_traits>
#include "AtomList.h"
#include "BlobBinding.h"
#include "FileBinding.h"
#include "MainThreadUtils.h"
#include "WrapperFactory.h"
#include "js/Array.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.h"
#include "js/ForOfIterator.h"
#include "js/MapAndSet.h"
#include "js/Object.h"
#include "js/PropertyAndElement.h"
#include "js/PropertyDescriptor.h"
#include "js/experimental/JitInfo.h"
#include "jsfriendapi.h"
#include "mozilla/Atomics.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/Blob.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/PrimitiveConversions.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SimpleGlobalObject.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/TypedArray.h"
#include "mozilla/dom/UnionTypes.h"
#include "mozilla/dom/WebIDLPrefs.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsContentUtils.h"
#include "nsIFile.h"

namespace mozilla::dom {

namespace binding_detail {}; // Just to make sure it's known as a namespace
using namespace mozilla::dom::binding_detail;



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




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

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

bool
FilePropertyBag::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());
  FilePropertyBagAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<FilePropertyBagAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  // Per spec, we init the parent's members first
  if (!BlobPropertyBag::Init(cx, val)) {
    return false;
  }

  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->lastModified_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    mLastModified.Construct();
    if (!ValueToPrimitive<int64_t, eDefault>(cx, temp.ref(), "'lastModified' member of FilePropertyBag", &(mLastModified.Value()))) {
      return false;
    }
    mIsAnyMemberPresent = true;
  }
  return true;
}

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

FilePropertyBag&
FilePropertyBag::operator=(const FilePropertyBag& aOther)
{
  BlobPropertyBag::operator=(aOther);
  mLastModified.Reset();
  if (aOther.mLastModified.WasPassed()) {
    mLastModified.Construct(aOther.mLastModified.Value());
  }
  return *this;
}



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




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

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

bool
ChromeFilePropertyBag::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());
  ChromeFilePropertyBagAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<ChromeFilePropertyBagAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  // Per spec, we init the parent's members first
  if (!FilePropertyBag::Init(cx, val)) {
    return false;
  }

  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->existenceCheck_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ValueToPrimitive<bool, eDefault>(cx, temp.ref(), "'existenceCheck' member of ChromeFilePropertyBag", &mExistenceCheck)) {
      return false;
    }
  } else {
    mExistenceCheck = true;
  }
  mIsAnyMemberPresent = true;

  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->name_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mName)) {
      return false;
    }
  } else {
    mName.AssignLiteral(u"");
  }
  mIsAnyMemberPresent = true;
  return true;
}

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

ChromeFilePropertyBag&
ChromeFilePropertyBag::operator=(const ChromeFilePropertyBag& aOther)
{
  FilePropertyBag::operator=(aOther);
  mExistenceCheck = aOther.mExistenceCheck;
  mName = aOther.mName;
  return *this;
}


namespace File_Binding {

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

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

  auto* self = static_cast<mozilla::dom::File*>(void_self);
  DOMString result;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetName(result))>, "Should be returning void here");
  MOZ_KnownLive(self)->GetName(result);
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!xpc::NonVoidStringToJsval(cx, result, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo name_getterinfo = {
  { get_name },
  { prototypes::id::File },
  { PrototypeTraits<prototypes::id::File>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_STRING,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

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

  auto* self = static_cast<mozilla::dom::File*>(void_self);
  FastErrorResult rv;
  int64_t result(MOZ_KnownLive(self)->GetLastModified(rv));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "File.lastModified getter"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  args.rval().set(JS_NumberValue(double(result)));
  return true;
}

static const JSJitInfo lastModified_getterinfo = {
  { get_lastModified },
  { prototypes::id::File },
  { PrototypeTraits<prototypes::id::File>::Depth },
  JSJitInfo::Getter,
  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
get_webkitRelativePath(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, JSJitGetterCallArgs args)
{
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "File", "webkitRelativePath", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_GETTER) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::File*>(void_self);
  DOMString result;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetRelativePath(result))>, "Should be returning void here");
  MOZ_KnownLive(self)->GetRelativePath(result);
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!xpc::NonVoidStringToJsval(cx, result, args.rval())) {
    return false;
  }
  return true;
}

static const JSJitInfo webkitRelativePath_getterinfo = {
  { get_webkitRelativePath },
  { prototypes::id::File },
  { PrototypeTraits<prototypes::id::File>::Depth },
  JSJitInfo::Getter,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_STRING,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

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

  auto* self = static_cast<mozilla::dom::File*>(void_self);
  FastErrorResult rv;
  DOMString result;
  // NOTE: This assert does NOT call the function.
  static_assert(std::is_void_v<decltype(MOZ_KnownLive(self)->GetMozFullPath(result, SystemCallerGuarantee(), rv))>, "Should be returning void here");
  MOZ_KnownLive(self)->GetMozFullPath(result, SystemCallerGuarantee(), rv);
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "File.mozFullPath getter"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  if (!xpc::NonVoidStringToJsval(cx, result, args.rval())) {
    return false;
  }
  return true;
}

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

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

static const JSJitInfo setMozRelativePath_methodinfo = {
  { (JSJitGetterOp)setMozRelativePath },
  { prototypes::id::File },
  { PrototypeTraits<prototypes::id::File>::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
createFromNsIFile(JSContext* cx_, unsigned argc, JS::Value* vp)
{
  BindingCallContext cx(cx_, "File.createFromNsIFile");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "File", "createFromNsIFile", 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, "File.createFromNsIFile", 1)) {
    return false;
  }
  GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj));
  if (global.Failed()) {
    return false;
  }

  nsIFile* arg0;
  RefPtr<nsIFile> arg0_holder;
  if (args[0].isObject()) {
    JS::Rooted<JSObject*> source(cx, &args[0].toObject());
    if (NS_FAILED(UnwrapArg<nsIFile>(cx, source, getter_AddRefs(arg0_holder)))) {
      cx.ThrowErrorMessage<MSG_DOES_NOT_IMPLEMENT_INTERFACE>("Argument 1", "nsIFile");
      return false;
    }
    MOZ_ASSERT(arg0_holder);
    arg0 = arg0_holder;
  } else {
    cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Argument 1");
    return false;
  }
  binding_detail::FastChromeFilePropertyBag arg1;
  if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(mozilla::dom::File::CreateFromNsIFile(global, MOZ_KnownLive(NonNullHelper(arg0)), Constify(arg1), SystemCallerGuarantee(), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "File.createFromNsIFile"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}


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

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

  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  if (!NormalizeUSVString(arg0)) {
    JS_ReportOutOfMemory(cx);
    return false;
  }
  binding_detail::FastChromeFilePropertyBag arg1;
  if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(mozilla::dom::File::CreateFromFileName(global, Constify(arg0), Constify(arg1), SystemCallerGuarantee(), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "File.createFromFileName"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}


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

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

MOZ_GLOBINIT static const JSFunctionSpec sChromeStaticMethods_specs[] = {
  JS_FNSPEC("createFromNsIFile", StaticMethodPromiseWrapper, &createFromNsIFile_methodinfo, 1, JSPROP_ENUMERATE, nullptr),
  JS_FNSPEC("createFromFileName", StaticMethodPromiseWrapper, &createFromFileName_methodinfo, 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};

static const PrefableDisablers sChromeStaticMethods_disablers0 = {
  WebIDLPrefIndex::NoPref, GlobalNames::DedicatedWorkerGlobalScope | GlobalNames::ServiceWorkerGlobalScope | GlobalNames::SharedWorkerGlobalScope, false, OriginTrial(0), nullptr
};

static const Prefable<const JSFunctionSpec> sChromeStaticMethods[] = {
  { &sChromeStaticMethods_disablers0, &sChromeStaticMethods_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(2 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");

MOZ_GLOBINIT static const JSFunctionSpec sChromeMethods_specs[] = {
  JS_FNSPEC("setMozRelativePath", (GenericMethod<NormalThisPolicy, ThrowExceptions>), reinterpret_cast<const JSJitInfo*>(&setMozRelativePath_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};


static const Prefable<const JSFunctionSpec> sChromeMethods[] = {
  { nullptr, &sChromeMethods_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");

MOZ_GLOBINIT static const JSPropertySpec sAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("name", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &name_getterinfo, nullptr, nullptr),
  JSPropertySpec::nativeAccessors("lastModified", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &lastModified_getterinfo, nullptr, nullptr),
  JS_PS_END,
  JSPropertySpec::nativeAccessors("webkitRelativePath", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &webkitRelativePath_getterinfo, nullptr, nullptr),
  JS_PS_END
};

static const PrefableDisablers sAttributes_disablers3 = {
  WebIDLPrefIndex::dom_webkitBlink_dirPicker_enabled, 0, false, OriginTrial(0), nullptr
};

static const Prefable<const JSPropertySpec> sAttributes[] = {
  { nullptr, &sAttributes_specs[0] },
  { &sAttributes_disablers3, &sAttributes_specs[3] },
  { nullptr, nullptr }
};

static_assert(2 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(2 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");

MOZ_GLOBINIT static const JSPropertySpec sChromeAttributes_specs[] = {
  JSPropertySpec::nativeAccessors("mozFullPath", JSPROP_ENUMERATE, GenericGetter<NormalThisPolicy, ThrowExceptions>, &mozFullPath_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[3];
static PropertyInfo sNativeProperties_propertyInfos[3];

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

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

static const NativePropertiesN<3> sChromeOnlyNativeProperties = {
  true,  0 /* sChromeStaticMethods */,
  false, 0,
  true,  1 /* sChromeMethods */,
  true,  2 /* sChromeAttributes */,
  false, 0,
  false, 0,
  false, 0,
  -1,
  4,
  sChromeOnlyNativeProperties_sortedPropertyIndices,
  {
    { sChromeStaticMethods, &sChromeOnlyNativeProperties_propertyInfos[0] },
    { sChromeMethods, &sChromeOnlyNativeProperties_propertyInfos[2] },
    { sChromeAttributes, &sChromeOnlyNativeProperties_propertyInfos[3] }
  }
};
static_assert(4 < 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::File,
  constructors::id::File,
  &DefaultXrayExpandoObjectClass
};

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

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

  if (!args.requireAtLeast(cx, "File constructor", 2)) {
    return false;
  }
  GlobalObject global(cx, obj);
  if (global.Failed()) {
    return false;
  }

  bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj);
  binding_detail::AutoSequence<OwningArrayBufferViewOrArrayBufferOrBlobOrUTF8String> arg0;
  SequenceRooter<OwningArrayBufferViewOrArrayBufferOrBlobOrUTF8String> arg0_holder(cx, &arg0);
  if (args[0].isObject()) {
    JS::ForOfIterator iter(cx);
    if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) {
      return false;
    }
    if (!iter.valueIsIterable()) {
      cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Argument 1", "sequence");
      return false;
    }
    binding_detail::AutoSequence<OwningArrayBufferViewOrArrayBufferOrBlobOrUTF8String> &arr = arg0;
    JS::Rooted<JS::Value> temp(cx);
    while (true) {
      bool done;
      if (!iter.next(&temp, &done)) {
        return false;
      }
      if (done) {
        break;
      }
      OwningArrayBufferViewOrArrayBufferOrBlobOrUTF8String* slotPtr = arr.AppendElement(mozilla::fallible);
      if (!slotPtr) {
        JS_ReportOutOfMemory(cx);
        return false;
      }
      OwningArrayBufferViewOrArrayBufferOrBlobOrUTF8String& slot = *slotPtr;
      if (!slot.Init(cx, temp, "Element of argument 1", false)) {
        return false;
      }
    }
  } else {
    cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>("Argument 1", "sequence");
    return false;
  }
  binding_detail::FakeString<char16_t> arg1;
  if (!ConvertJSValueToString(cx, args[1], eStringify, eStringify, arg1)) {
    return false;
  }
  if (!NormalizeUSVString(arg1)) {
    JS_ReportOutOfMemory(cx);
    return false;
  }
  binding_detail::FastFilePropertyBag arg2;
  if (!arg2.Init(cx, (args.hasDefined(2)) ? args[2] : JS::NullHandleValue, "Argument 3", 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;
    }
    for (uint32_t indexName0 = 0; indexName0 < arg0.Length(); ++indexName0) {
      if (arg0[indexName0].IsArrayBufferView()) {
        if (!arg0[indexName0].GetAsArrayBufferView().WrapIntoNewCompartment(cx)) {
          return false;
        }
      }
      else if (arg0[indexName0].IsArrayBuffer()) {
        if (!arg0[indexName0].GetAsArrayBuffer().WrapIntoNewCompartment(cx)) {
          return false;
        }
      }
    }
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<mozilla::dom::File>(mozilla::dom::File::Constructor(global, Constify(arg0), Constify(arg1), Constify(arg2), rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "File 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 },
  Blob_Binding::GetConstructorObjectHandle,
  PrototypeTraits<prototypes::id::File>::Depth,
  prototypes::id::File,
  true,
  2,
  "File",
};

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

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

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

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

} // namespace File_Binding



} // namespace mozilla::dom
