Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "builtin/ModuleObject.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/EnumSet.h"
#include "mozilla/ScopeExit.h"
#include "builtin/Promise.h"
#include "builtin/SelfHostingDefines.h"
#include "frontend/ParseNode.h"
#include "frontend/SharedContext.h"
#include "gc/FreeOp.h"
#include "gc/Policy.h"
#include "gc/Tracer.h"
#include "js/friend/ErrorMessages.h" // JSMSG_*
#include "js/Modules.h" // JS::GetModulePrivate, JS::ModuleDynamicImportHook
#include "js/PropertySpec.h"
#include "vm/AsyncFunction.h"
#include "vm/AsyncIteration.h"
#include "vm/EqualityOperations.h" // js::SameValue
#include "vm/ModuleBuilder.h" // js::ModuleBuilder
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/PromiseObject.h" // js::PromiseObject
#include "vm/SelfHosting.h"
#include "vm/SharedStencil.h" // js::GCThingIndex
#include "builtin/HandlerFunction-inl.h" // js::ExtraValueFromHandler, js::NewHandler{,WithExtraValue}, js::TargetFromHandler
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/List-inl.h"
#include "vm/NativeObject-inl.h"
using namespace js;
static_assert(MODULE_STATUS_UNLINKED < MODULE_STATUS_LINKING &&
MODULE_STATUS_LINKING < MODULE_STATUS_LINKED &&
MODULE_STATUS_LINKED < MODULE_STATUS_EVALUATED &&
MODULE_STATUS_EVALUATED < MODULE_STATUS_EVALUATED_ERROR,
"Module statuses are ordered incorrectly");
template <typename T, Value ValueGetter(const T* obj)>
static bool ModuleValueGetterImpl(JSContext* cx, const CallArgs& args) {
args.rval().set(ValueGetter(&args.thisv().toObject().as<T>()));
return true;
}
template <typename T, Value ValueGetter(const T* obj)>
static bool ModuleValueGetter(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<T::isInstance,
ModuleValueGetterImpl<T, ValueGetter>>(cx, args);
}
#define DEFINE_GETTER_FUNCTIONS(cls, name, slot) \
static Value cls##_##name##Value(const cls* obj) { \
return obj->getReservedSlot(cls::slot); \
} \
\
static bool cls##_##name##Getter(JSContext* cx, unsigned argc, Value* vp) { \
return ModuleValueGetter<cls, cls##_##name##Value>(cx, argc, vp); \
}
#define DEFINE_ATOM_ACCESSOR_METHOD(cls, name) \
JSAtom* cls::name() const { \
Value value = cls##_##name##Value(this); \
return &value.toString()->asAtom(); \
}
#define DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(cls, name) \
JSAtom* cls::name() const { \
Value value = cls##_##name##Value(this); \
if (value.isNull()) return nullptr; \
return &value.toString()->asAtom(); \
}
#define DEFINE_UINT32_ACCESSOR_METHOD(cls, name) \
uint32_t cls::name() const { \
Value value = cls##_##name##Value(this); \
MOZ_ASSERT(value.toNumber() >= 0); \
if (value.isInt32()) return value.toInt32(); \
return JS::ToUint32(value.toDouble()); \
}
static Value StringOrNullValue(JSString* maybeString) {
return maybeString ? StringValue(maybeString) : NullValue();
}
///////////////////////////////////////////////////////////////////////////
// ImportEntryObject
/* static */ const JSClass ImportEntryObject::class_ = {
"ImportEntry", JSCLASS_HAS_RESERVED_SLOTS(ImportEntryObject::SlotCount)};
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, moduleRequest, ModuleRequestSlot)
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, importName, ImportNameSlot)
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, localName, LocalNameSlot)
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, lineNumber, LineNumberSlot)
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, columnNumber, ColumnNumberSlot)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ImportEntryObject, importName)
DEFINE_ATOM_ACCESSOR_METHOD(ImportEntryObject, localName)
DEFINE_UINT32_ACCESSOR_METHOD(ImportEntryObject, lineNumber)
DEFINE_UINT32_ACCESSOR_METHOD(ImportEntryObject, columnNumber)
ModuleRequestObject* ImportEntryObject::moduleRequest() const {
Value value = getReservedSlot(ModuleRequestSlot);
return &value.toObject().as<ModuleRequestObject>();
}
/* static */
bool ImportEntryObject::isInstance(HandleValue value) {
return value.isObject() && value.toObject().is<ImportEntryObject>();
}
/* static */
bool GlobalObject::initImportEntryProto(JSContext* cx,
Handle<GlobalObject*> global) {
static const JSPropertySpec protoAccessors[] = {
JS_PSG("moduleRequest", ImportEntryObject_moduleRequestGetter, 0),
JS_PSG("importName", ImportEntryObject_importNameGetter, 0),
JS_PSG("localName", ImportEntryObject_localNameGetter, 0),
JS_PSG("lineNumber", ImportEntryObject_lineNumberGetter, 0),
JS_PSG("columnNumber", ImportEntryObject_columnNumberGetter, 0),
JS_PS_END};
RootedObject proto(
cx, GlobalObject::createBlankPrototype<PlainObject>(cx, global));
if (!proto) {
return false;
}
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, nullptr)) {
return false;
}
global->initBuiltinProto(ProtoKind::ImportEntryProto, proto);
return true;
}
/* static */
ImportEntryObject* ImportEntryObject::create(
JSContext* cx, HandleObject moduleRequest, HandleAtom maybeImportName,
HandleAtom localName, uint32_t lineNumber, uint32_t columnNumber) {
RootedObject proto(
cx, GlobalObject::getOrCreateImportEntryPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
ImportEntryObject* self =
NewObjectWithGivenProto<ImportEntryObject>(cx, proto);
if (!self) {
return nullptr;
}
self->initReservedSlot(ModuleRequestSlot, ObjectValue(*moduleRequest));
self->initReservedSlot(ImportNameSlot, StringOrNullValue(maybeImportName));
self->initReservedSlot(LocalNameSlot, StringValue(localName));
self->initReservedSlot(LineNumberSlot, NumberValue(lineNumber));
self->initReservedSlot(ColumnNumberSlot, NumberValue(columnNumber));
return self;
}
///////////////////////////////////////////////////////////////////////////
// ExportEntryObject
/* static */ const JSClass ExportEntryObject::class_ = {
"ExportEntry", JSCLASS_HAS_RESERVED_SLOTS(ExportEntryObject::SlotCount)};
DEFINE_GETTER_FUNCTIONS(ExportEntryObject, exportName, ExportNameSlot)
DEFINE_GETTER_FUNCTIONS(ExportEntryObject, moduleRequest, ModuleRequestSlot)
DEFINE_GETTER_FUNCTIONS(ExportEntryObject, importName, ImportNameSlot)
DEFINE_GETTER_FUNCTIONS(ExportEntryObject, localName, LocalNameSlot)
DEFINE_GETTER_FUNCTIONS(ExportEntryObject, lineNumber, LineNumberSlot)
DEFINE_GETTER_FUNCTIONS(ExportEntryObject, columnNumber, ColumnNumberSlot)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ExportEntryObject, exportName)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ExportEntryObject, importName)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ExportEntryObject, localName)
DEFINE_UINT32_ACCESSOR_METHOD(ExportEntryObject, lineNumber)
DEFINE_UINT32_ACCESSOR_METHOD(ExportEntryObject, columnNumber)
ModuleRequestObject* ExportEntryObject::moduleRequest() const {
Value value = getReservedSlot(ModuleRequestSlot);
return &value.toObject().as<ModuleRequestObject>();
}
/* static */
bool ExportEntryObject::isInstance(HandleValue value) {
return value.isObject() && value.toObject().is<ExportEntryObject>();
}
/* static */
bool GlobalObject::initExportEntryProto(JSContext* cx,
Handle<GlobalObject*> global) {
static const JSPropertySpec protoAccessors[] = {
JS_PSG("exportName", ExportEntryObject_exportNameGetter, 0),
JS_PSG("moduleRequest", ExportEntryObject_moduleRequestGetter, 0),
JS_PSG("importName", ExportEntryObject_importNameGetter, 0),
JS_PSG("localName", ExportEntryObject_localNameGetter, 0),
JS_PSG("lineNumber", ExportEntryObject_lineNumberGetter, 0),
JS_PSG("columnNumber", ExportEntryObject_columnNumberGetter, 0),
JS_PS_END};
RootedObject proto(
cx, GlobalObject::createBlankPrototype<PlainObject>(cx, global));
if (!proto) {
return false;
}
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, nullptr)) {
return false;
}
global->initBuiltinProto(ProtoKind::ExportEntryProto, proto);
return true;
}
/* static */
ExportEntryObject* ExportEntryObject::create(
JSContext* cx, HandleAtom maybeExportName, HandleObject moduleRequest,
HandleAtom maybeImportName, HandleAtom maybeLocalName, uint32_t lineNumber,
uint32_t columnNumber) {
// Line and column numbers are optional for export entries since direct
// entries are checked at parse time.
RootedObject proto(
cx, GlobalObject::getOrCreateExportEntryPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
ExportEntryObject* self =
NewObjectWithGivenProto<ExportEntryObject>(cx, proto);
if (!self) {
return nullptr;
}
self->initReservedSlot(ExportNameSlot, StringOrNullValue(maybeExportName));
self->initReservedSlot(ModuleRequestSlot, ObjectValue(*moduleRequest));
self->initReservedSlot(ImportNameSlot, StringOrNullValue(maybeImportName));
self->initReservedSlot(LocalNameSlot, StringOrNullValue(maybeLocalName));
self->initReservedSlot(LineNumberSlot, NumberValue(lineNumber));
self->initReservedSlot(ColumnNumberSlot, NumberValue(columnNumber));
return self;
}
///////////////////////////////////////////////////////////////////////////
// RequestedModuleObject
/* static */ const JSClass RequestedModuleObject::class_ = {
"RequestedModule",
JSCLASS_HAS_RESERVED_SLOTS(RequestedModuleObject::SlotCount)};
DEFINE_GETTER_FUNCTIONS(RequestedModuleObject, moduleRequest, ModuleRequestSlot)
DEFINE_GETTER_FUNCTIONS(RequestedModuleObject, lineNumber, LineNumberSlot)
DEFINE_GETTER_FUNCTIONS(RequestedModuleObject, columnNumber, ColumnNumberSlot)
DEFINE_UINT32_ACCESSOR_METHOD(RequestedModuleObject, lineNumber)
DEFINE_UINT32_ACCESSOR_METHOD(RequestedModuleObject, columnNumber)
ModuleRequestObject* RequestedModuleObject::moduleRequest() const {
Value value = getReservedSlot(ModuleRequestSlot);
return &value.toObject().as<ModuleRequestObject>();
}
/* static */
bool RequestedModuleObject::isInstance(HandleValue value) {
return value.isObject() && value.toObject().is<RequestedModuleObject>();
}
/* static */
bool GlobalObject::initRequestedModuleProto(JSContext* cx,
Handle<GlobalObject*> global) {
static const JSPropertySpec protoAccessors[] = {
JS_PSG("moduleRequest", RequestedModuleObject_moduleRequestGetter, 0),
JS_PSG("lineNumber", RequestedModuleObject_lineNumberGetter, 0),
JS_PSG("columnNumber", RequestedModuleObject_columnNumberGetter, 0),
JS_PS_END};
RootedObject proto(
cx, GlobalObject::createBlankPrototype<PlainObject>(cx, global));
if (!proto) {
return false;
}
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, nullptr)) {
return false;
}
global->initBuiltinProto(ProtoKind::RequestedModuleProto, proto);
return true;
}
/* static */
RequestedModuleObject* RequestedModuleObject::create(JSContext* cx,
HandleObject moduleRequest,
uint32_t lineNumber,
uint32_t columnNumber) {
RootedObject proto(
cx, GlobalObject::getOrCreateRequestedModulePrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
RequestedModuleObject* self =
NewObjectWithGivenProto<RequestedModuleObject>(cx, proto);
if (!self) {
return nullptr;
}
self->initReservedSlot(ModuleRequestSlot, ObjectValue(*moduleRequest));
self->initReservedSlot(LineNumberSlot, NumberValue(lineNumber));
self->initReservedSlot(ColumnNumberSlot, NumberValue(columnNumber));
return self;
}
///////////////////////////////////////////////////////////////////////////
// ModuleRequestObject
/* static */ const JSClass ModuleRequestObject::class_ = {
"ModuleRequest",
JSCLASS_HAS_RESERVED_SLOTS(ModuleRequestObject::SlotCount)};
DEFINE_GETTER_FUNCTIONS(ModuleRequestObject, specifier, SpecifierSlot)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ModuleRequestObject, specifier)
/* static */
bool ModuleRequestObject::isInstance(HandleValue value) {
return value.isObject() && value.toObject().is<ModuleRequestObject>();
}
/* static */
bool GlobalObject::initModuleRequestProto(JSContext* cx,
Handle<GlobalObject*> global) {
static const JSPropertySpec protoAccessors[] = {
JS_PSG("specifier", ModuleRequestObject_specifierGetter, 0), JS_PS_END};
RootedObject proto(
cx, GlobalObject::createBlankPrototype<PlainObject>(cx, global));
if (!proto) {
return false;
}
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, nullptr)) {
return false;
}
global->initBuiltinProto(ProtoKind::ModuleRequestProto, proto);
return true;
}
/* static */
ModuleRequestObject* ModuleRequestObject::create(JSContext* cx,
HandleAtom specifier) {
RootedObject proto(
cx, GlobalObject::getOrCreateModuleRequestPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
ModuleRequestObject* self =
NewObjectWithGivenProto<ModuleRequestObject>(cx, proto);
if (!self) {
return nullptr;
}
self->initReservedSlot(SpecifierSlot, StringOrNullValue(specifier));
return self;
}
///////////////////////////////////////////////////////////////////////////
// IndirectBindingMap
IndirectBindingMap::Binding::Binding(ModuleEnvironmentObject* environment,
jsid targetName, PropertyInfo prop)
: environment(environment),
#ifdef DEBUG
targetName(targetName),
#endif
prop(prop) {
}
void IndirectBindingMap::trace(JSTracer* trc) {
if (!map_) {
return;
}
for (Map::Enum e(*map_); !e.empty(); e.popFront()) {
Binding& b = e.front().value();
TraceEdge(trc, &b.environment, "module bindings environment");
#ifdef DEBUG
TraceEdge(trc, &b.targetName, "module bindings target name");
#endif
mozilla::DebugOnly<jsid> prev(e.front().key());
TraceEdge(trc, &e.front().mutableKey(), "module bindings binding name");
MOZ_ASSERT(e.front().key() == prev);
}
}
bool IndirectBindingMap::put(JSContext* cx, HandleId name,
HandleModuleEnvironmentObject environment,
HandleId targetName) {
// This object might have been allocated on the background parsing thread in
// different zone to the final module. Lazily allocate the map so we don't
// have to switch its zone when merging realms.
if (!map_) {
MOZ_ASSERT(!cx->zone()->createdForHelperThread());
map_.emplace(cx->zone());
}
mozilla::Maybe<PropertyInfo> prop = environment->lookup(cx, targetName);
MOZ_ASSERT(prop.isSome());
if (!map_->put(name, Binding(environment, targetName, *prop))) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
bool IndirectBindingMap::lookup(jsid name, ModuleEnvironmentObject** envOut,
mozilla::Maybe<PropertyInfo>* propOut) const {
if (!map_) {
return false;
}
auto ptr = map_->lookup(name);
if (!ptr) {
return false;
}
const Binding& binding = ptr->value();
MOZ_ASSERT(binding.environment);
MOZ_ASSERT(
binding.environment->containsPure(binding.targetName, binding.prop));
*envOut = binding.environment;
*propOut = mozilla::Some(binding.prop);
return true;
}
///////////////////////////////////////////////////////////////////////////
// ModuleNamespaceObject
/* static */
const ModuleNamespaceObject::ProxyHandler ModuleNamespaceObject::proxyHandler;
/* static */
bool ModuleNamespaceObject::isInstance(HandleValue value) {
return value.isObject() && value.toObject().is<ModuleNamespaceObject>();
}
/* static */
ModuleNamespaceObject* ModuleNamespaceObject::create(
JSContext* cx, HandleModuleObject module, HandleArrayObject exports,
UniquePtr<IndirectBindingMap> bindings) {
RootedValue priv(cx, ObjectValue(*module));
ProxyOptions options;
options.setLazyProto(true);
Rooted<UniquePtr<IndirectBindingMap>> rootedBindings(cx, std::move(bindings));
RootedObject object(
cx, NewProxyObject(cx, &proxyHandler, priv, nullptr, options));
if (!object) {
return nullptr;
}
SetProxyReservedSlot(object, ExportsSlot, ObjectValue(*exports));
SetProxyReservedSlot(object, BindingsSlot,
PrivateValue(rootedBindings.release()));
AddCellMemory(object, sizeof(IndirectBindingMap),
MemoryUse::ModuleBindingMap);
return &object->as<ModuleNamespaceObject>();
}
ModuleObject& ModuleNamespaceObject::module() {
return GetProxyPrivate(this).toObject().as<ModuleObject>();
}
ArrayObject& ModuleNamespaceObject::exports() {
return GetProxyReservedSlot(this, ExportsSlot).toObject().as<ArrayObject>();
}
IndirectBindingMap& ModuleNamespaceObject::bindings() {
Value value = GetProxyReservedSlot(this, BindingsSlot);
auto bindings = static_cast<IndirectBindingMap*>(value.toPrivate());
MOZ_ASSERT(bindings);
return *bindings;
}
bool ModuleNamespaceObject::hasBindings() const {
// Import bindings may not be present if we hit OOM in initialization.
return !GetProxyReservedSlot(this, BindingsSlot).isUndefined();
}
bool ModuleNamespaceObject::addBinding(JSContext* cx, HandleAtom exportedName,
HandleModuleObject targetModule,
HandleAtom targetName) {
RootedModuleEnvironmentObject environment(
cx, &targetModule->initialEnvironment());
RootedId exportedNameId(cx, AtomToId(exportedName));
RootedId targetNameId(cx, AtomToId(targetName));
return bindings().put(cx, exportedNameId, environment, targetNameId);
}
const char ModuleNamespaceObject::ProxyHandler::family = 0;
ModuleNamespaceObject::ProxyHandler::ProxyHandler()
: BaseProxyHandler(&family, false) {}
bool ModuleNamespaceObject::ProxyHandler::getPrototype(
JSContext* cx, HandleObject proxy, MutableHandleObject protop) const {
protop.set(nullptr);
return true;
}
bool ModuleNamespaceObject::ProxyHandler::setPrototype(
JSContext* cx, HandleObject proxy, HandleObject proto,
ObjectOpResult& result) const {
if (!proto) {
return result.succeed();
}
return result.failCantSetProto();
}
bool ModuleNamespaceObject::ProxyHandler::getPrototypeIfOrdinary(
JSContext* cx, HandleObject proxy, bool* isOrdinary,
MutableHandleObject protop) const {
*isOrdinary = false;
return true;
}
bool ModuleNamespaceObject::ProxyHandler::setImmutablePrototype(
JSContext* cx, HandleObject proxy, bool* succeeded) const {
*succeeded = true;
return true;
}
bool ModuleNamespaceObject::ProxyHandler::isExtensible(JSContext* cx,
HandleObject proxy,
bool* extensible) const {
*extensible = false;
return true;
}
bool ModuleNamespaceObject::ProxyHandler::preventExtensions(
JSContext* cx, HandleObject proxy, ObjectOpResult& result) const {
result.succeed();
return true;
}
bool ModuleNamespaceObject::ProxyHandler::getOwnPropertyDescriptor(
JSContext* cx, HandleObject proxy, HandleId id,
MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) const {
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
if (id.isSymbol()) {
if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
desc.set(mozilla::Some(
PropertyDescriptor::Data(StringValue(cx->names().Module))));
return true;
}
desc.reset();
return true;
}
const IndirectBindingMap& bindings = ns->bindings();
ModuleEnvironmentObject* env;
mozilla::Maybe<PropertyInfo> prop;
if (!bindings.lookup(id, &env, &prop)) {
// Not found.
desc.reset();
return true;
}
RootedValue value(cx, env->getSlot(prop->slot()));
if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
return false;
}
desc.set(mozilla::Some(PropertyDescriptor::Data(
value,
{JS::PropertyAttribute::Enumerable, JS::PropertyAttribute::Writable})));
return true;
}
static bool ValidatePropertyDescriptor(
JSContext* cx, Handle<PropertyDescriptor> desc, bool expectedWritable,
bool expectedEnumerable, bool expectedConfigurable,
HandleValue expectedValue, ObjectOpResult& result) {
if (desc.isAccessorDescriptor()) {
return result.fail(JSMSG_CANT_REDEFINE_PROP);
}
if (desc.hasWritable() && desc.writable() != expectedWritable) {
return result.fail(JSMSG_CANT_REDEFINE_PROP);
}
if (desc.hasEnumerable() && desc.enumerable() != expectedEnumerable) {
return result.fail(JSMSG_CANT_REDEFINE_PROP);
}
if (desc.hasConfigurable() && desc.configurable() != expectedConfigurable) {
return result.fail(JSMSG_CANT_REDEFINE_PROP);
}
if (desc.hasValue()) {
bool same;
if (!SameValue(cx, desc.value(), expectedValue, &same)) {
return false;
}
if (!same) {
return result.fail(JSMSG_CANT_REDEFINE_PROP);
}
}
return result.succeed();
}
bool ModuleNamespaceObject::ProxyHandler::defineProperty(
JSContext* cx, HandleObject proxy, HandleId id,
Handle<PropertyDescriptor> desc, ObjectOpResult& result) const {
if (id.isSymbol()) {
if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
RootedValue value(cx, StringValue(cx->names().Module));
return ValidatePropertyDescriptor(cx, desc, false, false, false, value,
result);
}
return result.fail(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE);
}
const IndirectBindingMap& bindings =
proxy->as<ModuleNamespaceObject>().bindings();
ModuleEnvironmentObject* env;
mozilla::Maybe<PropertyInfo> prop;
if (!bindings.lookup(id, &env, &prop)) {
return result.fail(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE);
}
RootedValue value(cx, env->getSlot(prop->slot()));
if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
return false;
}
return ValidatePropertyDescriptor(cx, desc, true, true, false, value, result);
}
bool ModuleNamespaceObject::ProxyHandler::has(JSContext* cx, HandleObject proxy,
HandleId id, bool* bp) const {
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
if (id.isSymbol()) {
*bp = id.isWellKnownSymbol(JS::SymbolCode::toStringTag);
return true;
}
*bp = ns->bindings().has(id);
return true;
}
bool ModuleNamespaceObject::ProxyHandler::get(JSContext* cx, HandleObject proxy,
HandleValue receiver, HandleId id,
MutableHandleValue vp) const {
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
if (id.isSymbol()) {
if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
vp.setString(cx->names().Module);
return true;
}
vp.setUndefined();
return true;
}
ModuleEnvironmentObject* env;
mozilla::Maybe<PropertyInfo> prop;
if (!ns->bindings().lookup(id, &env, &prop)) {
vp.setUndefined();
return true;
}
RootedValue value(cx, env->getSlot(prop->slot()));
if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
return false;
}
vp.set(value);
return true;
}
bool ModuleNamespaceObject::ProxyHandler::set(JSContext* cx, HandleObject proxy,
HandleId id, HandleValue v,
HandleValue receiver,
ObjectOpResult& result) const {
return result.failReadOnly();
}
bool ModuleNamespaceObject::ProxyHandler::delete_(
JSContext* cx, HandleObject proxy, HandleId id,
ObjectOpResult& result) const {
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
if (id.isSymbol()) {
if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
return result.failCantDelete();
}
return result.succeed();
}
if (ns->bindings().has(id)) {
return result.failCantDelete();
}
return result.succeed();
}
bool ModuleNamespaceObject::ProxyHandler::ownPropertyKeys(
JSContext* cx, HandleObject proxy, MutableHandleIdVector props) const {
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
Rooted<ArrayObject*> exports(cx, &ns->exports());
uint32_t count = exports->length();
if (!props.reserve(props.length() + count + 1)) {
return false;
}
Rooted<ValueVector> names(cx, ValueVector(cx));
if (!names.resize(count) || !GetElements(cx, exports, count, names.begin())) {
return false;
}
for (uint32_t i = 0; i < count; i++) {
props.infallibleAppend(AtomToId(&names[i].toString()->asAtom()));
}
props.infallibleAppend(SYMBOL_TO_JSID(cx->wellKnownSymbols().toStringTag));
return true;
}
void ModuleNamespaceObject::ProxyHandler::trace(JSTracer* trc,
JSObject* proxy) const {
auto& self = proxy->as<ModuleNamespaceObject>();
if (self.hasBindings()) {
self.bindings().trace(trc);
}
}
void ModuleNamespaceObject::ProxyHandler::finalize(JSFreeOp* fop,
JSObject* proxy) const {
auto& self = proxy->as<ModuleNamespaceObject>();
if (self.hasBindings()) {
fop->delete_(proxy, &self.bindings(), MemoryUse::ModuleBindingMap);
}
}
///////////////////////////////////////////////////////////////////////////
// ModuleObject
/* static */ const JSClassOps ModuleObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
ModuleObject::finalize, // finalize
nullptr, // call
nullptr, // hasInstance
nullptr, // construct
ModuleObject::trace, // trace
};
/* static */ const JSClass ModuleObject::class_ = {
"Module",
JSCLASS_HAS_RESERVED_SLOTS(ModuleObject::SlotCount) |
JSCLASS_BACKGROUND_FINALIZE,
&ModuleObject::classOps_};
#define DEFINE_ARRAY_SLOT_ACCESSOR(cls, name, slot) \
ArrayObject& cls::name() const { \
return getReservedSlot(cls::slot).toObject().as<ArrayObject>(); \
}
DEFINE_ARRAY_SLOT_ACCESSOR(ModuleObject, requestedModules, RequestedModulesSlot)
DEFINE_ARRAY_SLOT_ACCESSOR(ModuleObject, importEntries, ImportEntriesSlot)
DEFINE_ARRAY_SLOT_ACCESSOR(ModuleObject, localExportEntries,
LocalExportEntriesSlot)
DEFINE_ARRAY_SLOT_ACCESSOR(ModuleObject, indirectExportEntries,
IndirectExportEntriesSlot)
DEFINE_ARRAY_SLOT_ACCESSOR(ModuleObject, starExportEntries,
StarExportEntriesSlot)
/* static */
bool ModuleObject::isInstance(HandleValue value) {
return value.isObject() && value.toObject().is<ModuleObject>();
}
// Declared as static function instead of ModuleObject method in order to
// avoid recursive #include dependency between frontend and VM.
static frontend::FunctionDeclarationVector* GetFunctionDeclarations(
ModuleObject* module) {
Value value = module->getReservedSlot(ModuleObject::FunctionDeclarationsSlot);
if (value.isUndefined()) {
return nullptr;
}
return static_cast<frontend::FunctionDeclarationVector*>(value.toPrivate());
}
static void InitFunctionDeclarations(
ModuleObject* module, frontend::FunctionDeclarationVector&& decls) {
*GetFunctionDeclarations(module) = std::move(decls);
}
/* static */
ModuleObject* ModuleObject::create(JSContext* cx) {
RootedObject proto(
cx, GlobalObject::getOrCreateModulePrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
RootedModuleObject self(cx, NewObjectWithGivenProto<ModuleObject>(cx, proto));
if (!self) {
return nullptr;
}
IndirectBindingMap* bindings = cx->new_<IndirectBindingMap>();
if (!bindings) {
return nullptr;
}
InitReservedSlot(self, ImportBindingsSlot, bindings,
MemoryUse::ModuleBindingMap);
frontend::FunctionDeclarationVector* funDecls =
cx->new_<frontend::FunctionDeclarationVector>();
if (!funDecls) {
return nullptr;
}
self->initReservedSlot(FunctionDeclarationsSlot, PrivateValue(funDecls));
return self;
}
/* static */
void ModuleObject::finalize(JSFreeOp* fop, JSObject* obj) {
MOZ_ASSERT(fop->maybeOnHelperThread());
ModuleObject* self = &obj->as<ModuleObject>();
if (self->hasImportBindings()) {
fop->delete_(obj, &self->importBindings(), MemoryUse::ModuleBindingMap);
}
if (frontend::FunctionDeclarationVector* funDecls =
GetFunctionDeclarations(self)) {
// Not tracked as these may move between zones on merge.
fop->deleteUntracked(funDecls);
}
}
ModuleEnvironmentObject& ModuleObject::initialEnvironment() const {
Value value = getReservedSlot(EnvironmentSlot);
return value.toObject().as<ModuleEnvironmentObject>();
}
ModuleEnvironmentObject* ModuleObject::environment() const {
// Note that this it's valid to call this even if there was an error
// evaluating the module.
// According to the spec the environment record is created during
// instantiation, but we create it earlier than that.
if (status() < MODULE_STATUS_LINKED) {
return nullptr;
}
return &initialEnvironment();
}
bool ModuleObject::hasImportBindings() const {
// Import bindings may not be present if we hit OOM in initialization.
return !getReservedSlot(ImportBindingsSlot).isUndefined();
}
IndirectBindingMap& ModuleObject::importBindings() {
return *static_cast<IndirectBindingMap*>(
getReservedSlot(ImportBindingsSlot).toPrivate());
}
ModuleNamespaceObject* ModuleObject::namespace_() {
Value value = getReservedSlot(NamespaceSlot);
if (value.isUndefined()) {
return nullptr;
}
return &value.toObject().as<ModuleNamespaceObject>();
}
ScriptSourceObject* ModuleObject::scriptSourceObject() const {
return &getReservedSlot(ScriptSourceObjectSlot)
.toObject()
.as<ScriptSourceObject>();
}
bool ModuleObject::initAsyncSlots(JSContext* cx, bool isAsync,
HandleObject asyncParentModulesList) {
initReservedSlot(AsyncSlot, BooleanValue(isAsync));
initReservedSlot(AsyncParentModulesSlot,
ObjectValue(*asyncParentModulesList));
return true;
}
constexpr uint32_t ASYNC_EVALUATING_POST_ORDER_FALSE = 0;
constexpr uint32_t ASYNC_EVALUATING_POST_ORDER_INIT = 1;
uint32_t AsyncPostOrder = ASYNC_EVALUATING_POST_ORDER_INIT;
uint32_t nextPostOrder() {
uint32_t ordinal = AsyncPostOrder;
MOZ_ASSERT(AsyncPostOrder < MAX_UINT32);
AsyncPostOrder++;
return ordinal;
}
bool ModuleObject::initAsyncEvaluatingSlot() {
initReservedSlot(AsyncEvaluatingPostOrderSlot,
PrivateUint32Value(nextPostOrder()));
return true;
}
void ModuleObject::initScriptSlots(HandleScript script) {
MOZ_ASSERT(script);
initReservedSlot(ScriptSlot, PrivateGCThingValue(script));
initReservedSlot(ScriptSourceObjectSlot,
ObjectValue(*script->sourceObject()));
}
void ModuleObject::setInitialEnvironment(
HandleModuleEnvironmentObject initialEnvironment) {
initReservedSlot(EnvironmentSlot, ObjectValue(*initialEnvironment));
}
void ModuleObject::initStatusSlot() {
initReservedSlot(StatusSlot, Int32Value(MODULE_STATUS_UNLINKED));
}
void ModuleObject::initImportExportData(HandleArrayObject requestedModules,
HandleArrayObject importEntries,
HandleArrayObject localExportEntries,
HandleArrayObject indirectExportEntries,
HandleArrayObject starExportEntries) {
initReservedSlot(RequestedModulesSlot, ObjectValue(*requestedModules));
initReservedSlot(ImportEntriesSlot, ObjectValue(*importEntries));
initReservedSlot(LocalExportEntriesSlot, ObjectValue(*localExportEntries));
initReservedSlot(IndirectExportEntriesSlot,
ObjectValue(*indirectExportEntries));
initReservedSlot(StarExportEntriesSlot, ObjectValue(*starExportEntries));
}
static bool FreezeObjectProperty(JSContext* cx, HandleNativeObject obj,
uint32_t slot) {
RootedObject property(cx, &obj->getSlot(slot).toObject());
return FreezeObject(cx, property);
}
/* static */
bool ModuleObject::Freeze(JSContext* cx, HandleModuleObject self) {
return FreezeObjectProperty(cx, self, RequestedModulesSlot) &&
FreezeObjectProperty(cx, self, ImportEntriesSlot) &&
FreezeObjectProperty(cx, self, LocalExportEntriesSlot) &&
FreezeObjectProperty(cx, self, IndirectExportEntriesSlot) &&
FreezeObjectProperty(cx, self, StarExportEntriesSlot) &&
FreezeObject(cx, self);
}
#ifdef DEBUG
static inline bool CheckObjectFrozen(JSContext* cx, HandleObject obj,
bool* result) {
return TestIntegrityLevel(cx, obj, IntegrityLevel::Frozen, result);
}
static inline bool CheckObjectPropertyFrozen(JSContext* cx,
HandleNativeObject obj,
uint32_t slot, bool* result) {
RootedObject property(cx, &obj->getSlot(slot).toObject());
return CheckObjectFrozen(cx, property, result);
}
/* static */ inline bool ModuleObject::AssertFrozen(JSContext* cx,
HandleModuleObject self) {
static const mozilla::EnumSet<ModuleSlot> slotsToCheck = {
RequestedModulesSlot, ImportEntriesSlot, LocalExportEntriesSlot,
IndirectExportEntriesSlot, StarExportEntriesSlot};
bool frozen = false;
for (auto slot : slotsToCheck) {
if (!CheckObjectPropertyFrozen(cx, self, slot, &frozen)) {
return false;
}
MOZ_ASSERT(frozen);
}
if (!CheckObjectFrozen(cx, self, &frozen)) {
return false;
}
MOZ_ASSERT(frozen);
return true;
}
#endif
inline static void AssertModuleScopesMatch(ModuleObject* module) {
MOZ_ASSERT(module->enclosingScope()->is<GlobalScope>());
MOZ_ASSERT(IsGlobalLexicalEnvironment(
&module->initialEnvironment().enclosingEnvironment()));
}
void ModuleObject::fixEnvironmentsAfterRealmMerge() {
AssertModuleScopesMatch(this);
initialEnvironment().fixEnclosingEnvironmentAfterRealmMerge(
script()->global());
AssertModuleScopesMatch(this);
}
JSScript* ModuleObject::maybeScript() const {
Value value = getReservedSlot(ScriptSlot);
if (value.isUndefined()) {
return nullptr;
}
BaseScript* script = value.toGCThing()->as<BaseScript>();
MOZ_ASSERT(script->hasBytecode(),
"Module scripts should always have bytecode");
return script->asJSScript();
}
JSScript* ModuleObject::script() const {
JSScript* ptr = maybeScript();
MOZ_RELEASE_ASSERT(ptr);
return ptr;
}
static inline void AssertValidModuleStatus(ModuleStatus status) {
MOZ_ASSERT(status >= MODULE_STATUS_UNLINKED &&
status <= MODULE_STATUS_EVALUATED_ERROR);
}
ModuleStatus ModuleObject::status() const {
ModuleStatus status = getReservedSlot(StatusSlot).toInt32();
AssertValidModuleStatus(status);
return status;
}
bool ModuleObject::isAsync() const {
return getReservedSlot(AsyncSlot).toBoolean();
}
bool ModuleObject::isAsyncEvaluating() const {
if (getReservedSlot(AsyncEvaluatingPostOrderSlot).isUndefined()) {
return false;
}
return getReservedSlot(AsyncEvaluatingPostOrderSlot).toPrivateUint32() !=
ASYNC_EVALUATING_POST_ORDER_FALSE;
}
void ModuleObject::setAsyncEvaluatingFalse() {
if (AsyncPostOrder == getAsyncEvaluatingPostOrder()) {
// If this condition is true, we can reset postOrder.
// Graph is not re-entrant and any future modules will be independent from
// this one.
AsyncPostOrder = ASYNC_EVALUATING_POST_ORDER_INIT;
}
return setReservedSlot(AsyncEvaluatingPostOrderSlot,
PrivateUint32Value(ASYNC_EVALUATING_POST_ORDER_FALSE));
}
uint32_t ModuleObject::dfsIndex() const {
return getReservedSlot(DFSIndexSlot).toInt32();
}
uint32_t ModuleObject::dfsAncestorIndex() const {
return getReservedSlot(DFSAncestorIndexSlot).toInt32();
}
JSObject* ModuleObject::topLevelCapability() const {
Value capability = getReservedSlot(TopLevelCapabilitySlot);
MOZ_RELEASE_ASSERT(capability.isObject());
return &capability.toObject();
}
PromiseObject* ModuleObject::createTopLevelCapability(
JSContext* cx, HandleModuleObject module) {
MOZ_ASSERT(module->getReservedSlot(TopLevelCapabilitySlot).isUndefined());
Rooted<PromiseObject*> resultPromise(cx, CreatePromiseObjectForAsync(cx));
if (!resultPromise) {
return nullptr;
}
module->setInitialTopLevelCapability(resultPromise);
return resultPromise;
}
void ModuleObject::setInitialTopLevelCapability(HandleObject promiseObj) {
initReservedSlot(TopLevelCapabilitySlot, ObjectValue(*promiseObj));
}
inline ListObject* ModuleObject::asyncParentModules() const {
return &getReservedSlot(AsyncParentModulesSlot).toObject().as<ListObject>();
}
bool ModuleObject::appendAsyncParentModule(JSContext* cx,
HandleModuleObject self,
HandleModuleObject parent) {
Rooted<Value> parentValue(cx, ObjectValue(*parent));
return self->asyncParentModules()->append(cx, parentValue);
}
uint32_t ModuleObject::pendingAsyncDependencies() const {
return getReservedSlot(PendingAsyncDependenciesSlot).toInt32();
}
uint32_t ModuleObject::getAsyncEvaluatingPostOrder() const {
MOZ_ASSERT(isAsyncEvaluating());
return getReservedSlot(AsyncEvaluatingPostOrderSlot).toPrivateUint32();
}
void ModuleObject::setPendingAsyncDependencies(uint32_t newValue) {
return setReservedSlot(PendingAsyncDependenciesSlot, NumberValue(newValue));
}
void ModuleObject::setCycleRoot(ModuleObject* cycleRoot) {
return setReservedSlot(CycleRootSlot, ObjectValue(*cycleRoot));
}
ModuleObject* ModuleObject::getCycleRoot() const {
Value cycleRoot = getReservedSlot(CycleRootSlot);
MOZ_RELEASE_ASSERT(cycleRoot.isObject());
return &cycleRoot.toObject().as<ModuleObject>();
}
bool ModuleObject::hasTopLevelCapability() const {
return !getReservedSlot(TopLevelCapabilitySlot).isUndefined();
}
bool ModuleObject::hadEvaluationError() const {
return status() == MODULE_STATUS_EVALUATED_ERROR;
}
void ModuleObject::setEvaluationError(HandleValue newValue) {
setReservedSlot(StatusSlot, Int32Value(MODULE_STATUS_EVALUATED_ERROR));
return setReservedSlot(EvaluationErrorSlot, newValue);
}
Value ModuleObject::evaluationError() const {
MOZ_ASSERT(hadEvaluationError());
return getReservedSlot(EvaluationErrorSlot);
}
JSObject* ModuleObject::metaObject() const {
Value value = getReservedSlot(MetaObjectSlot);
if (value.isObject()) {
return &value.toObject();
}
MOZ_ASSERT(value.isUndefined());
return nullptr;
}
void ModuleObject::setMetaObject(JSObject* obj) {
MOZ_ASSERT(obj);
MOZ_ASSERT(!metaObject());
setReservedSlot(MetaObjectSlot, ObjectValue(*obj));
}
Scope* ModuleObject::enclosingScope() const {
return script()->enclosingScope();
}
/* static */
void ModuleObject::trace(JSTracer* trc, JSObject* obj) {
ModuleObject& module = obj->as<ModuleObject>();
if (module.hasImportBindings()) {
module.importBindings().trace(trc);
}
}
/* static */
bool ModuleObject::instantiateFunctionDeclarations(JSContext* cx,
HandleModuleObject self) {
#ifdef DEBUG
MOZ_ASSERT(self->status() == MODULE_STATUS_LINKING);
if (!AssertFrozen(cx, self)) {
return false;
}
#endif
// |self| initially manages this vector.
frontend::FunctionDeclarationVector* funDecls =
GetFunctionDeclarations(self.get());
if (!funDecls) {
JS_ReportErrorASCII(
cx, "Module function declarations have already been instantiated");
return false;
}
RootedModuleEnvironmentObject env(cx, &self->initialEnvironment());
RootedObject obj(cx);
RootedValue value(cx);
RootedFunction fun(cx);
RootedPropertyName name(cx);
for (GCThingIndex funIndex : *funDecls) {
fun.set(self->script()->getFunction(funIndex));
obj = Lambda(cx, fun, env);
if (!obj) {
return false;
}
name = fun->explicitName()->asPropertyName();
value = ObjectValue(*obj);
if (!SetProperty(cx, env, name, value)) {
return false;
}
}
// Transfer ownership of the vector from |self|, then free the vector, once
// its contents are no longer needed.
self->setReservedSlot(FunctionDeclarationsSlot, UndefinedValue());
js_delete(funDecls);
return true;
}
/* static */
bool ModuleObject::execute(JSContext* cx, HandleModuleObject self,
MutableHandleValue rval) {
#ifdef DEBUG
MOZ_ASSERT(self->status() == MODULE_STATUS_EVALUATING ||
self->status() == MODULE_STATUS_EVALUATED);
if (!AssertFrozen(cx, self)) {
return false;
}
#endif
RootedScript script(cx, self->script());
// The top-level script if a module is only ever executed once. Clear the
// reference at exit to prevent us keeping this alive unnecessarily. This is
// kept while executing so it is available to the debugger.
auto guardA = mozilla::MakeScopeExit(
[&] { self->setReservedSlot(ScriptSlot, UndefinedValue()); });
RootedModuleEnvironmentObject env(cx, self->environment());
if (!env) {
JS_ReportErrorASCII(cx,
"Module declarations have not yet been instantiated");
return false;
}
return Execute(cx, script, env, rval);
}
/* static */
ModuleNamespaceObject* ModuleObject::createNamespace(JSContext* cx,
HandleModuleObject self,
HandleObject exports) {
MOZ_ASSERT(!self->namespace_());
MOZ_ASSERT(exports->is<ArrayObject>());
auto bindings = cx->make_unique<IndirectBindingMap>();
if (!bindings) {
return nullptr;
}
auto ns = ModuleNamespaceObject::create(cx, self, exports.as<ArrayObject>(),
std::move(bindings));
if (!ns) {
return nullptr;
}
self->initReservedSlot(NamespaceSlot, ObjectValue(*ns));
return ns;
}
/* static */
bool ModuleObject::createEnvironment(JSContext* cx, HandleModuleObject self) {
RootedModuleEnvironmentObject env(cx,
ModuleEnvironmentObject::create(cx, self));
if (!env) {
return false;
}
self->setInitialEnvironment(env);
return true;
}
static bool InvokeSelfHostedMethod(JSContext* cx, HandleModuleObject self,
HandlePropertyName name,
MutableHandleValue rval) {
RootedValue thisv(cx, ObjectValue(*self));
FixedInvokeArgs<0> args(cx);
return CallSelfHostedFunction(cx, name, thisv, args, rval);
}
/* static */
bool ModuleObject::Instantiate(JSContext* cx, HandleModuleObject self) {
RootedValue ignored(cx);
return InvokeSelfHostedMethod(cx, self, cx->names().ModuleInstantiate,
&ignored);
}
/* static */
bool ModuleObject::Evaluate(JSContext* cx, HandleModuleObject self,
MutableHandleValue rval) {
return InvokeSelfHostedMethod(cx, self, cx->names().ModuleEvaluate, rval);
}
/* static */
ModuleNamespaceObject* ModuleObject::GetOrCreateModuleNamespace(
JSContext* cx, HandleModuleObject self) {
FixedInvokeArgs<1> args(cx);
args[0].setObject(*self);
RootedValue result(cx);
if (!CallSelfHostedFunction(cx, cx->names().GetModuleNamespace,
UndefinedHandleValue, args, &result)) {
return nullptr;
}
return &result.toObject().as<ModuleNamespaceObject>();
}
DEFINE_GETTER_FUNCTIONS(ModuleObject, namespace_, NamespaceSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, status, StatusSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, evaluationError, EvaluationErrorSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, requestedModules, RequestedModulesSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, importEntries, ImportEntriesSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, localExportEntries,
LocalExportEntriesSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, indirectExportEntries,
IndirectExportEntriesSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, starExportEntries, StarExportEntriesSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, dfsIndex, DFSIndexSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, dfsAncestorIndex, DFSAncestorIndexSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, async, AsyncSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, topLevelCapability,
TopLevelCapabilitySlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, asyncEvaluatingPostOrder,
AsyncEvaluatingPostOrderSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, asyncParentModules,
AsyncParentModulesSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, pendingAsyncDependencies,
PendingAsyncDependenciesSlot)
/* static */
bool GlobalObject::initModuleProto(JSContext* cx,
Handle<GlobalObject*> global) {
static const JSPropertySpec protoAccessors[] = {
JS_PSG("namespace", ModuleObject_namespace_Getter, 0),
JS_PSG("status", ModuleObject_statusGetter, 0),
JS_PSG("evaluationError", ModuleObject_evaluationErrorGetter, 0),
JS_PSG("requestedModules", ModuleObject_requestedModulesGetter, 0),
JS_PSG("importEntries", ModuleObject_importEntriesGetter, 0),
JS_PSG("localExportEntries", ModuleObject_localExportEntriesGetter, 0),
JS_PSG("indirectExportEntries", ModuleObject_indirectExportEntriesGetter,
0),
JS_PSG("starExportEntries", ModuleObject_starExportEntriesGetter, 0),
JS_PSG("dfsIndex", ModuleObject_dfsIndexGetter, 0),
JS_PSG("dfsAncestorIndex", ModuleObject_dfsAncestorIndexGetter, 0),
JS_PSG("async", ModuleObject_asyncGetter, 0),
JS_PSG("topLevelCapability", ModuleObject_topLevelCapabilityGetter, 0),
JS_PSG("asyncEvaluatingPostOrder",
ModuleObject_asyncEvaluatingPostOrderGetter, 0),
JS_PSG("asyncParentModules", ModuleObject_asyncParentModulesGetter, 0),
JS_PSG("pendingAsyncDependencies",
ModuleObject_pendingAsyncDependenciesGetter, 0),
JS_PS_END};
static const JSFunctionSpec protoFunctions[] = {
JS_SELF_HOSTED_FN("getExportedNames", "ModuleGetExportedNames", 1, 0),
JS_SELF_HOSTED_FN("resolveExport", "ModuleResolveExport", 2, 0),
JS_SELF_HOSTED_FN("declarationInstantiation", "ModuleInstantiate", 0, 0),
JS_SELF_HOSTED_FN("evaluation", "ModuleEvaluate", 0, 0),
JS_SELF_HOSTED_FN("gatherAsyncParentCompletions",
"GatherAsyncParentCompletions", 2, 0),
JS_FS_END};
RootedObject proto(
cx, GlobalObject::createBlankPrototype<PlainObject>(cx, global));
if (!proto) {
return false;
}
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors,
protoFunctions)) {
return false;
}
global->initBuiltinProto(ProtoKind::ModuleProto, proto);
return true;
}
#undef DEFINE_GETTER_FUNCTIONS
#undef DEFINE_STRING_ACCESSOR_METHOD
#undef DEFINE_ARRAY_SLOT_ACCESSOR
///////////////////////////////////////////////////////////////////////////
// ModuleBuilder