Files
palemoon27/js/src/builtin/ModuleObject.cpp
T
roytam1 4696208ad8 import changes from `dev' branch of rmottola/Arctic-Fox:- Bug 1258966 - Remove unnecessary null-checks of MediaDecoderStateMachine::mReader. r=bechen. (0513c82214)
- Bug 1258627 - always schedule next cycle so MDSM has a chance to leave buffering state. r=cpearce. (49fb876b9e)
- Bug 1258271 - Remove arguments from MediaDecoderStateMachine::HaveEnoughDecodedAudio(). r=bechen. (e8610f7f76)
- Bug 1252753. Part 1 - remove calls to PushFront(). r=kinetik. (7abe1bfb0f)
- Bug 1252753. Part 2 - remove MediaDecoderStateMachine::PushFront(). r=kinetik. (1a153a5b00)
- Bug 1230527: P1. Ensure seeked event is fired prior loadeddata. r=jwwang (aa9eef9fd3)
- Bug 1230527: P2. Add mochitest. r=jwwang (6e9f920781)
- Bug 1252767 - Remove MediaDecoderStateMachine::mPendingSeek. r=cpearce. (e5d69a191d)
- Bug 1255268 - Replace SeekJob::Steal() with move semantics. r=cpearce. (6294c01ba7)
- Bug 1253490 - fix the calculation of decodeTime. r=jya. (b8f3c8801a)
- Bug 1252343. Part 1 - make mReader const. r=bechen. (33a8b6a4ad)
- Bug 1252343. Part 2 - remove null checks for mReader which is const and never null. r=bechen. (5cd068aafc)
- Bug 1250054. Part 2 - employ MediaDecoderReaderWrapper for MDSM and remove code about adjusting start time. r=jya. (b5a954d8d8)
- Bug 1252341 - No need to reset mReader in ~MediaDecoderStateMachine() because the destructor will do that. r=bechen. (cd0639e366)
- Bug 1264784 - part 2 - remove unused virtual methods from nsIFrame; r=dholbert (5d52314a79)
- Bug 1264784 - part 3 - make nsIFrame::GetNearestWidget methods non-virtual; r=dholbert (67b0987de6)
- Bug 1053986 - Rename nsIFrame::IsBoxFrame to IsXULBoxFrame. r=dholbert (394613f49f)
- Bug 1256040 - Fix some nsGridContainerFrame.h/cpp compile errors in non-unified build. r=dholbert (b49241e3b1)
- Bug 1264607 - Treat track size <percentage> values as 'auto' when the grid container size is indefinite. r=dholbert (3895d4d922)
- Bug 1260614 - Cleanup grid item iterator Reset() calls. r=dholbert (e6760e1def)
- Bug 1256040 - Bustage fix. r=me (d67b9c0de5)
- Bug 1233191 part 1 - Implement sanity checks on the flex/grid container child frame list. Remove the anon grid item sanity checks that the frame constructor now does instead. r=dholbert (d9412bb043)
- Bug 1233191 part 2 - Remove anon flex item sanity checks that the frame constructor now does instead. r=dholbert (564184ea6d)
- Bug 1233191 part 3 - crashtest. (c6b6bb4fca)
- Bug 1187846 Stack layout doesn't honour min/max sizes for positioned elements r=Enn (8080e9db71)
- Bug 1053986 - Rename nsIFrame::GetMinSize to GetXULMinSize, and related methods. r=dholbert (fa1722982e)
- Bug 1000870 - Add some features in testing system. r=smaug (f7b4b8916f)
- Bug 1053986 - Rename nsIFrame::GetPrefSize to GetXULPrefSize, and related methods. r=dholbert (9f7e8de26e)
- Bug 1053986 - Rename nsIFrame::GetMaxSize to GetXULMaxSize, and related methods. r=dholbert (a632913886)
- Bug 1053986 - Rename nsIFrame::GetMinSizeForScrollArea to GetXULMinSizeForScrollArea. r=dholbert (ac520afe6f)
- Bug 1053986 - Rename nsIFrame::GetOrdinal to GetXULOrdinal. r=dholbert (e5f7342d03)
- Bug 1053986 - Rename nsIFrame::GetFlex to GetXULFlex. r=dholbert (aadf567a8c)
- Bug 1053986 - Rename nsIFrame::GetBoxAscent to GetXULBoxAscent. r=dholbert (4e729c60ea)
- Bug 1053986 - Rename nsFrame.cpp static method IsBoxWrapped to IsXULBoxWrapped. r=dholbert (009b251df0)
- Bug 1053986 - Rename nsIFrame::IsCollapsed to IsXULCollapsed, and related methods. r=dholbert (eec509e378)
- Bug 1168212 - Ensure popups have a minimum width of their preferred size r=Enn (657c8da6fa)
- Bug 1053986 - Rename nsIFrame::SetBounds to SetXULBounds. r=dholbert (304ff47c6c)
- Bug 1088637 - check we get the right transition event, r=Enn (b0da4a67f6)
- Bug 1053986 - Rename nsIFrame::Layout to XULLayout, and related methods with the same name. r=dholbert (66ef396b10)
- Bug 1053986 - Rename nsIFrame::GetBorderAndPadding to GetXULBorderAndPadding. r=dholbert (588f824000)
- Bug 1053986 - Rename nsIFrame::GetBorder to GetXULBorder. r=dholbert (f91ae3fc59)
- Bug 1053986 - Rename nsIFrame::GetPadding to GetXULPadding. r=dholbert (797e21e6af)
- Bug 1053986 - Rename nsIFrame::GetMargin to GetXULMargin. r=dholbert (05dc0235f2)
- Bug 1053986 - Rename nsIFrame::SetLayoutManager to SetXULLayoutManager. r=dholbert (0cb22c411d)
- Bug 1053986 - Rename nsIFrame::GetLayoutManager to GetXULLayoutManager. r=dholbert (6a03e1de2c)
- Bug 852754 - Part 1: Share the code for limiting scale factors to all image types. r=mstange (098a083d1a)
- Bug 852754 - Part 2: Share the implementation of GetContainer. r=mstange (063b7683dd)
- Bug 852754 - Part 3: Share the implementation of ConfigureLayer. r=mstange (ffd2d99802)
- Bug 1256999 - Pass the right context to new channels for image loads. r=bz r=seth (275cebb231)
- Bug 1194337 - Context menu positioned incorrectly on OSX. r=enn (1e429a9d3c)
- Bug 1216284 - Tooltips do not flip correctly on OSX. r=enndeakin (c08931768b)
- Bug 1053986 - Rename nsIFrame::GetClientRect to GetXULClientRect. r=dholbert (c06a121de6)
- Bug 1053986 - Rename nsIFrame::GetVAlign to GetXULVAlign. r=dholbert (a923d76c4b)
- Bug 1053986 - Rename nsBox::GetChildBox to GetChildXULBox. r=dholbert (ebe12c77f1)
- Bug 1053986 - Rename nsIFrame::GetHAlign to GetXULHAlign. r=dholbert (dbd501e2bd)
- Bug 1053986 - Rename nsBox::GetNextBox to GetNextXULBox. r=dholbert (1cd5fa1ce3)
- Bug 1053986 - Rename nsBox::GetParentBox to GetParentXULBox. r=dholbert (2beaeb6bdd)
- Bug 1171696 - Don't resize scrollbar thumb when updating its position. r=mstange (5b51241744)
- Bug 1053986 - Rename nsIFrame::IsHorizontal to IsXULHorizontal, and related methods. r=dholbert (7d8e4142e5)
- Bug 1053986 - Rename nsIFrame::IsNormalDirection to IsXULNormalDirection. r=dholbert (7d9686b089)
- Bug 1053986 - Rename nsIFrame::Redraw to XULRedraw. r=dholbert (20da19c2ce)
- Bug 1053986 - Rename nsIFrame::RelayoutChildAtOrdinal to XULRelayoutChildAtOrdinal. r=dholbert (e5c4eb2b9f)
- Bug 1053986 - Rename nsIFrame::SetDebug to SetXULDebug. r=dholbert (438c3a1109)
- Bug 1053986 - Rename nsIFrame::GetDebug to GetXULDebug. r=dholbert (00e0ca19e4)
- Bug 1053986 - Rename nsIFrame::DumpBox to XULDumpBox. r=dholbert (30edc21d8e)
- Bug 1053986 - Rename nsIFrame::AddCSSPrefSize, AddCSSMinSize, AddCSSMaxSize, and AddCSSFlex by replacing CSS with XUL. r=dholbert (4e79b90b1f)
- Bug 1053986 - Fix ordering of methods in nsIFrame.h r=dholbert (fb08aa035f)
- Bug 1053986 - Rename nsBox::BeginLayout to BeginXULLayout. r=dholbert (595cb70526)
- Bug 1053986 - Rename nsBox::EndLayout to EndXULLayout. r=dholbert (13f98a84a0)
- Bug 1213895: Part 1 - Correctly support crop="none" in XUL labels. r=neil (053e0c8414)
- Bug 1053986 - Rename nsBox::DoLayout to DoXULLayout. r=dholbert (40ef0ece53)
- Bug 1144619 - Variable 'nextX' is created in the wrong scope. r=dbaron (7893ccb301)
- Bug 1172011 - Remove unneeded 'spaceLeft' declaration from nsSplitterFrame.cpp. r=froydnj (7ef937e283)
- Bug 1192376: Make nsImageBoxFrame check whether image size is available before trying to paint an image. r=seth (2db203eb3b)
- Bug 1240533 - Parameters to ScreenForRect need to be passed as desktop pixels, not device pixels. r=emk (d49b532344)
- Bug 1212658 - Remove needless IsCallerChrome check in nsMenuPopupFrame. r=bz (bdf0d16a49)
- Bug 374471 Make the noautohide attribute live where supported r=enndeakin (f696b4d174)
- Bug 1200870, allow -1 as a value to popup.moveTo, r=tn (10e05d4240)
- Bug 1182856 - Part 1: Add StopTransitionsForElement. r=heycam (1c0ac374c4)
- Bug 1182856 - Part 2: Let AnimationsWithDestroyFrame destroy transitions. r=heycam (7820f7b1e5)
- Bug 1182856 - Part 3: Cancel transitions for destroy frames. r=heycam (439fb07545)
- Bug 1157936 - Put the correct ratio on the scrollbar layer. r=tn (a64f35b9ea)
- Bug 1238137 - Telemetry pings for main thread scrollbar-driven scroll input methods. r=kats (89e5187b88)
- Bug 1156106 - Make nsMenuBarFrame::mMenuBarListener an nsRefPtr; r=roc (838126cd16)
- Bug 1163304 Close all existing popups when menubar becomes active because it should have pseudo focus and other popups shouldn't handle key events r=enn+neil (933c9ae40e)
- Bug 1252693 - Assert that we do not tenure into an OMT Zone; r=sfink (0812fc81f2)
- Bug 1265679 - Always call the object moved hook in generational GC r=terrence (6d75efba2d)
- Bug 1265825 - Remove mSuppressionActive assert. r=kats (3b6b3ba030)
- Bug 1250226 - Only report compacting GC telemetry for compacting GCs r=terrence (4e0f511ccf)
- Bug 1258578: Improve documentation for js::RelocatablePtr. DONTBUILD r=terrence (3ed2a933e0)
- Bug 1252713 - Fix FILES_PER_UNIFIED_FILE=1 bustage in js/. r=terrence (8a97e6c7e2)
- Bug 1265741: Fix unified build for fuzzers; r=nbp (ad3b4a4543)
- Bug 1013219 - set the line number of the terminating retrval; r=jimb, r=ejpbruel, r=fitzgen (df810884a9)
- Bug 1013219 - set line number of return instruction; r=efaust, r=fitzgen, r=ejpbruel (503b1a2bf3)
- Bug 1260577 - Fix |obj[expr] += e2| erroneously calling expr.toString() twice. (r=till) (e2485baccb)
- Bug 1260577 - followup: Change confusing name SelfAssign to CompoundAssign. (rs=jorendorff) (51a7dee68e)
- Bug 1263881 - Check the the number of body level lexicals doesn't exceed that which we can store in Bindings r=shu (d610d7a1e9)
- Bug 1258097 - Check for redeclaration of imports by functions r=shu (78f06f273f)
- Bug 1264954 - Add missing OOM check in Parser::templateLiteral. r=jonco (2743a82e1e)
- Bug 1265313 - Fix Annex B.3.5 handling with body-level lexicals. (r=jorendorff) (6b4139d25b)
- Bug 1260620 - Ensure that possibleErrors are not null before attempting to check them; r=jorendorff (6b284c1107)
- Bug 1253275 - Remove const_casts from Runtime.cpp. r=sfink (40b6d68455)
- Bug 1262731 - Add JS_InitWithFailureDiagnostic(). r=sfink. (310579fcd3)
- Bug 1263886 - Don't call makeConstructorCode if the group has unknown properties. r=bhackett (e81c939928)
- Bug 1260891 - Acquire and release the lock when destorying an `ExclusiveData<T>`'s protected value; r=terrence a=kwierso (dc39af575e)
- Bug 1252034 - Value Numbering: Unconditionally generate fixup blocks. r=sunfish (3b46b2df51)
- Bug 1232229 - Ensure generator object prototype is a singleton and tenured. r=jonco (d0c4f17cb6)
2024-04-25 21:58:07 +08:00

1257 lines
41 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* 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 "builtin/SelfHostingDefines.h"
#include "frontend/ParseNode.h"
#include "frontend/SharedContext.h"
#include "gc/Policy.h"
#include "gc/Tracer.h"
#include "jsobjinlines.h"
#include "jsscriptinlines.h"
using namespace js;
using namespace js::frontend;
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->getFixedSlot(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(); \
}
///////////////////////////////////////////////////////////////////////////
// ImportEntryObject
/* static */ const Class
ImportEntryObject::class_ = {
"ImportEntry",
JSCLASS_HAS_RESERVED_SLOTS(ImportEntryObject::SlotCount) |
JSCLASS_IS_ANONYMOUS
};
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, moduleRequest, ModuleRequestSlot)
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, importName, ImportNameSlot)
DEFINE_GETTER_FUNCTIONS(ImportEntryObject, localName, LocalNameSlot)
DEFINE_ATOM_ACCESSOR_METHOD(ImportEntryObject, moduleRequest)
DEFINE_ATOM_ACCESSOR_METHOD(ImportEntryObject, importName)
DEFINE_ATOM_ACCESSOR_METHOD(ImportEntryObject, localName)
/* 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_PS_END
};
RootedObject proto(cx, global->createBlankPrototype<PlainObject>(cx));
if (!proto)
return false;
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, nullptr))
return false;
global->setReservedSlot(IMPORT_ENTRY_PROTO, ObjectValue(*proto));
return true;
}
/* static */ ImportEntryObject*
ImportEntryObject::create(ExclusiveContext* cx,
HandleAtom moduleRequest,
HandleAtom importName,
HandleAtom localName)
{
RootedObject proto(cx, cx->global()->getImportEntryPrototype());
RootedObject obj(cx, NewObjectWithGivenProto(cx, &class_, proto));
if (!obj)
return nullptr;
RootedImportEntryObject self(cx, &obj->as<ImportEntryObject>());
self->initReservedSlot(ModuleRequestSlot, StringValue(moduleRequest));
self->initReservedSlot(ImportNameSlot, StringValue(importName));
self->initReservedSlot(LocalNameSlot, StringValue(localName));
return self;
}
///////////////////////////////////////////////////////////////////////////
// ExportEntryObject
/* static */ const Class
ExportEntryObject::class_ = {
"ExportEntry",
JSCLASS_HAS_RESERVED_SLOTS(ExportEntryObject::SlotCount) |
JSCLASS_IS_ANONYMOUS
};
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_ATOM_ACCESSOR_METHOD(ExportEntryObject, exportName)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ExportEntryObject, moduleRequest)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ExportEntryObject, importName)
DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ExportEntryObject, localName)
/* 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_PS_END
};
RootedObject proto(cx, global->createBlankPrototype<PlainObject>(cx));
if (!proto)
return false;
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, nullptr))
return false;
global->setReservedSlot(EXPORT_ENTRY_PROTO, ObjectValue(*proto));
return true;
}
static Value
StringOrNullValue(JSString* maybeString)
{
return maybeString ? StringValue(maybeString) : NullValue();
}
/* static */ ExportEntryObject*
ExportEntryObject::create(ExclusiveContext* cx,
HandleAtom maybeExportName,
HandleAtom maybeModuleRequest,
HandleAtom maybeImportName,
HandleAtom maybeLocalName)
{
RootedObject proto(cx, cx->global()->getExportEntryPrototype());
RootedObject obj(cx, NewObjectWithGivenProto(cx, &class_, proto));
if (!obj)
return nullptr;
RootedExportEntryObject self(cx, &obj->as<ExportEntryObject>());
self->initReservedSlot(ExportNameSlot, StringOrNullValue(maybeExportName));
self->initReservedSlot(ModuleRequestSlot, StringOrNullValue(maybeModuleRequest));
self->initReservedSlot(ImportNameSlot, StringOrNullValue(maybeImportName));
self->initReservedSlot(LocalNameSlot, StringOrNullValue(maybeLocalName));
return self;
}
///////////////////////////////////////////////////////////////////////////
// IndirectBindingMap
IndirectBindingMap::Binding::Binding(ModuleEnvironmentObject* environment, Shape* shape)
: environment(environment), shape(shape)
{}
IndirectBindingMap::IndirectBindingMap(Zone* zone)
: map_(ZoneAllocPolicy(zone))
{
}
bool
IndirectBindingMap::init()
{
return map_.init();
}
void
IndirectBindingMap::trace(JSTracer* trc)
{
for (Map::Enum e(map_); !e.empty(); e.popFront()) {
Binding& b = e.front().value();
TraceEdge(trc, &b.environment, "module bindings environment");
TraceEdge(trc, &b.shape, "module bindings shape");
jsid bindingName = e.front().key();
TraceManuallyBarrieredEdge(trc, &bindingName, "module bindings binding name");
MOZ_ASSERT(bindingName == e.front().key());
}
}
bool
IndirectBindingMap::putNew(JSContext* cx, HandleId name,
HandleModuleEnvironmentObject environment, HandleId localName)
{
RootedShape shape(cx, environment->lookup(cx, localName));
MOZ_ASSERT(shape);
if (!map_.putNew(name, Binding(environment, shape))) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
bool
IndirectBindingMap::lookup(jsid name, ModuleEnvironmentObject** envOut, Shape** shapeOut) const
{
auto ptr = map_.lookup(name);
if (!ptr)
return false;
const Binding& binding = ptr->value();
MOZ_ASSERT(binding.environment);
MOZ_ASSERT(!binding.environment->inDictionaryMode());
MOZ_ASSERT(binding.environment->containsPure(binding.shape));
*envOut = binding.environment;
*shapeOut = binding.shape;
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)
{
RootedValue priv(cx, ObjectValue(*module));
ProxyOptions options;
options.setLazyProto(true);
options.setSingleton(true);
RootedObject object(cx, NewProxyObject(cx, &proxyHandler, priv, nullptr, options));
if (!object)
return nullptr;
RootedId funName(cx, INTERNED_STRING_TO_JSID(cx, cx->names().Symbol_iterator_fun));
RootedFunction enumerateFun(cx);
enumerateFun = JS::GetSelfHostedFunction(cx, "ModuleNamespaceEnumerate", funName, 0);
if (!enumerateFun)
return nullptr;
SetProxyExtra(object, ProxyHandler::EnumerateFunctionSlot, ObjectValue(*enumerateFun));
return &object->as<ModuleNamespaceObject>();
}
ModuleObject&
ModuleNamespaceObject::module()
{
return GetProxyPrivate(this).toObject().as<ModuleObject>();
}
JSObject&
ModuleNamespaceObject::exports()
{
JSObject* exports = module().namespaceExports();
MOZ_ASSERT(exports);
return *exports;
}
IndirectBindingMap&
ModuleNamespaceObject::bindings()
{
IndirectBindingMap* bindings = module().namespaceBindings();
MOZ_ASSERT(bindings);
return *bindings;
}
bool
ModuleNamespaceObject::addBinding(JSContext* cx, HandleAtom exportedName,
HandleModuleObject targetModule, HandleAtom localName)
{
IndirectBindingMap* bindings(this->module().namespaceBindings());
MOZ_ASSERT(bindings);
RootedModuleEnvironmentObject environment(cx, &targetModule->initialEnvironment());
RootedId exportedNameId(cx, AtomToId(exportedName));
RootedId localNameId(cx, AtomToId(localName));
return bindings->putNew(cx, exportedNameId, environment, localNameId);
}
const char ModuleNamespaceObject::ProxyHandler::family = 0;
ModuleNamespaceObject::ProxyHandler::ProxyHandler()
: BaseProxyHandler(&family, true)
{}
JS::Value ModuleNamespaceObject::ProxyHandler::getEnumerateFunction(HandleObject proxy) const
{
return GetProxyExtra(proxy, EnumerateFunctionSlot);
}
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
{
return result.failCantSetProto();
}
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<PropertyDescriptor> desc) const
{
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
if (JSID_IS_SYMBOL(id)) {
Rooted<JS::Symbol*> symbol(cx, JSID_TO_SYMBOL(id));
if (symbol == cx->wellKnownSymbols().iterator) {
RootedValue enumerateFun(cx, getEnumerateFunction(proxy));
desc.object().set(proxy);
desc.setConfigurable(false);
desc.setEnumerable(false);
desc.setValue(enumerateFun);
return true;
}
// TODO: Implement @@toStringTag here and in has() and get() methods.
return true;
}
const IndirectBindingMap& bindings = ns->bindings();
ModuleEnvironmentObject* env;
Shape* shape;
if (!bindings.lookup(id, &env, &shape))
return true;
RootedValue value(cx, env->getSlot(shape->slot()));
if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
return false;
}
desc.object().set(env);
desc.setConfigurable(false);
desc.setEnumerable(true);
desc.setValue(value);
return true;
}
bool
ModuleNamespaceObject::ProxyHandler::defineProperty(JSContext* cx, HandleObject proxy, HandleId id,
Handle<PropertyDescriptor> desc,
ObjectOpResult& result) const
{
return result.failReadOnly();
}
bool
ModuleNamespaceObject::ProxyHandler::has(JSContext* cx, HandleObject proxy, HandleId id,
bool* bp) const
{
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
if (JSID_IS_SYMBOL(id)) {
Rooted<JS::Symbol*> symbol(cx, JSID_TO_SYMBOL(id));
if (symbol == cx->wellKnownSymbols().iterator)
return true;
return false;
}
*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 (JSID_IS_SYMBOL(id)) {
Rooted<JS::Symbol*> symbol(cx, JSID_TO_SYMBOL(id));
if (symbol == cx->wellKnownSymbols().iterator) {
vp.set(getEnumerateFunction(proxy));
return true;
}
return false;
}
ModuleEnvironmentObject* env;
Shape* shape;
if (!ns->bindings().lookup(id, &env, &shape))
return false;
RootedValue value(cx, env->getSlot(shape->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 (ns->bindings().has(id))
return result.failReadOnly();
return result.succeed();
}
bool
ModuleNamespaceObject::ProxyHandler::ownPropertyKeys(JSContext* cx, HandleObject proxy,
AutoIdVector& props) const
{
Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
RootedObject exports(cx, &ns->exports());
uint32_t count;
if (!GetLengthProperty(cx, exports, &count) || !props.reserve(props.length() + count))
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()));
return true;
}
///////////////////////////////////////////////////////////////////////////
// FunctionDeclaration
FunctionDeclaration::FunctionDeclaration(HandleAtom name, HandleFunction fun)
: name(name), fun(fun)
{}
void FunctionDeclaration::trace(JSTracer* trc)
{
TraceEdge(trc, &name, "FunctionDeclaration name");
TraceEdge(trc, &fun, "FunctionDeclaration fun");
}
///////////////////////////////////////////////////////////////////////////
// ModuleObject
/* static */ const ClassOps
ModuleObject::classOps_ = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* getProperty */
nullptr, /* setProperty */
nullptr, /* enumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
ModuleObject::finalize,
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
ModuleObject::trace
};
/* static */ const Class
ModuleObject::class_ = {
"Module",
JSCLASS_HAS_RESERVED_SLOTS(ModuleObject::SlotCount) |
JSCLASS_IS_ANONYMOUS,
&ModuleObject::classOps_
};
#define DEFINE_ARRAY_SLOT_ACCESSOR(cls, name, slot) \
ArrayObject& \
cls::name() const \
{ \
return getFixedSlot(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>();
}
/* static */ ModuleObject*
ModuleObject::create(ExclusiveContext* cx, HandleObject enclosingStaticScope)
{
RootedObject proto(cx, cx->global()->getModulePrototype());
RootedObject obj(cx, NewObjectWithGivenProto(cx, &class_, proto));
if (!obj)
return nullptr;
RootedModuleObject self(cx, &obj->as<ModuleObject>());
self->initReservedSlot(StaticScopeSlot, ObjectOrNullValue(enclosingStaticScope));
Zone* zone = cx->zone();
IndirectBindingMap* bindings = zone->new_<IndirectBindingMap>(zone);
if (!bindings || !bindings->init()) {
ReportOutOfMemory(cx);
js_delete<IndirectBindingMap>(bindings);
return nullptr;
}
self->initReservedSlot(ImportBindingsSlot, PrivateValue(bindings));
FunctionDeclarationVector* funDecls = zone->new_<FunctionDeclarationVector>(zone);
if (!funDecls) {
ReportOutOfMemory(cx);
return nullptr;
}
self->initReservedSlot(FunctionDeclarationsSlot, PrivateValue(funDecls));
return self;
}
/* static */ void
ModuleObject::finalize(js::FreeOp* fop, JSObject* obj)
{
ModuleObject* self = &obj->as<ModuleObject>();
if (self->hasImportBindings())
fop->delete_(&self->importBindings());
if (IndirectBindingMap* bindings = self->namespaceBindings())
fop->delete_(bindings);
if (FunctionDeclarationVector* funDecls = self->functionDeclarations())
fop->delete_(funDecls);
}
ModuleEnvironmentObject*
ModuleObject::environment() const
{
Value value = getReservedSlot(EnvironmentSlot);
if (value.isUndefined())
return nullptr;
return &value.toObject().as<ModuleEnvironmentObject>();
}
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());
}
JSObject*
ModuleObject::namespaceExports()
{
Value value = getReservedSlot(NamespaceExportsSlot);
if (value.isUndefined())
return nullptr;
return &value.toObject();
}
IndirectBindingMap*
ModuleObject::namespaceBindings()
{
Value value = getReservedSlot(NamespaceBindingsSlot);
if (value.isUndefined())
return nullptr;
return static_cast<IndirectBindingMap*>(value.toPrivate());
}
ModuleNamespaceObject*
ModuleObject::namespace_()
{
Value value = getReservedSlot(NamespaceSlot);
if (value.isUndefined())
return nullptr;
return &value.toObject().as<ModuleNamespaceObject>();
}
FunctionDeclarationVector*
ModuleObject::functionDeclarations()
{
Value value = getReservedSlot(FunctionDeclarationsSlot);
if (value.isUndefined())
return nullptr;
return static_cast<FunctionDeclarationVector*>(value.toPrivate());
}
void
ModuleObject::init(HandleScript script)
{
initReservedSlot(ScriptSlot, PrivateValue(script));
initReservedSlot(EvaluatedSlot, BooleanValue(false));
}
void
ModuleObject::setInitialEnvironment(HandleModuleEnvironmentObject initialEnvironment)
{
initReservedSlot(InitialEnvironmentSlot, ObjectValue(*initialEnvironment));
}
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::FreezeArrayProperties(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);
}
static inline void
AssertObjectPropertyFrozen(JSContext* cx, HandleNativeObject obj, uint32_t slot)
{
#ifdef DEBUG
bool frozen = false;
RootedObject property(cx, &obj->getSlot(slot).toObject());
MOZ_ALWAYS_TRUE(TestIntegrityLevel(cx, property, IntegrityLevel::Frozen, &frozen));
MOZ_ASSERT(frozen);
#endif
}
/* static */ inline void
ModuleObject::AssertArrayPropertiesFrozen(JSContext* cx, HandleModuleObject self)
{
AssertObjectPropertyFrozen(cx, self, RequestedModulesSlot);
AssertObjectPropertyFrozen(cx, self, ImportEntriesSlot);
AssertObjectPropertyFrozen(cx, self, LocalExportEntriesSlot);
AssertObjectPropertyFrozen(cx, self, IndirectExportEntriesSlot);
AssertObjectPropertyFrozen(cx, self, StarExportEntriesSlot);
}
inline static void
AssertModuleScopesMatch(ModuleObject* module)
{
MOZ_ASSERT(IsStaticGlobalLexicalScope(module->enclosingStaticScope()));
MOZ_ASSERT(module->initialEnvironment().enclosingScope().as<ClonedBlockObject>().staticScope() ==
module->enclosingStaticScope());
}
void
ModuleObject::fixScopesAfterCompartmentMerge(JSContext* cx)
{
AssertModuleScopesMatch(this);
Rooted<ClonedBlockObject*> lexicalScope(cx, &script()->global().lexicalScope());
setReservedSlot(StaticScopeSlot, ObjectValue(lexicalScope->staticBlock()));
initialEnvironment().setEnclosingScope(lexicalScope);
AssertModuleScopesMatch(this);
}
bool
ModuleObject::hasScript() const
{
// When modules are parsed via the Reflect.parse() API, the module object
// doesn't have a script.
return !getReservedSlot(ScriptSlot).isUndefined();
}
JSScript*
ModuleObject::script() const
{
return static_cast<JSScript*>(getReservedSlot(ScriptSlot).toPrivate());
}
bool
ModuleObject::evaluated() const
{
return getReservedSlot(EvaluatedSlot).toBoolean();
}
ModuleEnvironmentObject&
ModuleObject::initialEnvironment() const
{
return getReservedSlot(InitialEnvironmentSlot).toObject().as<ModuleEnvironmentObject>();
}
JSObject*
ModuleObject::enclosingStaticScope() const
{
return getReservedSlot(StaticScopeSlot).toObjectOrNull();
}
/* static */ void
ModuleObject::trace(JSTracer* trc, JSObject* obj)
{
ModuleObject& module = obj->as<ModuleObject>();
if (module.hasScript()) {
JSScript* script = module.script();
TraceManuallyBarrieredEdge(trc, &script, "Module script");
module.setReservedSlot(ScriptSlot, PrivateValue(script));
}
if (module.hasImportBindings())
module.importBindings().trace(trc);
if (IndirectBindingMap* bindings = module.namespaceBindings())
bindings->trace(trc);
if (FunctionDeclarationVector* funDecls = module.functionDeclarations())
funDecls->trace(trc);
}
void
ModuleObject::createEnvironment()
{
// The environment has already been created, we just neet to set it in the
// right slot.
MOZ_ASSERT(!getReservedSlot(InitialEnvironmentSlot).isUndefined());
MOZ_ASSERT(getReservedSlot(EnvironmentSlot).isUndefined());
setReservedSlot(EnvironmentSlot, getReservedSlot(InitialEnvironmentSlot));
}
bool
ModuleObject::noteFunctionDeclaration(ExclusiveContext* cx, HandleAtom name, HandleFunction fun)
{
FunctionDeclarationVector* funDecls = functionDeclarations();
if (!funDecls->emplaceBack(name, fun)) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
/* static */ bool
ModuleObject::instantiateFunctionDeclarations(JSContext* cx, HandleModuleObject self)
{
AssertArrayPropertiesFrozen(cx, self);
FunctionDeclarationVector* funDecls = self->functionDeclarations();
if (!funDecls) {
JS_ReportError(cx, "Module function declarations have already been instantiated");
return false;
}
RootedModuleEnvironmentObject env(cx, &self->initialEnvironment());
RootedFunction fun(cx);
RootedValue value(cx);
for (const auto& funDecl : *funDecls) {
fun = funDecl.fun;
RootedObject obj(cx, Lambda(cx, fun, env));
if (!obj)
return false;
value = ObjectValue(*fun);
if (!SetProperty(cx, env, funDecl.name->asPropertyName(), value))
return false;
}
js_delete(funDecls);
self->setReservedSlot(FunctionDeclarationsSlot, UndefinedValue());
return true;
}
void
ModuleObject::setEvaluated()
{
MOZ_ASSERT(!evaluated());
setReservedSlot(EvaluatedSlot, TrueHandleValue);
}
/* static */ bool
ModuleObject::evaluate(JSContext* cx, HandleModuleObject self, MutableHandleValue rval)
{
AssertArrayPropertiesFrozen(cx, self);
RootedScript script(cx, self->script());
RootedModuleEnvironmentObject scope(cx, self->environment());
if (!scope) {
JS_ReportError(cx, "Module declarations have not yet been instantiated");
return false;
}
return Execute(cx, script, *scope, rval.address());
}
/* static */ ModuleNamespaceObject*
ModuleObject::createNamespace(JSContext* cx, HandleModuleObject self, HandleObject exports)
{
MOZ_ASSERT(!self->namespace_());
MOZ_ASSERT(exports->is<ArrayObject>() || exports->is<UnboxedArrayObject>());
RootedModuleNamespaceObject ns(cx, ModuleNamespaceObject::create(cx, self));
if (!ns)
return nullptr;
Zone* zone = cx->zone();
IndirectBindingMap* bindings = zone->new_<IndirectBindingMap>(zone);
if (!bindings || !bindings->init()) {
ReportOutOfMemory(cx);
js_delete<IndirectBindingMap>(bindings);
return nullptr;
}
self->initReservedSlot(NamespaceSlot, ObjectValue(*ns));
self->initReservedSlot(NamespaceExportsSlot, ObjectValue(*exports));
self->initReservedSlot(NamespaceBindingsSlot, PrivateValue(bindings));
return ns;
}
DEFINE_GETTER_FUNCTIONS(ModuleObject, namespace_, NamespaceSlot)
DEFINE_GETTER_FUNCTIONS(ModuleObject, evaluated, EvaluatedSlot)
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)
/* static */ bool
GlobalObject::initModuleProto(JSContext* cx, Handle<GlobalObject*> global)
{
static const JSPropertySpec protoAccessors[] = {
JS_PSG("namespace", ModuleObject_namespace_Getter, 0),
JS_PSG("evaluated", ModuleObject_evaluatedGetter, 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_PS_END
};
static const JSFunctionSpec protoFunctions[] = {
JS_SELF_HOSTED_FN("getExportedNames", "ModuleGetExportedNames", 1, 0),
JS_SELF_HOSTED_FN("resolveExport", "ModuleResolveExport", 3, 0),
JS_SELF_HOSTED_FN("declarationInstantiation", "ModuleDeclarationInstantiation", 0, 0),
JS_SELF_HOSTED_FN("evaluation", "ModuleEvaluation", 0, 0),
JS_FS_END
};
RootedObject proto(cx, global->createBlankPrototype<PlainObject>(cx));
if (!proto)
return false;
if (!DefinePropertiesAndFunctions(cx, proto, protoAccessors, protoFunctions))
return false;
global->setReservedSlot(MODULE_PROTO, ObjectValue(*proto));
return true;
}
bool
js::InitModuleClasses(JSContext* cx, HandleObject obj)
{
Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
return GlobalObject::initModuleProto(cx, global) &&
GlobalObject::initImportEntryProto(cx, global) &&
GlobalObject::initExportEntryProto(cx, global);
}
#undef DEFINE_GETTER_FUNCTIONS
#undef DEFINE_STRING_ACCESSOR_METHOD
#undef DEFINE_ARRAY_SLOT_ACCESSOR
///////////////////////////////////////////////////////////////////////////
// ModuleBuilder
ModuleBuilder::ModuleBuilder(ExclusiveContext* cx, HandleModuleObject module)
: cx_(cx),
module_(cx, module),
requestedModules_(cx, AtomVector(cx)),
importedBoundNames_(cx, AtomVector(cx)),
importEntries_(cx, ImportEntryVector(cx)),
exportEntries_(cx, ExportEntryVector(cx)),
localExportEntries_(cx, ExportEntryVector(cx)),
indirectExportEntries_(cx, ExportEntryVector(cx)),
starExportEntries_(cx, ExportEntryVector(cx))
{}
bool
ModuleBuilder::buildTables()
{
for (const auto& e : exportEntries_) {
RootedExportEntryObject exp(cx_, e);
if (!exp->moduleRequest()) {
RootedImportEntryObject importEntry(cx_, importEntryFor(exp->localName()));
if (!importEntry) {
if (!localExportEntries_.append(exp))
return false;
} else {
if (importEntry->importName() == cx_->names().star) {
if (!localExportEntries_.append(exp))
return false;
} else {
RootedAtom exportName(cx_, exp->exportName());
RootedAtom moduleRequest(cx_, importEntry->moduleRequest());
RootedAtom importName(cx_, importEntry->importName());
RootedExportEntryObject exportEntry(cx_);
exportEntry = ExportEntryObject::create(cx_,
exportName,
moduleRequest,
importName,
nullptr);
if (!exportEntry || !indirectExportEntries_.append(exportEntry))
return false;
}
}
} else if (exp->importName() == cx_->names().star) {
if (!starExportEntries_.append(exp))
return false;
} else {
if (!indirectExportEntries_.append(exp))
return false;
}
}
return true;
}
bool
ModuleBuilder::initModule()
{
RootedArrayObject requestedModules(cx_, createArray<JSAtom*>(requestedModules_));
if (!requestedModules)
return false;
RootedArrayObject importEntries(cx_, createArray<ImportEntryObject*>(importEntries_));
if (!importEntries)
return false;
RootedArrayObject localExportEntries(cx_, createArray<ExportEntryObject*>(localExportEntries_));
if (!localExportEntries)
return false;
RootedArrayObject indirectExportEntries(cx_);
indirectExportEntries = createArray<ExportEntryObject*>(indirectExportEntries_);
if (!indirectExportEntries)
return false;
RootedArrayObject starExportEntries(cx_, createArray<ExportEntryObject*>(starExportEntries_));
if (!starExportEntries)
return false;
module_->initImportExportData(requestedModules,
importEntries,
localExportEntries,
indirectExportEntries,
starExportEntries);
return true;
}
bool
ModuleBuilder::processImport(frontend::ParseNode* pn)
{
MOZ_ASSERT(pn->isKind(PNK_IMPORT));
MOZ_ASSERT(pn->isArity(PN_BINARY));
MOZ_ASSERT(pn->pn_left->isKind(PNK_IMPORT_SPEC_LIST));
MOZ_ASSERT(pn->pn_right->isKind(PNK_STRING));
RootedAtom module(cx_, pn->pn_right->pn_atom);
if (!maybeAppendRequestedModule(module))
return false;
for (ParseNode* spec = pn->pn_left->pn_head; spec; spec = spec->pn_next) {
MOZ_ASSERT(spec->isKind(PNK_IMPORT_SPEC));
MOZ_ASSERT(spec->pn_left->isArity(PN_NAME));
MOZ_ASSERT(spec->pn_right->isArity(PN_NAME));
RootedAtom importName(cx_, spec->pn_left->pn_atom);
RootedAtom localName(cx_, spec->pn_right->pn_atom);
if (!importedBoundNames_.append(localName))
return false;
RootedImportEntryObject importEntry(cx_);
importEntry = ImportEntryObject::create(cx_, module, importName, localName);
if (!importEntry || !importEntries_.append(importEntry))
return false;
}
return true;
}
bool
ModuleBuilder::processExport(frontend::ParseNode* pn)
{
MOZ_ASSERT(pn->isKind(PNK_EXPORT) || pn->isKind(PNK_EXPORT_DEFAULT));
MOZ_ASSERT(pn->getArity() == pn->isKind(PNK_EXPORT) ? PN_UNARY : PN_BINARY);
bool isDefault = pn->getKind() == PNK_EXPORT_DEFAULT;
ParseNode* kid = isDefault ? pn->pn_left : pn->pn_kid;
switch (kid->getKind()) {
case PNK_EXPORT_SPEC_LIST:
MOZ_ASSERT(!isDefault);
for (ParseNode* spec = kid->pn_head; spec; spec = spec->pn_next) {
MOZ_ASSERT(spec->isKind(PNK_EXPORT_SPEC));
RootedAtom localName(cx_, spec->pn_left->pn_atom);
RootedAtom exportName(cx_, spec->pn_right->pn_atom);
if (!appendExportEntry(exportName, localName))
return false;
}
break;
case PNK_FUNCTION: {
RootedFunction func(cx_, kid->pn_funbox->function());
RootedAtom localName(cx_, func->atom());
RootedAtom exportName(cx_, isDefault ? cx_->names().default_ : localName.get());
if (!appendExportEntry(exportName, localName))
return false;
break;
}
case PNK_CLASS: {
const ClassNode& cls = kid->as<ClassNode>();
MOZ_ASSERT(cls.names());
RootedAtom localName(cx_, cls.names()->innerBinding()->pn_atom);
RootedAtom exportName(cx_, isDefault ? cx_->names().default_ : localName.get());
if (!appendExportEntry(exportName, localName))
return false;
break;
}
case PNK_VAR:
case PNK_CONST:
case PNK_LET: {
MOZ_ASSERT(kid->isArity(PN_LIST));
for (ParseNode* var = kid->pn_head; var; var = var->pn_next) {
if (var->isKind(PNK_ASSIGN))
var = var->pn_left;
MOZ_ASSERT(var->isKind(PNK_NAME));
RootedAtom localName(cx_, var->pn_atom);
RootedAtom exportName(cx_, isDefault ? cx_->names().default_ : localName.get());
if (!appendExportEntry(exportName, localName))
return false;
}
break;
}
default:
MOZ_ASSERT(isDefault);
RootedAtom localName(cx_, cx_->names().starDefaultStar);
RootedAtom exportName(cx_, cx_->names().default_);
if (!appendExportEntry(exportName, localName))
return false;
break;
}
return true;
}
bool
ModuleBuilder::processExportFrom(frontend::ParseNode* pn)
{
MOZ_ASSERT(pn->isKind(PNK_EXPORT_FROM));
MOZ_ASSERT(pn->isArity(PN_BINARY));
MOZ_ASSERT(pn->pn_left->isKind(PNK_EXPORT_SPEC_LIST));
MOZ_ASSERT(pn->pn_right->isKind(PNK_STRING));
RootedAtom module(cx_, pn->pn_right->pn_atom);
if (!maybeAppendRequestedModule(module))
return false;
for (ParseNode* spec = pn->pn_left->pn_head; spec; spec = spec->pn_next) {
if (spec->isKind(PNK_EXPORT_SPEC)) {
RootedAtom bindingName(cx_, spec->pn_left->pn_atom);
RootedAtom exportName(cx_, spec->pn_right->pn_atom);
if (!appendExportFromEntry(exportName, module, bindingName))
return false;
} else {
MOZ_ASSERT(spec->isKind(PNK_EXPORT_BATCH_SPEC));
RootedAtom importName(cx_, cx_->names().star);
if (!appendExportFromEntry(nullptr, module, importName))
return false;
}
}
return true;
}
ImportEntryObject*
ModuleBuilder::importEntryFor(JSAtom* localName) const
{
for (auto import : importEntries_) {
if (import->localName() == localName)
return import;
}
return nullptr;
}
bool
ModuleBuilder::hasExportedName(JSAtom* name) const
{
for (auto entry : exportEntries_) {
if (entry->exportName() == name)
return true;
}
return false;
}
bool
ModuleBuilder::appendExportEntry(HandleAtom exportName, HandleAtom localName)
{
Rooted<ExportEntryObject*> exportEntry(cx_);
exportEntry = ExportEntryObject::create(cx_, exportName, nullptr, nullptr, localName);
return exportEntry && exportEntries_.append(exportEntry);
}
bool
ModuleBuilder::appendExportFromEntry(HandleAtom exportName, HandleAtom moduleRequest,
HandleAtom importName)
{
Rooted<ExportEntryObject*> exportEntry(cx_);
exportEntry = ExportEntryObject::create(cx_, exportName, moduleRequest, importName, nullptr);
return exportEntry && exportEntries_.append(exportEntry);
}
bool
ModuleBuilder::maybeAppendRequestedModule(HandleAtom module)
{
for (auto m : requestedModules_) {
if (m == module)
return true;
}
return requestedModules_.append(module);
}
static Value
MakeElementValue(JSString *string)
{
return StringValue(string);
}
static Value
MakeElementValue(JSObject *object)
{
return ObjectValue(*object);
}
template <typename T>
ArrayObject* ModuleBuilder::createArray(const GCVector<T>& vector)
{
uint32_t length = vector.length();
RootedArrayObject array(cx_, NewDenseFullyAllocatedArray(cx_, length));
if (!array)
return nullptr;
array->setDenseInitializedLength(length);
for (uint32_t i = 0; i < length; i++)
array->initDenseElement(i, MakeElementValue(vector[i]));
return array;
}