/* THIS FILE IS AUTOGENERATED FROM Localization.webidl BY Codegen.py - DO NOT EDIT */ #include #include "AtomList.h" #include "FluentBinding.h" #include "L10nRegistryBinding.h" #include "LocalizationBinding.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 "mozilla/Atomics.h" #include "mozilla/FloatingPoint.h" #include "mozilla/OwningNonNull.h" #include "mozilla/ProfilerLabels.h" #include "mozilla/dom/BindingCallContext.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/DOMJSClass.h" #include "mozilla/dom/NonRefcountedDOMObject.h" #include "mozilla/dom/Nullable.h" #include "mozilla/dom/PrimitiveConversions.h" #include "mozilla/dom/Promise.h" #include "mozilla/dom/Record.h" #include "mozilla/dom/ScriptSettings.h" #include "mozilla/dom/SimpleGlobalObject.h" #include "mozilla/dom/ToJSValue.h" #include "mozilla/dom/XrayExpandoClass.h" #include "mozilla/intl/L10nRegistry.h" #include "mozilla/intl/Localization.h" namespace mozilla::dom { namespace binding_detail {}; // Just to make sure it's known as a namespace using namespace mozilla::dom::binding_detail; AttributeNameValue::AttributeNameValue() { // Safe to pass a null context if we pass a null value Init(nullptr, JS::NullHandleValue); } bool AttributeNameValue::InitIds(JSContext* cx, AttributeNameValueAtoms* atomsCache) { MOZ_ASSERT(reinterpret_cast(atomsCache)->isVoid()); // Initialize these in reverse order so that any failure leaves the first one // uninitialized. if (!atomsCache->value_id.init(cx, "value") || !atomsCache->name_id.init(cx, "name")) { return false; } return true; } bool AttributeNameValue::Init(BindingCallContext& cx, JS::Handle 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()); AttributeNameValueAtoms* atomsCache = nullptr; if (cx) { atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } } if (!IsConvertibleToDictionary(val)) { return cx.ThrowErrorMessage(sourceDescription, "dictionary"); } bool isNull = val.isNullOrUndefined(); // We only need these if !isNull, in which case we have |cx|. Maybe > object; Maybe > temp; if (!isNull) { MOZ_ASSERT(cx); object.emplace(cx, &val.toObject()); temp.emplace(cx); } 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; } mIsAnyMemberPresent = true; } else if (cx) { // Don't error out if we have no cx. In that // situation the caller is default-constructing us and we'll // just assume they know what they're doing. return cx.ThrowErrorMessage("'name' member of AttributeNameValue"); } if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->value_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { if (!ConvertJSValueToString(cx, temp.ref(), eStringify, eStringify, mValue)) { return false; } mIsAnyMemberPresent = true; } else if (cx) { // Don't error out if we have no cx. In that // situation the caller is default-constructing us and we'll // just assume they know what they're doing. return cx.ThrowErrorMessage("'value' member of AttributeNameValue"); } return true; } bool AttributeNameValue::Init(JSContext* cx_, JS::Handle val, const char* sourceDescription, bool passedToJSImpl) { // We don't want to use sourceDescription for our context here; // that's not really what it's formatted for. BindingCallContext cx(cx_, nullptr); return Init(cx, val, sourceDescription, passedToJSImpl); } bool AttributeNameValue::ToObjectInternal(JSContext* cx, JS::MutableHandle rval) const { AttributeNameValueAtoms* atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } JS::Rooted obj(cx, JS_NewPlainObject(cx)); if (!obj) { return false; } rval.setObject(*obj); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); nsCString const & currentValue = mName; if (!NonVoidUTF8StringToJsval(cx, currentValue, &temp)) { return false; } if (!JS_DefinePropertyById(cx, obj, atomsCache->name_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); nsCString const & currentValue = mValue; if (!NonVoidUTF8StringToJsval(cx, currentValue, &temp)) { return false; } if (!JS_DefinePropertyById(cx, obj, atomsCache->value_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); return true; } void AttributeNameValue::TraceDictionary(JSTracer* trc) { } AttributeNameValue& AttributeNameValue::operator=(const AttributeNameValue& aOther) { MaybeEmptyDictionaryBase::operator=(aOther); mName = aOther.mName; mValue = aOther.mValue; return *this; } L10nArgsHelperDict::L10nArgsHelperDict() { // Safe to pass a null context if we pass a null value Init(nullptr, JS::NullHandleValue); } bool L10nArgsHelperDict::InitIds(JSContext* cx, L10nArgsHelperDictAtoms* atomsCache) { MOZ_ASSERT(reinterpret_cast(atomsCache)->isVoid()); // Initialize these in reverse order so that any failure leaves the first one // uninitialized. if (!atomsCache->args_id.init(cx, "args")) { return false; } return true; } bool L10nArgsHelperDict::Init(BindingCallContext& cx, JS::Handle 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()); L10nArgsHelperDictAtoms* atomsCache = nullptr; if (cx) { atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } } if (!IsConvertibleToDictionary(val)) { return cx.ThrowErrorMessage(sourceDescription, "dictionary"); } bool isNull = val.isNullOrUndefined(); // We only need these if !isNull, in which case we have |cx|. Maybe > object; Maybe > temp; if (!isNull) { MOZ_ASSERT(cx); object.emplace(cx, &val.toObject()); temp.emplace(cx); } if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->args_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { if (temp.ref().isObject()) { auto& recordEntries = mArgs.Entries(); JS::Rooted recordObj(cx, &temp.ref().toObject()); JS::RootedVector ids(cx); if (!js::GetPropertyKeys(cx, recordObj, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) { return false; } if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } JS::Rooted propNameValue(cx); JS::Rooted temp(cx); JS::Rooted curId(cx); JS::Rooted idVal(cx); // Use a hashset to keep track of ids seen, to avoid // introducing nasty O(N^2) behavior scanning for them all the // time. Ideally we'd use a data structure with O(1) lookup // _and_ ordering for the MozMap, but we don't have one lying // around. nsTHashtable idsSeen; for (size_t i = 0; i < ids.length(); ++i) { curId = ids[i]; JS::Rooted> desc(cx); if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId, &desc)) { return false; } if (desc.isNothing() || !desc->enumerable()) { continue; } idVal = js::IdToValue(curId); nsCString propName; // This will just throw if idVal is a Symbol, like the spec says // to do. if (!ConvertJSValueToString(cx, idVal, "key of 'args' member of L10nArgsHelperDict", propName)) { return false; } if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) { return false; } Record>::EntryType* entry; if (!idsSeen.EnsureInserted(propName)) { // Find the existing entry. auto idx = recordEntries.IndexOf(propName); MOZ_ASSERT(idx != recordEntries.NoIndex, "Why is it not found?"); // Now blow it away to make it look like it was just added // to the array, because it's not obvious that it's // safe to write to its already-initialized mValue via our // normal codegen conversions. For example, the value // could be a union and this would change its type, but // codegen assumes we won't do that. entry = recordEntries.ReconstructElementAt(idx); } else { // Safe to do an infallible append here, because we did a // SetCapacity above to the right capacity. entry = recordEntries.AppendElement(); } entry->mKey = propName; Nullable& slot = entry->mValue; if (temp.isNullOrUndefined()) { slot.SetNull(); } else { if (!slot.SetValue().Init(cx, temp, "Value in 'args' member of L10nArgsHelperDict", passedToJSImpl)) { return false; } } } } else { cx.ThrowErrorMessage("'args' member of L10nArgsHelperDict"); return false; } mIsAnyMemberPresent = true; } else if (cx) { // Don't error out if we have no cx. In that // situation the caller is default-constructing us and we'll // just assume they know what they're doing. return cx.ThrowErrorMessage("'args' member of L10nArgsHelperDict"); } return true; } bool L10nArgsHelperDict::Init(JSContext* cx_, JS::Handle val, const char* sourceDescription, bool passedToJSImpl) { // We don't want to use sourceDescription for our context here; // that's not really what it's formatted for. BindingCallContext cx(cx_, nullptr); return Init(cx, val, sourceDescription, passedToJSImpl); } bool L10nArgsHelperDict::Init(const nsAString& aJSON) { AutoJSAPI jsapi; JSObject* cleanGlobal = SimpleGlobalObject::Create(SimpleGlobalObject::GlobalType::BindingDetail); if (!cleanGlobal) { return false; } if (!jsapi.Init(cleanGlobal)) { return false; } JSContext* cx = jsapi.cx(); JS::Rooted json(cx); bool ok = ParseJSON(cx, aJSON, &json); NS_ENSURE_TRUE(ok, false); return Init(cx, json); } bool L10nArgsHelperDict::Init(const nsACString& aJSON) { AutoJSAPI jsapi; JSObject* cleanGlobal = SimpleGlobalObject::Create(SimpleGlobalObject::GlobalType::BindingDetail); if (!cleanGlobal) { return false; } if (!jsapi.Init(cleanGlobal)) { return false; } JSContext* cx = jsapi.cx(); JS::Rooted json(cx); bool ok = ParseJSON(cx, aJSON, &json); NS_ENSURE_TRUE(ok, false); return Init(cx, json); } bool L10nArgsHelperDict::ToObjectInternal(JSContext* cx, JS::MutableHandle rval) const { L10nArgsHelperDictAtoms* atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } JS::Rooted obj(cx, JS_NewPlainObject(cx)); if (!obj) { return false; } rval.setObject(*obj); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); Record> const & currentValue = mArgs; JS::Rooted returnObj(cx, JS_NewPlainObject(cx)); if (!returnObj) { return false; } // Scope for 'tmp' { JS::Rooted tmp(cx); for (auto& entry : currentValue.Entries()) { auto& recordValue0 = entry.mValue; // Control block to let us common up the JS_DefineUCProperty calls when there // are different ways to succeed at wrapping the value. do { if (recordValue0.IsNull()) { tmp.setNull(); break; } if (!recordValue0.Value().ToJSVal(cx, returnObj, &tmp)) { return false; } break; } while (false); NS_ConvertUTF8toUTF16 expandedKey(entry.mKey); if (!JS_DefineUCProperty(cx, returnObj, expandedKey.BeginReading(), expandedKey.Length(), tmp, JSPROP_ENUMERATE)) { return false; } } } temp.setObject(*returnObj); if (!JS_DefinePropertyById(cx, obj, atomsCache->args_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); return true; } void L10nArgsHelperDict::TraceDictionary(JSTracer* trc) { } L10nIdArgs::L10nIdArgs() { // Safe to pass a null context if we pass a null value Init(nullptr, JS::NullHandleValue); } bool L10nIdArgs::InitIds(JSContext* cx, L10nIdArgsAtoms* atomsCache) { MOZ_ASSERT(reinterpret_cast(atomsCache)->isVoid()); // Initialize these in reverse order so that any failure leaves the first one // uninitialized. if (!atomsCache->id_id.init(cx, "id") || !atomsCache->args_id.init(cx, "args")) { return false; } return true; } bool L10nIdArgs::Init(BindingCallContext& cx, JS::Handle 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()); L10nIdArgsAtoms* atomsCache = nullptr; if (cx) { atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } } if (!IsConvertibleToDictionary(val)) { return cx.ThrowErrorMessage(sourceDescription, "dictionary"); } bool isNull = val.isNullOrUndefined(); // We only need these if !isNull, in which case we have |cx|. Maybe > object; Maybe > temp; if (!isNull) { MOZ_ASSERT(cx); object.emplace(cx, &val.toObject()); temp.emplace(cx); } if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->args_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { if (temp.ref().isObject()) { auto& recordEntries = mArgs.SetValue().Entries(); JS::Rooted recordObj(cx, &temp.ref().toObject()); JS::RootedVector ids(cx); if (!js::GetPropertyKeys(cx, recordObj, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) { return false; } if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } JS::Rooted propNameValue(cx); JS::Rooted temp(cx); JS::Rooted curId(cx); JS::Rooted idVal(cx); // Use a hashset to keep track of ids seen, to avoid // introducing nasty O(N^2) behavior scanning for them all the // time. Ideally we'd use a data structure with O(1) lookup // _and_ ordering for the MozMap, but we don't have one lying // around. nsTHashtable idsSeen; for (size_t i = 0; i < ids.length(); ++i) { curId = ids[i]; JS::Rooted> desc(cx); if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId, &desc)) { return false; } if (desc.isNothing() || !desc->enumerable()) { continue; } idVal = js::IdToValue(curId); nsCString propName; // This will just throw if idVal is a Symbol, like the spec says // to do. if (!ConvertJSValueToString(cx, idVal, "key of 'args' member of L10nIdArgs", propName)) { return false; } if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) { return false; } Record>::EntryType* entry; if (!idsSeen.EnsureInserted(propName)) { // Find the existing entry. auto idx = recordEntries.IndexOf(propName); MOZ_ASSERT(idx != recordEntries.NoIndex, "Why is it not found?"); // Now blow it away to make it look like it was just added // to the array, because it's not obvious that it's // safe to write to its already-initialized mValue via our // normal codegen conversions. For example, the value // could be a union and this would change its type, but // codegen assumes we won't do that. entry = recordEntries.ReconstructElementAt(idx); } else { // Safe to do an infallible append here, because we did a // SetCapacity above to the right capacity. entry = recordEntries.AppendElement(); } entry->mKey = propName; Nullable& slot = entry->mValue; if (temp.isNullOrUndefined()) { slot.SetNull(); } else { if (!slot.SetValue().Init(cx, temp, "Value in 'args' member of L10nIdArgs", passedToJSImpl)) { return false; } } } } else if (temp.ref().isNullOrUndefined()) { mArgs.SetNull(); } else { cx.ThrowErrorMessage("'args' member of L10nIdArgs"); return false; } } else { mArgs.SetNull(); } mIsAnyMemberPresent = true; if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->id_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { if (!ConvertJSValueToString(cx, temp.ref(), eNull, eNull, mId)) { return false; } } else { mId.SetIsVoid(true); } mIsAnyMemberPresent = true; return true; } bool L10nIdArgs::Init(JSContext* cx_, JS::Handle val, const char* sourceDescription, bool passedToJSImpl) { // We don't want to use sourceDescription for our context here; // that's not really what it's formatted for. BindingCallContext cx(cx_, nullptr); return Init(cx, val, sourceDescription, passedToJSImpl); } bool L10nIdArgs::ToObjectInternal(JSContext* cx, JS::MutableHandle rval) const { L10nIdArgsAtoms* atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } JS::Rooted obj(cx, JS_NewPlainObject(cx)); if (!obj) { return false; } rval.setObject(*obj); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); Nullable>> const & currentValue = mArgs; if (currentValue.IsNull()) { temp.setNull(); if (!JS_DefinePropertyById(cx, obj, atomsCache->args_id, temp, JSPROP_ENUMERATE)) { return false; } break; } JS::Rooted returnObj(cx, JS_NewPlainObject(cx)); if (!returnObj) { return false; } // Scope for 'tmp' { JS::Rooted tmp(cx); for (auto& entry : currentValue.Value().Entries()) { auto& recordValue0 = entry.mValue; // Control block to let us common up the JS_DefineUCProperty calls when there // are different ways to succeed at wrapping the value. do { if (recordValue0.IsNull()) { tmp.setNull(); break; } if (!recordValue0.Value().ToJSVal(cx, returnObj, &tmp)) { return false; } break; } while (false); NS_ConvertUTF8toUTF16 expandedKey(entry.mKey); if (!JS_DefineUCProperty(cx, returnObj, expandedKey.BeginReading(), expandedKey.Length(), tmp, JSPROP_ENUMERATE)) { return false; } } } temp.setObject(*returnObj); if (!JS_DefinePropertyById(cx, obj, atomsCache->args_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); nsCString const & currentValue = mId; if (!UTF8StringToJsval(cx, currentValue, &temp)) { return false; } if (!JS_DefinePropertyById(cx, obj, atomsCache->id_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); return true; } void L10nIdArgs::TraceDictionary(JSTracer* trc) { } L10nMessage::L10nMessage() { // Safe to pass a null context if we pass a null value Init(nullptr, JS::NullHandleValue); } bool L10nMessage::InitIds(JSContext* cx, L10nMessageAtoms* atomsCache) { MOZ_ASSERT(reinterpret_cast(atomsCache)->isVoid()); // Initialize these in reverse order so that any failure leaves the first one // uninitialized. if (!atomsCache->value_id.init(cx, "value") || !atomsCache->attributes_id.init(cx, "attributes")) { return false; } return true; } bool L10nMessage::Init(BindingCallContext& cx, JS::Handle 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()); L10nMessageAtoms* atomsCache = nullptr; if (cx) { atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } } if (!IsConvertibleToDictionary(val)) { return cx.ThrowErrorMessage(sourceDescription, "dictionary"); } bool isNull = val.isNullOrUndefined(); // We only need these if !isNull, in which case we have |cx|. Maybe > object; Maybe > temp; if (!isNull) { MOZ_ASSERT(cx); object.emplace(cx, &val.toObject()); temp.emplace(cx); } if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->attributes_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { if (temp.ref().isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(temp.ref(), JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("'attributes' member of L10nMessage", "sequence"); return false; } Sequence &arr = mAttributes.SetValue(); if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } AttributeNameValue* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } AttributeNameValue& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of 'attributes' member of L10nMessage", passedToJSImpl)) { return false; } } } else if (temp.ref().isNullOrUndefined()) { mAttributes.SetNull(); } else { cx.ThrowErrorMessage("'attributes' member of L10nMessage", "sequence"); return false; } } else { mAttributes.SetNull(); } mIsAnyMemberPresent = true; if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->value_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { if (!ConvertJSValueToString(cx, temp.ref(), eNull, eNull, mValue)) { return false; } } else { mValue.SetIsVoid(true); } mIsAnyMemberPresent = true; return true; } bool L10nMessage::Init(JSContext* cx_, JS::Handle val, const char* sourceDescription, bool passedToJSImpl) { // We don't want to use sourceDescription for our context here; // that's not really what it's formatted for. BindingCallContext cx(cx_, nullptr); return Init(cx, val, sourceDescription, passedToJSImpl); } bool L10nMessage::ToObjectInternal(JSContext* cx, JS::MutableHandle rval) const { L10nMessageAtoms* atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } JS::Rooted obj(cx, JS_NewPlainObject(cx)); if (!obj) { return false; } rval.setObject(*obj); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); Nullable> const & currentValue = mAttributes; if (currentValue.IsNull()) { temp.setNull(); if (!JS_DefinePropertyById(cx, obj, atomsCache->attributes_id, temp, JSPROP_ENUMERATE)) { return false; } break; } uint32_t length = currentValue.Value().Length(); JS::Rooted returnArray(cx, JS::NewArrayObject(cx, length)); if (!returnArray) { return false; } // Scope for 'tmp' { JS::Rooted tmp(cx); for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) { // Control block to let us common up the JS_DefineElement calls when there // are different ways to succeed at wrapping the object. do { if (!currentValue.Value()[sequenceIdx0].ToObjectInternal(cx, &tmp)) { return false; } break; } while (false); if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp, JSPROP_ENUMERATE)) { return false; } } } temp.setObject(*returnArray); if (!JS_DefinePropertyById(cx, obj, atomsCache->attributes_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); nsCString const & currentValue = mValue; if (!UTF8StringToJsval(cx, currentValue, &temp)) { return false; } if (!JS_DefinePropertyById(cx, obj, atomsCache->value_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); return true; } void L10nMessage::TraceDictionary(JSTracer* trc) { } L10nMessage& L10nMessage::operator=(const L10nMessage& aOther) { MaybeEmptyDictionaryBase::operator=(aOther); mAttributes = aOther.mAttributes; mValue = aOther.mValue; return *this; } bool UTF8StringOrL10nIdArgs::TrySetToUTF8String(JSContext* cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot nsAutoCString& memberSlot = RawSetAsUTF8String(); if (!ConvertJSValueToString(cx, value, eStringify, eStringify, memberSlot)) { return false; } } return true; } bool UTF8StringOrL10nIdArgs::TrySetToL10nIdArgs(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot binding_detail::FastL10nIdArgs& memberSlot = RawSetAsL10nIdArgs(); if (!IsConvertibleToDictionary(value)) { DestroyL10nIdArgs(); tryNext = true; return true; } if (!memberSlot.Init(cx, value, "L10nIdArgs branch of (USVString or L10nIdArgs)", passedToJSImpl)) { return false; } } return true; } bool UTF8StringOrL10nIdArgs::TrySetToL10nIdArgs(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToL10nIdArgs(cx, value, tryNext, passedToJSImpl); } bool UTF8StringOrL10nIdArgs::Init(BindingCallContext& cx, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { MOZ_ASSERT(mType == eUninitialized); bool done = false, failed = false, tryNext; if (!done) { done = (failed = !TrySetToL10nIdArgs(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(sourceDescription, "L10nIdArgs"); return false; } return true; } bool UTF8StringOrL10nIdArgs::Init(JSContext* cx_, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return Init(cx, value, sourceDescription, passedToJSImpl); } bool UTF8StringOrL10nIdArgs::ToJSVal(JSContext* cx, JS::Handle scopeObj, JS::MutableHandle rval) const { switch (mType) { case eUninitialized: { return false; } case eUTF8String: { if (!NonVoidUTF8StringToJsval(cx, mValue.mUTF8String.Value(), rval)) { return false; } return true; } case eL10nIdArgs: { if (!mValue.mL10nIdArgs.Value().ToObjectInternal(cx, rval)) { return false; } return true; } default: { return false; } } } OwningUTF8StringOrL10nIdArgs::OwningUTF8StringOrL10nIdArgs(OwningUTF8StringOrL10nIdArgs&& aOther) : mType(eUninitialized) { switch (aOther.mType) { case eUninitialized: { MOZ_ASSERT(mType == eUninitialized, "We need to destroy ourselves?"); break; } case eUTF8String: { mType = eUTF8String; mValue.mUTF8String.SetValue(std::move(aOther.mValue.mUTF8String.Value())); break; } case eL10nIdArgs: { mType = eL10nIdArgs; mValue.mL10nIdArgs.SetValue(std::move(aOther.mValue.mL10nIdArgs.Value())); break; } } } bool OwningUTF8StringOrL10nIdArgs::TrySetToUTF8String(JSContext* cx, JS::Handle 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& OwningUTF8StringOrL10nIdArgs::RawSetAsUTF8String() { if (mType == eUTF8String) { return mValue.mUTF8String.Value(); } MOZ_ASSERT(mType == eUninitialized); mType = eUTF8String; return mValue.mUTF8String.SetValue(); } [[nodiscard]] nsCString& OwningUTF8StringOrL10nIdArgs::SetAsUTF8String() { if (mType == eUTF8String) { return mValue.mUTF8String.Value(); } Uninit(); mType = eUTF8String; return mValue.mUTF8String.SetValue(); } void OwningUTF8StringOrL10nIdArgs::DestroyUTF8String() { MOZ_RELEASE_ASSERT(IsUTF8String(), "Wrong type!"); mValue.mUTF8String.Destroy(); mType = eUninitialized; } bool OwningUTF8StringOrL10nIdArgs::TrySetToL10nIdArgs(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot L10nIdArgs& memberSlot = RawSetAsL10nIdArgs(); if (!IsConvertibleToDictionary(value)) { DestroyL10nIdArgs(); tryNext = true; return true; } if (!memberSlot.Init(cx, value, "L10nIdArgs branch of (USVString or L10nIdArgs)", passedToJSImpl)) { return false; } } return true; } bool OwningUTF8StringOrL10nIdArgs::TrySetToL10nIdArgs(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToL10nIdArgs(cx, value, tryNext, passedToJSImpl); } [[nodiscard]] L10nIdArgs& OwningUTF8StringOrL10nIdArgs::RawSetAsL10nIdArgs() { if (mType == eL10nIdArgs) { return mValue.mL10nIdArgs.Value(); } MOZ_ASSERT(mType == eUninitialized); mType = eL10nIdArgs; return mValue.mL10nIdArgs.SetValue(); } [[nodiscard]] L10nIdArgs& OwningUTF8StringOrL10nIdArgs::SetAsL10nIdArgs() { if (mType == eL10nIdArgs) { return mValue.mL10nIdArgs.Value(); } Uninit(); mType = eL10nIdArgs; return mValue.mL10nIdArgs.SetValue(); } void OwningUTF8StringOrL10nIdArgs::DestroyL10nIdArgs() { MOZ_RELEASE_ASSERT(IsL10nIdArgs(), "Wrong type!"); mValue.mL10nIdArgs.Destroy(); mType = eUninitialized; } bool OwningUTF8StringOrL10nIdArgs::Init(BindingCallContext& cx, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { MOZ_ASSERT(mType == eUninitialized); bool done = false, failed = false, tryNext; if (!done) { done = (failed = !TrySetToL10nIdArgs(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(sourceDescription, "L10nIdArgs"); return false; } return true; } bool OwningUTF8StringOrL10nIdArgs::Init(JSContext* cx_, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return Init(cx, value, sourceDescription, passedToJSImpl); } void OwningUTF8StringOrL10nIdArgs::Uninit() { switch (mType) { case eUninitialized: { break; } case eUTF8String: { DestroyUTF8String(); break; } case eL10nIdArgs: { DestroyL10nIdArgs(); break; } } } bool OwningUTF8StringOrL10nIdArgs::ToJSVal(JSContext* cx, JS::Handle scopeObj, JS::MutableHandle rval) const { switch (mType) { case eUninitialized: { return false; } case eUTF8String: { if (!NonVoidUTF8StringToJsval(cx, mValue.mUTF8String.Value(), rval)) { return false; } return true; } case eL10nIdArgs: { if (!mValue.mL10nIdArgs.Value().ToObjectInternal(cx, rval)) { return false; } return true; } default: { return false; } } } OwningUTF8StringOrL10nIdArgs& OwningUTF8StringOrL10nIdArgs::operator=(OwningUTF8StringOrL10nIdArgs&& aOther) { this->~OwningUTF8StringOrL10nIdArgs(); new (this) OwningUTF8StringOrL10nIdArgs (std::move(aOther)); return *this; } namespace Localization_Binding { MOZ_CAN_RUN_SCRIPT static bool addResourceIds(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.addResourceIds"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "addResourceIds", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.addResourceIds", 1)) { return false; } binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrResourceId* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrResourceId& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } // NOTE: This assert does NOT call the function. static_assert(std::is_void_vAddResourceIds(Constify(arg0)))>, "Should be returning void here"); MOZ_KnownLive(self)->AddResourceIds(Constify(arg0)); MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setUndefined(); return true; } static const JSJitInfo addResourceIds_methodinfo = { { (JSJitGetterOp)addResourceIds }, { prototypes::id::Localization }, { PrototypeTraits::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 removeResourceIds(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.removeResourceIds"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "removeResourceIds", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.removeResourceIds", 1)) { return false; } binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrResourceId* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrResourceId& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } uint32_t result(MOZ_KnownLive(self)->RemoveResourceIds(Constify(arg0))); MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setNumber(result); return true; } static const JSJitInfo removeResourceIds_methodinfo = { { (JSJitGetterOp)removeResourceIds }, { prototypes::id::Localization }, { PrototypeTraits::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 formatValue(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.formatValue"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "formatValue", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.formatValue", 1)) { return false; } nsAutoCString arg0; if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) { return false; } Optional>> arg1; if (args.hasDefined(1)) { arg1.Construct(); if (args[1].isObject()) { auto& recordEntries = arg1.Value().Entries(); JS::Rooted recordObj(cx, &args[1].toObject()); JS::RootedVector ids(cx); if (!js::GetPropertyKeys(cx, recordObj, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) { return false; } if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } JS::Rooted propNameValue(cx); JS::Rooted temp(cx); JS::Rooted curId(cx); JS::Rooted idVal(cx); // Use a hashset to keep track of ids seen, to avoid // introducing nasty O(N^2) behavior scanning for them all the // time. Ideally we'd use a data structure with O(1) lookup // _and_ ordering for the MozMap, but we don't have one lying // around. nsTHashtable idsSeen; for (size_t i = 0; i < ids.length(); ++i) { curId = ids[i]; JS::Rooted> desc(cx); if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId, &desc)) { return false; } if (desc.isNothing() || !desc->enumerable()) { continue; } idVal = js::IdToValue(curId); nsCString propName; // This will just throw if idVal is a Symbol, like the spec says // to do. if (!ConvertJSValueToString(cx, idVal, "key of argument 2", propName)) { return false; } if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) { return false; } Record>::EntryType* entry; if (!idsSeen.EnsureInserted(propName)) { // Find the existing entry. auto idx = recordEntries.IndexOf(propName); MOZ_ASSERT(idx != recordEntries.NoIndex, "Why is it not found?"); // Now blow it away to make it look like it was just added // to the array, because it's not obvious that it's // safe to write to its already-initialized mValue via our // normal codegen conversions. For example, the value // could be a union and this would change its type, but // codegen assumes we won't do that. entry = recordEntries.ReconstructElementAt(idx); } else { // Safe to do an infallible append here, because we did a // SetCapacity above to the right capacity. entry = recordEntries.AppendElement(); } entry->mKey = propName; Nullable& slot = entry->mValue; if (temp.isNullOrUndefined()) { slot.SetNull(); } else { if (!slot.SetValue().Init(cx, temp, "Value in argument 2", false)) { return false; } } } } else { cx.ThrowErrorMessage("Argument 2"); return false; } } FastErrorResult rv; auto result(StrongOrRawPtr(MOZ_KnownLive(self)->FormatValue(Constify(arg0), Constify(arg1), rv))); if (rv.MaybeSetPendingException(cx, "Localization.formatValue")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); static_assert(!std::is_pointer_v, "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 formatValue_promiseWrapper(JSContext* cx, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { bool ok = formatValue(cx, obj, void_self, args); if (ok) { return true; } return ConvertExceptionToPromise(cx, args.rval()); } static const JSJitInfo formatValue_methodinfo = { { (JSJitGetterOp)formatValue_promiseWrapper }, { prototypes::id::Localization }, { PrototypeTraits::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 formatValues(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.formatValues"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "formatValues", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.formatValues", 1)) { return false; } binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrL10nIdArgs* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrL10nIdArgs& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } FastErrorResult rv; auto result(StrongOrRawPtr(MOZ_KnownLive(self)->FormatValues(Constify(arg0), rv))); if (rv.MaybeSetPendingException(cx, "Localization.formatValues")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); static_assert(!std::is_pointer_v, "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 formatValues_promiseWrapper(JSContext* cx, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { bool ok = formatValues(cx, obj, void_self, args); if (ok) { return true; } return ConvertExceptionToPromise(cx, args.rval()); } static const JSJitInfo formatValues_methodinfo = { { (JSJitGetterOp)formatValues_promiseWrapper }, { prototypes::id::Localization }, { PrototypeTraits::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 formatMessages(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.formatMessages"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "formatMessages", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.formatMessages", 1)) { return false; } binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrL10nIdArgs* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrL10nIdArgs& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } FastErrorResult rv; auto result(StrongOrRawPtr(MOZ_KnownLive(self)->FormatMessages(Constify(arg0), rv))); if (rv.MaybeSetPendingException(cx, "Localization.formatMessages")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); static_assert(!std::is_pointer_v, "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 formatMessages_promiseWrapper(JSContext* cx, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { bool ok = formatMessages(cx, obj, void_self, args); if (ok) { return true; } return ConvertExceptionToPromise(cx, args.rval()); } static const JSJitInfo formatMessages_methodinfo = { { (JSJitGetterOp)formatMessages_promiseWrapper }, { prototypes::id::Localization }, { PrototypeTraits::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 setAsync(JSContext* cx, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "setAsync", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); // NOTE: This assert does NOT call the function. static_assert(std::is_void_vSetAsync())>, "Should be returning void here"); MOZ_KnownLive(self)->SetAsync(); MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setUndefined(); return true; } static const JSJitInfo setAsync_methodinfo = { { (JSJitGetterOp)setAsync }, { prototypes::id::Localization }, { PrototypeTraits::Depth }, JSJitInfo::Method, JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */ JSVAL_TYPE_UNDEFINED, /* returnType. Not relevant for setters. */ true, /* isInfallible. False in setters. */ false, /* isMovable. Not relevant for setters. */ false, /* isEliminatable. Not relevant for setters. */ false, /* isAlwaysInSlot. Only relevant for getters. */ false, /* isLazilyCachedInSlot. Only relevant for getters. */ false, /* isTypedMethod. Only relevant for methods. */ 0 /* Reserved slot index, if we're stored in a slot, else 0. */ }; MOZ_CAN_RUN_SCRIPT static bool formatValueSync(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.formatValueSync"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "formatValueSync", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.formatValueSync", 1)) { return false; } nsAutoCString arg0; if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) { return false; } Optional>> arg1; if (args.hasDefined(1)) { arg1.Construct(); if (args[1].isObject()) { auto& recordEntries = arg1.Value().Entries(); JS::Rooted recordObj(cx, &args[1].toObject()); JS::RootedVector ids(cx); if (!js::GetPropertyKeys(cx, recordObj, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &ids)) { return false; } if (!recordEntries.SetCapacity(ids.length(), mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } JS::Rooted propNameValue(cx); JS::Rooted temp(cx); JS::Rooted curId(cx); JS::Rooted idVal(cx); // Use a hashset to keep track of ids seen, to avoid // introducing nasty O(N^2) behavior scanning for them all the // time. Ideally we'd use a data structure with O(1) lookup // _and_ ordering for the MozMap, but we don't have one lying // around. nsTHashtable idsSeen; for (size_t i = 0; i < ids.length(); ++i) { curId = ids[i]; JS::Rooted> desc(cx); if (!JS_GetOwnPropertyDescriptorById(cx, recordObj, curId, &desc)) { return false; } if (desc.isNothing() || !desc->enumerable()) { continue; } idVal = js::IdToValue(curId); nsCString propName; // This will just throw if idVal is a Symbol, like the spec says // to do. if (!ConvertJSValueToString(cx, idVal, "key of argument 2", propName)) { return false; } if (!JS_GetPropertyById(cx, recordObj, curId, &temp)) { return false; } Record>::EntryType* entry; if (!idsSeen.EnsureInserted(propName)) { // Find the existing entry. auto idx = recordEntries.IndexOf(propName); MOZ_ASSERT(idx != recordEntries.NoIndex, "Why is it not found?"); // Now blow it away to make it look like it was just added // to the array, because it's not obvious that it's // safe to write to its already-initialized mValue via our // normal codegen conversions. For example, the value // could be a union and this would change its type, but // codegen assumes we won't do that. entry = recordEntries.ReconstructElementAt(idx); } else { // Safe to do an infallible append here, because we did a // SetCapacity above to the right capacity. entry = recordEntries.AppendElement(); } entry->mKey = propName; Nullable& slot = entry->mValue; if (temp.isNullOrUndefined()) { slot.SetNull(); } else { if (!slot.SetValue().Init(cx, temp, "Value in argument 2", false)) { return false; } } } } else { cx.ThrowErrorMessage("Argument 2"); return false; } } FastErrorResult rv; nsAutoCString result; // NOTE: This assert does NOT call the function. static_assert(std::is_void_vFormatValueSync(Constify(arg0), Constify(arg1), result, rv))>, "Should be returning void here"); MOZ_KnownLive(self)->FormatValueSync(Constify(arg0), Constify(arg1), result, rv); if (rv.MaybeSetPendingException(cx, "Localization.formatValueSync")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); if (!UTF8StringToJsval(cx, result, args.rval())) { return false; } return true; } static const JSJitInfo formatValueSync_methodinfo = { { (JSJitGetterOp)formatValueSync }, { prototypes::id::Localization }, { PrototypeTraits::Depth }, JSJitInfo::Method, JSJitInfo::AliasEverything, /* aliasSet. Not relevant for setters. */ JSVAL_TYPE_UNKNOWN, /* 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 formatValuesSync(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.formatValuesSync"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "formatValuesSync", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.formatValuesSync", 1)) { return false; } binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrL10nIdArgs* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrL10nIdArgs& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } FastErrorResult rv; nsTArray result; // NOTE: This assert does NOT call the function. static_assert(std::is_void_vFormatValuesSync(Constify(arg0), result, rv))>, "Should be returning void here"); MOZ_KnownLive(self)->FormatValuesSync(Constify(arg0), result, rv); if (rv.MaybeSetPendingException(cx, "Localization.formatValuesSync")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); uint32_t length = result.Length(); JS::Rooted returnArray(cx, JS::NewArrayObject(cx, length)); if (!returnArray) { return false; } // Scope for 'tmp' { JS::Rooted tmp(cx); for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) { // Control block to let us common up the JS_DefineElement calls when there // are different ways to succeed at wrapping the object. do { if (!UTF8StringToJsval(cx, result[sequenceIdx0], &tmp)) { return false; } break; } while (false); if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp, JSPROP_ENUMERATE)) { return false; } } } args.rval().setObject(*returnArray); return true; } static const JSJitInfo formatValuesSync_methodinfo = { { (JSJitGetterOp)formatValuesSync }, { prototypes::id::Localization }, { PrototypeTraits::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 formatMessagesSync(JSContext* cx_, JS::Handle obj, void* void_self, const JSJitMethodCallArgs& args) { BindingCallContext cx(cx_, "Localization.formatMessagesSync"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "formatMessagesSync", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); auto* self = static_cast(void_self); if (!args.requireAtLeast(cx, "Localization.formatMessagesSync", 1)) { return false; } binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrL10nIdArgs* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrL10nIdArgs& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } FastErrorResult rv; nsTArray> result; // NOTE: This assert does NOT call the function. static_assert(std::is_void_vFormatMessagesSync(Constify(arg0), result, rv))>, "Should be returning void here"); MOZ_KnownLive(self)->FormatMessagesSync(Constify(arg0), result, rv); if (rv.MaybeSetPendingException(cx, "Localization.formatMessagesSync")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); uint32_t length = result.Length(); JS::Rooted returnArray(cx, JS::NewArrayObject(cx, length)); if (!returnArray) { return false; } // Scope for 'tmp' { JS::Rooted tmp(cx); for (uint32_t sequenceIdx0 = 0; sequenceIdx0 < length; ++sequenceIdx0) { // Control block to let us common up the JS_DefineElement calls when there // are different ways to succeed at wrapping the object. do { if (result[sequenceIdx0].IsNull()) { tmp.setNull(); break; } if (!result[sequenceIdx0].Value().ToObjectInternal(cx, &tmp)) { return false; } break; } while (false); if (!JS_DefineElement(cx, returnArray, sequenceIdx0, tmp, JSPROP_ENUMERATE)) { return false; } } } args.rval().setObject(*returnArray); return true; } static const JSJitInfo formatMessagesSync_methodinfo = { { (JSJitGetterOp)formatMessagesSync }, { prototypes::id::Localization }, { PrototypeTraits::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. */ }; static void _finalize(JS::GCContext* gcx, JSObject* obj) { mozilla::intl::Localization* self = UnwrapPossiblyNotInitializedDOMObject(obj); if (self) { JS::SetNativeObjectReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue()); ClearWrapper(self, self, obj); if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) { JS::RemoveAssociatedMemory(obj, mallocBytes, JS::MemoryUse::DOMBinding); } AddForDeferredFinalization(self); } } MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = { JS_FNSPEC("addResourceIds", (GenericMethod), reinterpret_cast(&addResourceIds_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("removeResourceIds", (GenericMethod), reinterpret_cast(&removeResourceIds_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("formatValue", (GenericMethod), reinterpret_cast(&formatValue_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("formatValues", (GenericMethod), reinterpret_cast(&formatValues_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("formatMessages", (GenericMethod), reinterpret_cast(&formatMessages_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("setAsync", (GenericMethod), reinterpret_cast(&setAsync_methodinfo), 0, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("formatValueSync", (GenericMethod), reinterpret_cast(&formatValueSync_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("formatValuesSync", (GenericMethod), reinterpret_cast(&formatValuesSync_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("formatMessagesSync", (GenericMethod), reinterpret_cast(&formatMessagesSync_methodinfo), 1, JSPROP_ENUMERATE, nullptr), JS_FS_END }; static const Prefable 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(9 <= 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<1> sNativeProperties = { false, 0, false, 0, true, 0 /* sMethods */, false, 0, false, 0, false, 0, false, 0, -1, 9, sNativeProperties_sortedPropertyIndices, { { sMethods, &sNativeProperties_propertyInfos[0] } } }; static_assert(9 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)), "We have a property info count that is oversized"); bool sNativePropertiesInited = false; const NativePropertyHooks sNativePropertyHooks = { nullptr, { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited }, prototypes::id::Localization, constructors::id::Localization, &DefaultXrayExpandoObjectClass }; static bool _constructor(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "Localization constructor"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "Localization", "constructor", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.isConstructing()) { return ThrowConstructorWithoutNew(cx, "Localization"); } JS::Rooted desiredProto(cx); if (!GetDesiredProto(cx, args, prototypes::id::Localization, CreateInterfaceObjects, &desiredProto)) { return false; } if (!args.requireAtLeast(cx, "Localization constructor", 1)) { return false; } GlobalObject global(cx, obj); if (global.Failed()) { return false; } bool objIsXray = xpc::WrapperFactory::IsXrayWrapper(obj); binding_detail::AutoSequence arg0; if (args[0].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[0], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } binding_detail::AutoSequence &arr = arg0; if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } OwningUTF8StringOrResourceId* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } OwningUTF8StringOrResourceId& slot = *slotPtr; if (!slot.Init(cx, temp, "Element of argument 1", false)) { return false; } } } else { cx.ThrowErrorMessage("Argument 1", "sequence"); return false; } bool arg1; if (args.hasDefined(1)) { if (!ValueToPrimitive(cx, args[1], "Argument 2", &arg1)) { return false; } } else { arg1 = false; } Optional> arg2; if (args.hasDefined(2)) { arg2.Construct(); if (args[2].isObject()) { { // Our JSContext should be in the right global to do unwrapping in. nsresult rv = UnwrapObject(args[2], arg2.Value(), cx); if (NS_FAILED(rv)) { cx.ThrowErrorMessage("Argument 3", "L10nRegistry"); return false; } } } else { cx.ThrowErrorMessage("Argument 3"); return false; } } Optional> arg3; if (args.hasDefined(3)) { arg3.Construct(); if (args[3].isObject()) { JS::ForOfIterator iter(cx); if (!iter.init(args[3], JS::ForOfIterator::AllowNonIterable)) { return false; } if (!iter.valueIsIterable()) { cx.ThrowErrorMessage("Argument 4", "sequence"); return false; } Sequence &arr = arg3.Value(); if (mozilla::Maybe sizeHint = iter.sizeHint()) { if (!arr.SetCapacity(*sizeHint, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } } JS::Rooted temp(cx); while (true) { bool done; if (!iter.next(&temp, &done)) { return false; } if (done) { break; } nsCString* slotPtr = arr.AppendElement(mozilla::fallible); if (!slotPtr) { JS_ReportOutOfMemory(cx); return false; } nsCString& slot = *slotPtr; if (!ConvertJSValueToString(cx, temp, eStringify, eStringify, slot)) { return false; } } } else { cx.ThrowErrorMessage("Argument 4", "sequence"); return false; } } Maybe 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::intl::Localization::Constructor(global, Constify(arg0), arg1, MOZ_KnownLive(NonNullHelper(Constify(arg2))), Constify(arg3), rv))); if (rv.MaybeSetPendingException(cx, "Localization constructor")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); static_assert(!std::is_pointer_v, "NewObject implies that we need to keep the object alive with a strong reference."); if (!GetOrCreateDOMReflector(cx, result, args.rval(), desiredProto)) { MOZ_ASSERT(JS_IsExceptionPending(cx)); return false; } return true; } static const DOMInterfaceInfo sInterfaceObjectInfo = { { _constructor, &sNativePropertyHooks }, JS::GetRealmFunctionPrototypeHandle, PrototypeTraits::Depth, prototypes::id::Localization, true, 1, "Localization", }; static const DOMIfaceAndProtoJSClass sPrototypeClass = { { "LocalizationPrototype", 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::Localization, PrototypeTraits::Depth, &sNativePropertyHooks, JS::GetRealmObjectPrototype }; bool ConstructorEnabled(JSContext* aCx, JS::Handle aObj) { return mozilla::intl::Localization::IsAPIEnabled(aCx, aObj); } 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 = { { "Localization", JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER, &sClassOps, JS_NULL_CLASS_SPEC, &NativeTypeHelpers::sClassExtension, JS_NULL_OBJECT_OPS }, { prototypes::id::Localization, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count }, std::is_base_of_v, &sNativePropertyHooks, GetProtoObjectHandle, GetCCParticipant::Get(), nullptr, NativeTypeHelpers::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::intl::Localization* aObject, nsWrapperCache* aCache, JS::Handle aGivenProto, JS::MutableHandle aReflector) { static_assert(!std::is_base_of_v, "Shouldn't have wrappercached things that are not refcounted."); static_assert(std::is_same_v); 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 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 canonicalProto = GetProtoObjectHandle(aCx); if (!canonicalProto) { return false; } JS::Rooted 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 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 aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal) { JS::Heap* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::Localization); JS::Heap* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::Localization); JS::Handle parentProto(JS::GetRealmObjectPrototypeHandle(aCx)); if (!parentProto) { return; } JS::Handle constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx)); if (!constructorProto) { return; } dom::CreateInterfaceObjects(aCx, aGlobal, parentProto, &sPrototypeClass, protoCache, constructorProto, &sInterfaceObjectInfo, 1, false, Span{}, interfaceCache, sNativeProperties.Upcast(), nullptr, "Localization", ShouldExpose(aCx, aGlobal, aDefineOnGlobal), nullptr, false, nullptr); } JS::Handle GetProtoObjectHandle(JSContext* aCx) { /* Get the interface prototype object for this class. This will create the object as needed. */ return GetPerInterfaceObjectHandle(aCx, prototypes::id::Localization, &CreateInterfaceObjects, DefineInterfaceProperty::CheckExposure); } JSObject* GetProtoObject(JSContext* aCx) { return GetProtoObjectHandle(aCx); } JS::Handle GetConstructorObjectHandle(JSContext* aCx) { /* Get the interface object for this class. This will create the object as needed. */ return GetPerInterfaceObjectHandle(aCx, constructors::id::Localization, &CreateInterfaceObjects, DefineInterfaceProperty::CheckExposure); } } // namespace Localization_Binding } // namespace mozilla::dom