Debian Codegraph @

js/src/builtin/ModuleObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "builtin/ModuleObject.h"
8
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/EnumSet.h"
11 #include "mozilla/ScopeExit.h"
12
13 #include "builtin/Promise.h"
14 #include "builtin/SelfHostingDefines.h"
15 #include "frontend/ParseNode.h"
16 #include "frontend/ParserAtom.h" // TaggedParserAtomIndex, ParserAtomsTable, ParserAtom
17 #include "frontend/SharedContext.h"
18 #include "frontend/Stencil.h"
19 #include "gc/GCContext.h"
20 #include "gc/Tracer.h"
21 #include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin, JS::LimitedColumnNumberOneOrigin
22 #include "js/friend/ErrorMessages.h" // JSMSG_*
23 #include "js/Modules.h" // JS::GetModulePrivate, JS::ModuleDynamicImportHook, JS::ModuleType
24 #include "vm/EqualityOperations.h" // js::SameValue
25 #include "vm/Interpreter.h" // Execute, Lambda, ReportRuntimeLexicalError
26 #include "vm/ModuleBuilder.h" // js::ModuleBuilder
27 #include "vm/Modules.h"
28 #include "vm/PlainObject.h" // js::PlainObject
29 #include "vm/PromiseObject.h" // js::PromiseObject
30 #include "vm/SharedStencil.h" // js::GCThingIndex
31
32 #include "builtin/HandlerFunction-inl.h" // js::ExtraValueFromHandler, js::NewHandler{,WithExtraValue}, js::TargetFromHandler
33 #include "gc/GCContext-inl.h"
34 #include "vm/EnvironmentObject-inl.h" // EnvironmentObject::setAliasedBinding
35 #include "vm/JSObject-inl.h"
36 #include "vm/JSScript-inl.h"
37 #include "vm/List-inl.h"
38 #include "vm/NativeObject-inl.h"
39
40 using namespace js;
41
42 using mozilla::Maybe;
43 using mozilla::Nothing;
44 using mozilla::Some;
45 using mozilla::Span;
46
47 static_assert(ModuleStatus::Unlinked < ModuleStatus::Linking &&
48 ModuleStatus::Linking < ModuleStatus::Linked &&
49 ModuleStatus::Linked < ModuleStatus::Evaluating &&
50 ModuleStatus::Evaluating < ModuleStatus::EvaluatingAsync &&
51 ModuleStatus::EvaluatingAsync < ModuleStatus::Evaluated &&
52 ModuleStatus::Evaluated < ModuleStatus::Evaluated_Error,
53 "Module statuses are ordered incorrectly");
54
55 static Value StringOrNullValue(JSString* maybeString) {
56 return maybeString ? StringValue(maybeString) : NullValue();
57 }
58
59 static Value ModuleTypeToValue(JS::ModuleType moduleType) {
60 static_assert(size_t(JS::ModuleType::Limit) <= INT32_MAX);
61 return Int32Value(int32_t(moduleType));
62 }
63
64 static JS::ModuleType ValueToModuleType(const Value& value) {
65 int32_t i = value.toInt32();
66 MOZ_ASSERT(i >= 0 && i <= int32_t(JS::ModuleType::Limit));
67 return static_cast<JS::ModuleType>(i);
68 }
69
70 #define DEFINE_ATOM_ACCESSOR_METHOD(cls, name, slot) \
71 JSAtom* cls::name() const { \
72 Value value = getReservedSlot(slot); \
73 return &value.toString()->asAtom(); \
74 }
75
76 #define DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(cls, name, slot) \
77 JSAtom* cls::name() const { \
78 Value value = getReservedSlot(slot); \
79 if (value.isNull()) { \
80 return nullptr; \
81 } \
82 return &value.toString()->asAtom(); \
83 }
84
85 #define DEFINE_UINT32_ACCESSOR_METHOD(cls, name, slot) \
86 uint32_t cls::name() const { \
87 Value value = getReservedSlot(slot); \
88 MOZ_ASSERT(value.toNumber() >= 0); \
89 if (value.isInt32()) { \
90 return value.toInt32(); \
91 } \
92 return JS::ToUint32(value.toDouble()); \
93 }
94
95 ///////////////////////////////////////////////////////////////////////////
96 // ImportEntry
97
98 ImportEntry::ImportEntry(Handle<ModuleRequestObject*> moduleRequest,
99 Handle<JSAtom*> maybeImportName,
100 Handle<JSAtom*> localName, uint32_t lineNumber,
101 JS::ColumnNumberOneOrigin columnNumber)
102 : moduleRequest_(moduleRequest),
103 importName_(maybeImportName),
104 localName_(localName),
105 lineNumber_(lineNumber),
106 columnNumber_(columnNumber) {}
107
108 void ImportEntry::trace(JSTracer* trc) {
109 TraceEdge(trc, &moduleRequest_, "ImportEntry::moduleRequest_");
110 TraceNullableEdge(trc, &importName_, "ImportEntry::importName_");
111 TraceNullableEdge(trc, &localName_, "ImportEntry::localName_");
112 }
113
114 ///////////////////////////////////////////////////////////////////////////
115 // ExportEntry
116
117 ExportEntry::ExportEntry(Handle<JSAtom*> maybeExportName,
118 Handle<ModuleRequestObject*> moduleRequest,
119 Handle<JSAtom*> maybeImportName,
120 Handle<JSAtom*> maybeLocalName, uint32_t lineNumber,
121 JS::ColumnNumberOneOrigin columnNumber)
122 : exportName_(maybeExportName),
123 moduleRequest_(moduleRequest),
124 importName_(maybeImportName),
125 localName_(maybeLocalName),
126 lineNumber_(lineNumber),
127 columnNumber_(columnNumber) {
128 // Line and column numbers are optional for export entries since direct
129 // entries are checked at parse time.
130 }
131
132 void ExportEntry::trace(JSTracer* trc) {
133 TraceNullableEdge(trc, &exportName_, "ExportEntry::exportName_");
134 TraceNullableEdge(trc, &moduleRequest_, "ExportEntry::moduleRequest_");
135 TraceNullableEdge(trc, &importName_, "ExportEntry::importName_");
136 TraceNullableEdge(trc, &localName_, "ExportEntry::localName_");
137 }
138
139 ///////////////////////////////////////////////////////////////////////////
140 // RequestedModule
141
142 /* static */
143 RequestedModule::RequestedModule(Handle<ModuleRequestObject*> moduleRequest,
144 uint32_t lineNumber,
145 JS::ColumnNumberOneOrigin columnNumber)
146 : moduleRequest_(moduleRequest),
147 lineNumber_(lineNumber),
148 columnNumber_(columnNumber) {}
149
150 void RequestedModule::trace(JSTracer* trc) {
151 TraceEdge(trc, &moduleRequest_, "ExportEntry::moduleRequest_");
152 }
153
154 ///////////////////////////////////////////////////////////////////////////
155 // ResolvedBindingObject
156
157 /* static */ const JSClass ResolvedBindingObject::class_ = {
158 "ResolvedBinding",
159 JSCLASS_HAS_RESERVED_SLOTS(ResolvedBindingObject::SlotCount),
160 };
161
162 ModuleObject* ResolvedBindingObject::module() const {
163 Value value = getReservedSlot(ModuleSlot);
164 return &value.toObject().as<ModuleObject>();
165 }
166
167 JSAtom* ResolvedBindingObject::bindingName() const {
168 Value value = getReservedSlot(BindingNameSlot);
169 return &value.toString()->asAtom();
170 }
171
172 /* static */
173 bool ResolvedBindingObject::isInstance(HandleValue value) {
174 return value.isObject() && value.toObject().is<ResolvedBindingObject>();
175 }
176
177 /* static */
178 ResolvedBindingObject* ResolvedBindingObject::create(
179 JSContext* cx, Handle<ModuleObject*> module, Handle<JSAtom*> bindingName) {
180 ResolvedBindingObject* self =
181 NewObjectWithGivenProto<ResolvedBindingObject>(cx, nullptr);
182 if (!self) {
183 return nullptr;
184 }
185
186 self->initReservedSlot(ModuleSlot, ObjectValue(*module));
187 self->initReservedSlot(BindingNameSlot, StringValue(bindingName));
188 return self;
189 }
190
191 ///////////////////////////////////////////////////////////////////////////
192 // ImportAttribute
193
194 ImportAttribute::ImportAttribute(Handle<JSAtom*> key, Handle<JSString*> value)
195 : key_(key), value_(value) {}
196
197 void ImportAttribute::trace(JSTracer* trc) {
198 TraceNullableEdge(trc, &key_, "ImportAttribute::key_");
199 TraceNullableEdge(trc, &value_, "ImportAttribute::value_");
200 }
201
202 ///////////////////////////////////////////////////////////////////////////
203 // ModuleRequestObject
204 /* static */ const JSClass ModuleRequestObject::class_ = {
205 "ModuleRequest",
206 JSCLASS_HAS_RESERVED_SLOTS(ModuleRequestObject::SlotCount),
207 };
208
209 DEFINE_ATOM_OR_NULL_ACCESSOR_METHOD(ModuleRequestObject, specifier,
210 SpecifierSlot)
211
212 JS::ModuleType ModuleRequestObject::moduleType() const {
213 return ValueToModuleType(getReservedSlot(ModuleTypeSlot));
214 }
215
216 static bool GetModuleType(JSContext* cx,
217 Handle<ImportAttributeVector> maybeAttributes,
218 JS::ModuleType& moduleType) {
219 for (const ImportAttribute& importAttribute : maybeAttributes) {
220 if (importAttribute.key() == cx->names().type) {
221 int32_t isJsonString;
222 if (!js::CompareStrings(cx, cx->names().json, importAttribute.value(),
223 &isJsonString)) {
224 return false;
225 }
226
227 if (isJsonString == 0) {
228 moduleType = JS::ModuleType::JSON;
229 return true;
230 }
231
232 moduleType = JS::ModuleType::Unknown;
233 return true;
234 }
235 }
236
237 moduleType = JS::ModuleType::JavaScript;
238 return true;
239 }
240
241 /* static */
242 bool ModuleRequestObject::isInstance(HandleValue value) {
243 return value.isObject() && value.toObject().is<ModuleRequestObject>();
244 }
245
246 /* static */
247 ModuleRequestObject* ModuleRequestObject::create(
248 JSContext* cx, Handle<JSAtom*> specifier,
249 Handle<ImportAttributeVector> maybeAttributes) {
250 JS::ModuleType moduleType = JS::ModuleType::JavaScript;
251 if (!GetModuleType(cx, maybeAttributes, moduleType)) {
252 return nullptr;
253 }
254
255 return create(cx, specifier, moduleType);
256 }
257
258 /* static */
259 ModuleRequestObject* ModuleRequestObject::create(JSContext* cx,
260 Handle<JSAtom*> specifier,
261 JS::ModuleType moduleType) {
262 ModuleRequestObject* self =
263 NewObjectWithGivenProto<ModuleRequestObject>(cx, nullptr);
264 if (!self) {
265 return nullptr;
266 }
267
268 self->initReservedSlot(SpecifierSlot, StringOrNullValue(specifier));
269 self->initReservedSlot(ModuleTypeSlot, ModuleTypeToValue(moduleType));
270
271 return self;
272 }
273
274 void ModuleRequestObject::setFirstUnsupportedAttributeKey(Handle<JSAtom*> key) {
275 initReservedSlot(FirstUnsupportedAttributeKeySlot, StringOrNullValue(key));
276 }
277
278 bool ModuleRequestObject::hasFirstUnsupportedAttributeKey() const {
279 return !getReservedSlot(FirstUnsupportedAttributeKeySlot).isNullOrUndefined();
280 }
281
282 JSAtom* ModuleRequestObject::getFirstUnsupportedAttributeKey() const {
283 if (!hasFirstUnsupportedAttributeKey()) {
284 return nullptr;
285 }
286 return &getReservedSlot(FirstUnsupportedAttributeKeySlot)
287 .toString()
288 ->asAtom();
289 }
290
291 ///////////////////////////////////////////////////////////////////////////
292 // IndirectBindingMap
293
294 IndirectBindingMap::Binding::Binding(ModuleEnvironmentObject* environment,
295 jsid targetName, PropertyInfo prop)
296 : environment(environment),
297 #ifdef DEBUG
298 targetName(targetName),
299 #endif
300 prop(prop) {
301 }
302
303 void IndirectBindingMap::trace(JSTracer* trc) {
304 if (!map_) {
305 return;
306 }
307
308 for (Map::Enum e(*map_); !e.empty(); e.popFront()) {
309 Binding& b = e.front().value();
310 TraceEdge(trc, &b.environment, "module bindings environment");
311 #ifdef DEBUG
312 TraceEdge(trc, &b.targetName, "module bindings target name");
313 #endif
314 mozilla::DebugOnly<jsid> prev(e.front().key());
315 TraceEdge(trc, &e.front().mutableKey(), "module bindings binding name");
316 MOZ_ASSERT(e.front().key() == prev);
317 }
318 }
319
320 bool IndirectBindingMap::put(JSContext* cx, HandleId name,
321 Handle<ModuleEnvironmentObject*> environment,
322 HandleId targetName) {
323 if (!map_) {
324 map_.emplace(cx->zone());
325 }
326
327 mozilla::Maybe<PropertyInfo> prop = environment->lookup(cx, targetName);
328 MOZ_ASSERT(prop.isSome());
329 if (!map_->put(name, Binding(environment, targetName, *prop))) {
330 ReportOutOfMemory(cx);
331 return false;
332 }
333
334 return true;
335 }
336
337 bool IndirectBindingMap::lookup(jsid name, ModuleEnvironmentObject** envOut,
338 mozilla::Maybe<PropertyInfo>* propOut) const {
339 if (!map_) {
340 return false;
341 }
342
343 auto ptr = map_->lookup(name);
344 if (!ptr) {
345 return false;
346 }
347
348 const Binding& binding = ptr->value();
349 MOZ_ASSERT(binding.environment);
350 MOZ_ASSERT(
351 binding.environment->containsPure(binding.targetName, binding.prop));
352 *envOut = binding.environment;
353 *propOut = Some(binding.prop);
354 return true;
355 }
356
357 ///////////////////////////////////////////////////////////////////////////
358 // ModuleNamespaceObject
359
360 /* static */
361 constexpr ModuleNamespaceObject::ProxyHandler
362 ModuleNamespaceObject::proxyHandler;
363
364 /* static */
365 bool ModuleNamespaceObject::isInstance(HandleValue value) {
366 return value.isObject() && value.toObject().is<ModuleNamespaceObject>();
367 }
368
369 /* static */
370 ModuleNamespaceObject* ModuleNamespaceObject::create(
371 JSContext* cx, Handle<ModuleObject*> module,
372 MutableHandle<UniquePtr<ExportNameVector>> exports,
373 MutableHandle<UniquePtr<IndirectBindingMap>> bindings) {
374 RootedValue priv(cx, ObjectValue(*module));
375 ProxyOptions options;
376 options.setLazyProto(true);
377
378 RootedObject object(
379 cx, NewProxyObject(cx, &proxyHandler, priv, nullptr, options));
380 if (!object) {
381 return nullptr;
382 }
383
384 SetProxyReservedSlot(object, ExportsSlot,
385 PrivateValue(exports.get().release()));
386 AddCellMemory(object, sizeof(ExportNameVector), MemoryUse::ModuleExports);
387
388 SetProxyReservedSlot(object, BindingsSlot,
389 PrivateValue(bindings.get().release()));
390 AddCellMemory(object, sizeof(IndirectBindingMap),
391 MemoryUse::ModuleBindingMap);
392
393 return &object->as<ModuleNamespaceObject>();
394 }
395
396 ModuleObject& ModuleNamespaceObject::module() {
397 return GetProxyPrivate(this).toObject().as<ModuleObject>();
398 }
399
400 const ExportNameVector& ModuleNamespaceObject::exports() const {
401 Value value = GetProxyReservedSlot(this, ExportsSlot);
402 auto* exports = static_cast<ExportNameVector*>(value.toPrivate());
403 MOZ_ASSERT(exports);
404 return *exports;
405 }
406
407 ExportNameVector& ModuleNamespaceObject::mutableExports() {
408 // Get a non-const reference for tracing/destruction. Do not actually mutate
409 // this vector! This would be incorrect without adding barriers.
410 return const_cast<ExportNameVector&>(exports());
411 }
412
413 IndirectBindingMap& ModuleNamespaceObject::bindings() {
414 Value value = GetProxyReservedSlot(this, BindingsSlot);
415 auto* bindings = static_cast<IndirectBindingMap*>(value.toPrivate());
416 MOZ_ASSERT(bindings);
417 return *bindings;
418 }
419
420 bool ModuleNamespaceObject::hasExports() const {
421 // Exports may not be present if we hit OOM in initialization.
422 return !GetProxyReservedSlot(this, ExportsSlot).isUndefined();
423 }
424
425 bool ModuleNamespaceObject::hasBindings() const {
426 // Import bindings may not be present if we hit OOM in initialization.
427 return !GetProxyReservedSlot(this, BindingsSlot).isUndefined();
428 }
429
430 bool ModuleNamespaceObject::addBinding(JSContext* cx,
431 Handle<JSAtom*> exportedName,
432 Handle<ModuleObject*> targetModule,
433 Handle<JSAtom*> targetName) {
434 Rooted<ModuleEnvironmentObject*> environment(
435 cx, &targetModule->initialEnvironment());
436 RootedId exportedNameId(cx, AtomToId(exportedName));
437 RootedId targetNameId(cx, AtomToId(targetName));
438 return bindings().put(cx, exportedNameId, environment, targetNameId);
439 }
440
441 constexpr char ModuleNamespaceObject::ProxyHandler::family = 0;
442
443 bool ModuleNamespaceObject::ProxyHandler::getPrototype(
444 JSContext* cx, HandleObject proxy, MutableHandleObject protop) const {
445 protop.set(nullptr);
446 return true;
447 }
448
449 bool ModuleNamespaceObject::ProxyHandler::setPrototype(
450 JSContext* cx, HandleObject proxy, HandleObject proto,
451 ObjectOpResult& result) const {
452 if (!proto) {
453 return result.succeed();
454 }
455 return result.failCantSetProto();
456 }
457
458 bool ModuleNamespaceObject::ProxyHandler::getPrototypeIfOrdinary(
459 JSContext* cx, HandleObject proxy, bool* isOrdinary,
460 MutableHandleObject protop) const {
461 *isOrdinary = false;
462 return true;
463 }
464
465 bool ModuleNamespaceObject::ProxyHandler::setImmutablePrototype(
466 JSContext* cx, HandleObject proxy, bool* succeeded) const {
467 *succeeded = true;
468 return true;
469 }
470
471 bool ModuleNamespaceObject::ProxyHandler::isExtensible(JSContext* cx,
472 HandleObject proxy,
473 bool* extensible) const {
474 *extensible = false;
475 return true;
476 }
477
478 bool ModuleNamespaceObject::ProxyHandler::preventExtensions(
479 JSContext* cx, HandleObject proxy, ObjectOpResult& result) const {
480 result.succeed();
481 return true;
482 }
483
484 bool ModuleNamespaceObject::ProxyHandler::getOwnPropertyDescriptor(
485 JSContext* cx, HandleObject proxy, HandleId id,
486 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) const {
487 Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
488 if (id.isSymbol()) {
489 if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
490 desc.set(Some(PropertyDescriptor::Data(StringValue(cx->names().Module))));
491 return true;
492 }
493
494 desc.reset();
495 return true;
496 }
497
498 const IndirectBindingMap& bindings = ns->bindings();
499 ModuleEnvironmentObject* env;
500 mozilla::Maybe<PropertyInfo> prop;
501 if (!bindings.lookup(id, &env, &prop)) {
502 // Not found.
503 desc.reset();
504 return true;
505 }
506
507 RootedValue value(cx, env->getSlot(prop->slot()));
508 if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
509 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
510 return false;
511 }
512
513 desc.set(
514 Some(PropertyDescriptor::Data(value, {JS::PropertyAttribute::Enumerable,
515 JS::PropertyAttribute::Writable})));
516 return true;
517 }
518
519 static bool ValidatePropertyDescriptor(
520 JSContext* cx, Handle<PropertyDescriptor> desc, bool expectedWritable,
521 bool expectedEnumerable, bool expectedConfigurable,
522 HandleValue expectedValue, ObjectOpResult& result) {
523 if (desc.isAccessorDescriptor()) {
524 return result.fail(JSMSG_CANT_REDEFINE_PROP);
525 }
526
527 if (desc.hasWritable() && desc.writable() != expectedWritable) {
528 return result.fail(JSMSG_CANT_REDEFINE_PROP);
529 }
530
531 if (desc.hasEnumerable() && desc.enumerable() != expectedEnumerable) {
532 return result.fail(JSMSG_CANT_REDEFINE_PROP);
533 }
534
535 if (desc.hasConfigurable() && desc.configurable() != expectedConfigurable) {
536 return result.fail(JSMSG_CANT_REDEFINE_PROP);
537 }
538
539 if (desc.hasValue()) {
540 bool same;
541 if (!SameValue(cx, desc.value(), expectedValue, &same)) {
542 return false;
543 }
544 if (!same) {
545 return result.fail(JSMSG_CANT_REDEFINE_PROP);
546 }
547 }
548
549 return result.succeed();
550 }
551
552 bool ModuleNamespaceObject::ProxyHandler::defineProperty(
553 JSContext* cx, HandleObject proxy, HandleId id,
554 Handle<PropertyDescriptor> desc, ObjectOpResult& result) const {
555 if (id.isSymbol()) {
556 if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
557 RootedValue value(cx, StringValue(cx->names().Module));
558 return ValidatePropertyDescriptor(cx, desc, false, false, false, value,
559 result);
560 }
561 return result.fail(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE);
562 }
563
564 const IndirectBindingMap& bindings =
565 proxy->as<ModuleNamespaceObject>().bindings();
566 ModuleEnvironmentObject* env;
567 mozilla::Maybe<PropertyInfo> prop;
568 if (!bindings.lookup(id, &env, &prop)) {
569 return result.fail(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE);
570 }
571
572 RootedValue value(cx, env->getSlot(prop->slot()));
573 if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
574 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
575 return false;
576 }
577
578 return ValidatePropertyDescriptor(cx, desc, true, true, false, value, result);
579 }
580
581 bool ModuleNamespaceObject::ProxyHandler::has(JSContext* cx, HandleObject proxy,
582 HandleId id, bool* bp) const {
583 Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
584 if (id.isSymbol()) {
585 *bp = id.isWellKnownSymbol(JS::SymbolCode::toStringTag);
586 return true;
587 }
588
589 *bp = ns->bindings().has(id);
590 return true;
591 }
592
593 bool ModuleNamespaceObject::ProxyHandler::get(JSContext* cx, HandleObject proxy,
594 HandleValue receiver, HandleId id,
595 MutableHandleValue vp) const {
596 Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
597 if (id.isSymbol()) {
598 if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
599 vp.setString(cx->names().Module);
600 return true;
601 }
602
603 vp.setUndefined();
604 return true;
605 }
606
607 ModuleEnvironmentObject* env;
608 mozilla::Maybe<PropertyInfo> prop;
609 if (!ns->bindings().lookup(id, &env, &prop)) {
610 vp.setUndefined();
611 return true;
612 }
613
614 RootedValue value(cx, env->getSlot(prop->slot()));
615 if (value.isMagic(JS_UNINITIALIZED_LEXICAL)) {
616 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
617 return false;
618 }
619
620 vp.set(value);
621 return true;
622 }
623
624 bool ModuleNamespaceObject::ProxyHandler::set(JSContext* cx, HandleObject proxy,
625 HandleId id, HandleValue v,
626 HandleValue receiver,
627 ObjectOpResult& result) const {
628 return result.failReadOnly();
629 }
630
631 bool ModuleNamespaceObject::ProxyHandler::delete_(
632 JSContext* cx, HandleObject proxy, HandleId id,
633 ObjectOpResult& result) const {
634 Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
635 if (id.isSymbol()) {
636 if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
637 return result.failCantDelete();
638 }
639
640 return result.succeed();
641 }
642
643 if (ns->bindings().has(id)) {
644 return result.failCantDelete();
645 }
646
647 return result.succeed();
648 }
649
650 bool ModuleNamespaceObject::ProxyHandler::ownPropertyKeys(
651 JSContext* cx, HandleObject proxy, MutableHandleIdVector props) const {
652 Rooted<ModuleNamespaceObject*> ns(cx, &proxy->as<ModuleNamespaceObject>());
653 uint32_t count = ns->exports().length();
654 if (!props.reserve(props.length() + count + 1)) {
655 return false;
656 }
657
658 for (JSAtom* atom : ns->exports()) {
659 props.infallibleAppend(AtomToId(atom));
660 }
661 props.infallibleAppend(
662 PropertyKey::Symbol(cx->wellKnownSymbols().toStringTag));
663
664 return true;
665 }
666
667 void ModuleNamespaceObject::ProxyHandler::trace(JSTracer* trc,
668 JSObject* proxy) const {
669 auto& self = proxy->as<ModuleNamespaceObject>();
670
671 if (self.hasExports()) {
672 self.mutableExports().trace(trc);
673 }
674
675 if (self.hasBindings()) {
676 self.bindings().trace(trc);
677 }
678 }
679
680 void ModuleNamespaceObject::ProxyHandler::finalize(JS::GCContext* gcx,
681 JSObject* proxy) const {
682 auto& self = proxy->as<ModuleNamespaceObject>();
683
684 if (self.hasExports()) {
685 gcx->delete_(proxy, &self.mutableExports(), MemoryUse::ModuleExports);
686 }
687
688 if (self.hasBindings()) {
689 gcx->delete_(proxy, &self.bindings(), MemoryUse::ModuleBindingMap);
690 }
691 }
692
693 ///////////////////////////////////////////////////////////////////////////
694 // SyntheticModuleFields
695
696 // The fields of a synthetic module record, as described in:
697 // https://tc39.es/proposal-json-modules/#sec-synthetic-module-records
698 class js::SyntheticModuleFields {
699 public:
700 ExportNameVector exportNames;
701
702 public:
703 void trace(JSTracer* trc);
704 };
705
706 void SyntheticModuleFields::trace(JSTracer* trc) { exportNames.trace(trc); }
707
708 ///////////////////////////////////////////////////////////////////////////
709 // CyclicModuleFields
710
711 // The fields of a cyclic module record, as described in:
712 // https://tc39.es/ecma262/#sec-cyclic-module-records
713 class js::CyclicModuleFields {
714 public:
715 ModuleStatus status = ModuleStatus::Unlinked;
716
717 bool hasTopLevelAwait : 1;
718
719 private:
720 // Flag bits that determine whether other fields are present.
721 bool hasDfsIndex : 1;
722 bool hasDfsAncestorIndex : 1;
723 bool isAsyncEvaluating : 1;
724 bool hasPendingAsyncDependencies : 1;
725
726 // Fields whose presence is conditional on the flag bits above.
727 uint32_t dfsIndex = 0;
728 uint32_t dfsAncestorIndex = 0;
729 uint32_t asyncEvaluatingPostOrder = 0;
730 uint32_t pendingAsyncDependencies = 0;
731
732 // Fields describing the layout of exportEntries.
733 uint32_t indirectExportEntriesStart = 0;
734 uint32_t starExportEntriesStart = 0;
735
736 public:
737 HeapPtr<Value> evaluationError;
738 HeapPtr<JSObject*> metaObject;
739 HeapPtr<ScriptSourceObject*> scriptSourceObject;
740 RequestedModuleVector requestedModules;
741 ImportEntryVector importEntries;
742 ExportEntryVector exportEntries;
743 IndirectBindingMap importBindings;
744 UniquePtr<FunctionDeclarationVector> functionDeclarations;
745 HeapPtr<PromiseObject*> topLevelCapability;
746 HeapPtr<ListObject*> asyncParentModules;
747 HeapPtr<ModuleObject*> cycleRoot;
748
749 public:
750 CyclicModuleFields();
751
752 void trace(JSTracer* trc);
753
754 void initExportEntries(MutableHandle<ExportEntryVector> allEntries,
755 uint32_t localExportCount,
756 uint32_t indirectExportCount,
757 uint32_t starExportCount);
758 Span<const ExportEntry> localExportEntries() const;
759 Span<const ExportEntry> indirectExportEntries() const;
760 Span<const ExportEntry> starExportEntries() const;
761
762 void setDfsIndex(uint32_t index);
763 Maybe<uint32_t> maybeDfsIndex() const;
764 void setDfsAncestorIndex(uint32_t index);
765 Maybe<uint32_t> maybeDfsAncestorIndex() const;
766 void clearDfsIndexes();
767
768 void setAsyncEvaluating(uint32_t postOrder);
769 bool getIsAsyncEvaluating() const;
770 Maybe<uint32_t> maybeAsyncEvaluatingPostOrder() const;
771 void clearAsyncEvaluatingPostOrder();
772
773 void setPendingAsyncDependencies(uint32_t newValue);
774 Maybe<uint32_t> maybePendingAsyncDependencies() const;
775 };
776
777 CyclicModuleFields::CyclicModuleFields()
778 : hasTopLevelAwait(false),
779 hasDfsIndex(false),
780 hasDfsAncestorIndex(false),
781 isAsyncEvaluating(false),
782 hasPendingAsyncDependencies(false) {}
783
784 void CyclicModuleFields::trace(JSTracer* trc) {
785 TraceEdge(trc, &evaluationError, "CyclicModuleFields::evaluationError");
786 TraceNullableEdge(trc, &metaObject, "CyclicModuleFields::metaObject");
787 TraceNullableEdge(trc, &scriptSourceObject,
788 "CyclicModuleFields::scriptSourceObject");
789 requestedModules.trace(trc);
790 importEntries.trace(trc);
791 exportEntries.trace(trc);
792 importBindings.trace(trc);
793 TraceNullableEdge(trc, &topLevelCapability,
794 "CyclicModuleFields::topLevelCapability");
795 TraceNullableEdge(trc, &asyncParentModules,
796 "CyclicModuleFields::asyncParentModules");
797 TraceNullableEdge(trc, &cycleRoot, "CyclicModuleFields::cycleRoot");
798 }
799
800 void CyclicModuleFields::initExportEntries(
801 MutableHandle<ExportEntryVector> allEntries, uint32_t localExportCount,
802 uint32_t indirectExportCount, uint32_t starExportCount) {
803 MOZ_ASSERT(allEntries.length() ==
804 localExportCount + indirectExportCount + starExportCount);
805
806 exportEntries = std::move(allEntries.get());
807 indirectExportEntriesStart = localExportCount;
808 starExportEntriesStart = indirectExportEntriesStart + indirectExportCount;
809 }
810
811 Span<const ExportEntry> CyclicModuleFields::localExportEntries() const {
812 MOZ_ASSERT(indirectExportEntriesStart <= exportEntries.length());
813 return Span(exportEntries.begin(),
814 exportEntries.begin() + indirectExportEntriesStart);
815 }
816
817 Span<const ExportEntry> CyclicModuleFields::indirectExportEntries() const {
818 MOZ_ASSERT(indirectExportEntriesStart <= starExportEntriesStart);
819 MOZ_ASSERT(starExportEntriesStart <= exportEntries.length());
820 return Span(exportEntries.begin() + indirectExportEntriesStart,
821 exportEntries.begin() + starExportEntriesStart);
822 }
823
824 Span<const ExportEntry> CyclicModuleFields::starExportEntries() const {
825 MOZ_ASSERT(starExportEntriesStart <= exportEntries.length());
826 return Span(exportEntries.begin() + starExportEntriesStart,
827 exportEntries.end());
828 }
829
830 void CyclicModuleFields::setDfsIndex(uint32_t index) {
831 dfsIndex = index;
832 hasDfsIndex = true;
833 }
834
835 Maybe<uint32_t> CyclicModuleFields::maybeDfsIndex() const {
836 return hasDfsIndex ? Some(dfsIndex) : Nothing();
837 }
838
839 void CyclicModuleFields::setDfsAncestorIndex(uint32_t index) {
840 dfsAncestorIndex = index;
841 hasDfsAncestorIndex = true;
842 }
843
844 Maybe<uint32_t> CyclicModuleFields::maybeDfsAncestorIndex() const {
845 return hasDfsAncestorIndex ? Some(dfsAncestorIndex) : Nothing();
846 }
847
848 void CyclicModuleFields::clearDfsIndexes() {
849 dfsIndex = 0;
850 hasDfsIndex = false;
851 dfsAncestorIndex = 0;
852 hasDfsAncestorIndex = false;
853 }
854
855 void CyclicModuleFields::setAsyncEvaluating(uint32_t postOrder) {
856 isAsyncEvaluating = true;
857 asyncEvaluatingPostOrder = postOrder;
858 }
859
860 bool CyclicModuleFields::getIsAsyncEvaluating() const {
861 return isAsyncEvaluating;
862 }
863
864 Maybe<uint32_t> CyclicModuleFields::maybeAsyncEvaluatingPostOrder() const {
865 if (!isAsyncEvaluating ||
866 asyncEvaluatingPostOrder == ASYNC_EVALUATING_POST_ORDER_CLEARED) {
867 return Nothing();
868 }
869
870 return Some(asyncEvaluatingPostOrder);
871 }
872
873 void CyclicModuleFields::clearAsyncEvaluatingPostOrder() {
874 asyncEvaluatingPostOrder = ASYNC_EVALUATING_POST_ORDER_CLEARED;
875 }
876
877 void CyclicModuleFields::setPendingAsyncDependencies(uint32_t newValue) {
878 pendingAsyncDependencies = newValue;
879 hasPendingAsyncDependencies = true;
880 }
881
882 Maybe<uint32_t> CyclicModuleFields::maybePendingAsyncDependencies() const {
883 return hasPendingAsyncDependencies ? Some(pendingAsyncDependencies)
884 : Nothing();
885 }
886
887 ///////////////////////////////////////////////////////////////////////////
888 // ModuleObject
889
890 /* static */ const JSClassOps ModuleObject::classOps_ = {
891 nullptr, // addProperty
892 nullptr, // delProperty
893 nullptr, // enumerate
894 nullptr, // newEnumerate
895 nullptr, // resolve
896 nullptr, // mayResolve
897 ModuleObject::finalize, // finalize
898 nullptr, // call
899 nullptr, // construct
900 ModuleObject::trace, // trace
901 };
902
903 /* static */ const JSClass ModuleObject::class_ = {
904 "Module",
905 JSCLASS_HAS_RESERVED_SLOTS(ModuleObject::SlotCount) |
906 JSCLASS_BACKGROUND_FINALIZE,
907 &ModuleObject::classOps_,
908 };
909
910 /* static */
911 bool ModuleObject::isInstance(HandleValue value) {
912 return value.isObject() && value.toObject().is<ModuleObject>();
913 }
914
915 bool ModuleObject::hasCyclicModuleFields() const {
916 bool result = !getReservedSlot(CyclicModuleFieldsSlot).isUndefined();
917 MOZ_ASSERT_IF(result, !hasSyntheticModuleFields());
918 return result;
919 }
920
921 CyclicModuleFields* ModuleObject::cyclicModuleFields() {
922 MOZ_ASSERT(hasCyclicModuleFields());
923 void* ptr = getReservedSlot(CyclicModuleFieldsSlot).toPrivate();
924 MOZ_ASSERT(ptr);
925 return static_cast<CyclicModuleFields*>(ptr);
926 }
927 const CyclicModuleFields* ModuleObject::cyclicModuleFields() const {
928 return const_cast<ModuleObject*>(this)->cyclicModuleFields();
929 }
930
931 Span<const RequestedModule> ModuleObject::requestedModules() const {
932 return cyclicModuleFields()->requestedModules;
933 }
934
935 Span<const ImportEntry> ModuleObject::importEntries() const {
936 return cyclicModuleFields()->importEntries;
937 }
938
939 Span<const ExportEntry> ModuleObject::localExportEntries() const {
940 return cyclicModuleFields()->localExportEntries();
941 }
942
943 Span<const ExportEntry> ModuleObject::indirectExportEntries() const {
944 return cyclicModuleFields()->indirectExportEntries();
945 }
946
947 Span<const ExportEntry> ModuleObject::starExportEntries() const {
948 return cyclicModuleFields()->starExportEntries();
949 }
950
951 const ExportNameVector& ModuleObject::syntheticExportNames() const {
952 return syntheticModuleFields()->exportNames;
953 }
954
955 void ModuleObject::initFunctionDeclarations(
956 UniquePtr<FunctionDeclarationVector> decls) {
957 cyclicModuleFields()->functionDeclarations = std::move(decls);
958 }
959
960 /* static */
961 ModuleObject* ModuleObject::create(JSContext* cx) {
962 Rooted<UniquePtr<CyclicModuleFields>> fields(cx);
963 fields = cx->make_unique<CyclicModuleFields>();
964 if (!fields) {
965 return nullptr;
966 }
967
968 Rooted<ModuleObject*> self(
969 cx, NewObjectWithGivenProto<ModuleObject>(cx, nullptr));
970 if (!self) {
971 return nullptr;
972 }
973
974 InitReservedSlot(self, CyclicModuleFieldsSlot, fields.release(),
975 MemoryUse::ModuleCyclicFields);
976
977 return self;
978 }
979
980 /* static */
981 ModuleObject* ModuleObject::createSynthetic(
982 JSContext* cx, MutableHandle<ExportNameVector> exportNames) {
983 Rooted<UniquePtr<SyntheticModuleFields>> syntheticFields(cx);
984 syntheticFields = cx->make_unique<SyntheticModuleFields>();
985 if (!syntheticFields) {
986 return nullptr;
987 }
988
989 Rooted<ModuleObject*> self(
990 cx, NewObjectWithGivenProto<ModuleObject>(cx, nullptr));
991 if (!self) {
992 return nullptr;
993 }
994
995 InitReservedSlot(self, SyntheticModuleFieldsSlot, syntheticFields.release(),
996 MemoryUse::ModuleSyntheticFields);
997
998 self->syntheticModuleFields()->exportNames = std::move(exportNames.get());
999
1000 return self;
1001 }
1002
1003 /* static */
1004 void ModuleObject::finalize(JS::GCContext* gcx, JSObject* obj) {
1005 ModuleObject* self = &obj->as<ModuleObject>();
1006 if (self->hasCyclicModuleFields()) {
1007 gcx->delete_(obj, self->cyclicModuleFields(),
1008 MemoryUse::ModuleCyclicFields);
1009 }
1010 if (self->hasSyntheticModuleFields()) {
1011 gcx->delete_(obj, self->syntheticModuleFields(),
1012 MemoryUse::ModuleSyntheticFields);
1013 }
1014 }
1015
1016 ModuleEnvironmentObject& ModuleObject::initialEnvironment() const {
1017 Value value = getReservedSlot(EnvironmentSlot);
1018 return value.toObject().as<ModuleEnvironmentObject>();
1019 }
1020
1021 ModuleEnvironmentObject* ModuleObject::environment() const {
1022 // Note that this it's valid to call this even if there was an error
1023 // evaluating the module.
1024
1025 // According to the spec the environment record is created during linking, but
1026 // we create it earlier than that.
1027 if (status() < ModuleStatus::Linked) {
1028 return nullptr;
1029 }
1030
1031 return &initialEnvironment();
1032 }
1033
1034 IndirectBindingMap& ModuleObject::importBindings() {
1035 return cyclicModuleFields()->importBindings;
1036 }
1037
1038 ModuleNamespaceObject* ModuleObject::namespace_() {
1039 Value value = getReservedSlot(NamespaceSlot);
1040 if (value.isUndefined()) {
1041 return nullptr;
1042 }
1043 return &value.toObject().as<ModuleNamespaceObject>();
1044 }
1045
1046 ScriptSourceObject* ModuleObject::scriptSourceObject() const {
1047 return cyclicModuleFields()->scriptSourceObject;
1048 }
1049
1050 void ModuleObject::initAsyncSlots(JSContext* cx, bool hasTopLevelAwait,
1051 Handle<ListObject*> asyncParentModules) {
1052 cyclicModuleFields()->hasTopLevelAwait = hasTopLevelAwait;
1053 cyclicModuleFields()->asyncParentModules = asyncParentModules;
1054 }
1055
1056 static uint32_t NextPostOrder(JSRuntime* rt) {
1057 uint32_t ordinal = rt->moduleAsyncEvaluatingPostOrder;
1058 MOZ_ASSERT(ordinal != ASYNC_EVALUATING_POST_ORDER_CLEARED);
1059 MOZ_ASSERT(ordinal < MAX_UINT32);
1060 rt->moduleAsyncEvaluatingPostOrder++;
1061 return ordinal;
1062 }
1063
1064 // Reset the runtime's moduleAsyncEvaluatingPostOrder counter when the last
1065 // module that was async evaluating is finished.
1066 //
1067 // The graph is not re-entrant and any future modules will be independent from
1068 // this one.
1069 static void MaybeResetPostOrderCounter(JSRuntime* rt,
1070 uint32_t finishedPostOrder) {
1071 if (rt->moduleAsyncEvaluatingPostOrder == finishedPostOrder + 1) {
1072 rt->moduleAsyncEvaluatingPostOrder = ASYNC_EVALUATING_POST_ORDER_INIT;
1073 }
1074 }
1075
1076 void ModuleObject::setAsyncEvaluating() {
1077 MOZ_ASSERT(!isAsyncEvaluating());
1078 uint32_t postOrder = NextPostOrder(runtimeFromMainThread());
1079 cyclicModuleFields()->setAsyncEvaluating(postOrder);
1080 }
1081
1082 void ModuleObject::initScriptSlots(HandleScript script) {
1083 MOZ_ASSERT(script);
1084 MOZ_ASSERT(script->sourceObject());
1085 MOZ_ASSERT(script->filename());
1086 initReservedSlot(ScriptSlot, PrivateGCThingValue(script));
1087 cyclicModuleFields()->scriptSourceObject = script->sourceObject();
1088 }
1089
1090 void ModuleObject::setInitialEnvironment(
1091 Handle<ModuleEnvironmentObject*> initialEnvironment) {
1092 initReservedSlot(EnvironmentSlot, ObjectValue(*initialEnvironment));
1093 }
1094
1095 void ModuleObject::initImportExportData(
1096 MutableHandle<RequestedModuleVector> requestedModules,
1097 MutableHandle<ImportEntryVector> importEntries,
1098 MutableHandle<ExportEntryVector> exportEntries, uint32_t localExportCount,
1099 uint32_t indirectExportCount, uint32_t starExportCount) {
1100 cyclicModuleFields()->requestedModules = std::move(requestedModules.get());
1101 cyclicModuleFields()->importEntries = std::move(importEntries.get());
1102 cyclicModuleFields()->initExportEntries(exportEntries, localExportCount,
1103 indirectExportCount, starExportCount);
1104 }
1105
1106 /* static */
1107 bool ModuleObject::Freeze(JSContext* cx, Handle<ModuleObject*> self) {
1108 return FreezeObject(cx, self);
1109 }
1110
1111 #ifdef DEBUG
1112 /* static */ inline bool ModuleObject::AssertFrozen(
1113 JSContext* cx, Handle<ModuleObject*> self) {
1114 bool frozen = false;
1115 if (!TestIntegrityLevel(cx, self, IntegrityLevel::Frozen, &frozen)) {
1116 return false;
1117 }
1118 MOZ_ASSERT(frozen);
1119
1120 return true;
1121 }
1122 #endif
1123
1124 JSScript* ModuleObject::maybeScript() const {
1125 Value value = getReservedSlot(ScriptSlot);
1126 if (value.isUndefined()) {
1127 return nullptr;
1128 }
1129 BaseScript* script = value.toGCThing()->as<BaseScript>();
1130 MOZ_ASSERT(script->hasBytecode(),
1131 "Module scripts should always have bytecode");
1132 return script->asJSScript();
1133 }
1134
1135 JSScript* ModuleObject::script() const {
1136 JSScript* ptr = maybeScript();
1137 MOZ_RELEASE_ASSERT(ptr);
1138 return ptr;
1139 }
1140
1141 const char* ModuleObject::filename() const {
1142 // The ScriptSlot will be cleared once the module is evaluated, so we try to
1143 // get the filename from cyclicModuleFields().
1144
1145 // TODO: Bug 1885483: Provide filename for JSON modules
1146 if (!hasCyclicModuleFields()) {
1147 return "(JSON module)";
1148 }
1149 return cyclicModuleFields()->scriptSourceObject->source()->filename();
1150 }
1151
1152 static inline void AssertValidModuleStatus(ModuleStatus status) {
1153 MOZ_ASSERT(status >= ModuleStatus::Unlinked &&
1154 status <= ModuleStatus::Evaluated_Error);
1155 }
1156
1157 ModuleStatus ModuleObject::status() const {
1158 // Always return `ModuleStatus::Evaluated` so we can assert a module's status
1159 // without checking which kind it is, even though synthetic modules don't have
1160 // this field according to the spec.
1161 if (hasSyntheticModuleFields()) {
1162 return ModuleStatus::Evaluated;
1163 }
1164
1165 ModuleStatus status = cyclicModuleFields()->status;
1166 AssertValidModuleStatus(status);
1167
1168 if (status == ModuleStatus::Evaluated_Error) {
1169 return ModuleStatus::Evaluated;
1170 }
1171
1172 return status;
1173 }
1174
1175 void ModuleObject::setStatus(ModuleStatus newStatus) {
1176 AssertValidModuleStatus(newStatus);
1177
1178 // Note that under OOM conditions we can fail the module linking process even
1179 // after modules have been marked as linked.
1180 MOZ_ASSERT((status() <= ModuleStatus::Linked &&
1181 newStatus == ModuleStatus::Unlinked) ||
1182 newStatus > status(),
1183 "New module status inconsistent with current status");
1184
1185 cyclicModuleFields()->status = newStatus;
1186 }
1187
1188 bool ModuleObject::hasTopLevelAwait() const {
1189 return cyclicModuleFields()->hasTopLevelAwait;
1190 }
1191
1192 bool ModuleObject::isAsyncEvaluating() const {
1193 return cyclicModuleFields()->getIsAsyncEvaluating();
1194 }
1195
1196 Maybe<uint32_t> ModuleObject::maybeDfsIndex() const {
1197 return cyclicModuleFields()->maybeDfsIndex();
1198 }
1199
1200 uint32_t ModuleObject::dfsIndex() const { return maybeDfsIndex().value(); }
1201
1202 void ModuleObject::setDfsIndex(uint32_t index) {
1203 cyclicModuleFields()->setDfsIndex(index);
1204 }
1205
1206 Maybe<uint32_t> ModuleObject::maybeDfsAncestorIndex() const {
1207 return cyclicModuleFields()->maybeDfsAncestorIndex();
1208 }
1209
1210 uint32_t ModuleObject::dfsAncestorIndex() const {
1211 return maybeDfsAncestorIndex().value();
1212 }
1213
1214 void ModuleObject::setDfsAncestorIndex(uint32_t index) {
1215 cyclicModuleFields()->setDfsAncestorIndex(index);
1216 }
1217
1218 void ModuleObject::clearDfsIndexes() {
1219 cyclicModuleFields()->clearDfsIndexes();
1220 }
1221
1222 PromiseObject* ModuleObject::maybeTopLevelCapability() const {
1223 return cyclicModuleFields()->topLevelCapability;
1224 }
1225
1226 PromiseObject* ModuleObject::topLevelCapability() const {
1227 PromiseObject* capability = maybeTopLevelCapability();
1228 MOZ_RELEASE_ASSERT(capability);
1229 return capability;
1230 }
1231
1232 // static
1233 PromiseObject* ModuleObject::createTopLevelCapability(
1234 JSContext* cx, Handle<ModuleObject*> module) {
1235 MOZ_ASSERT(!module->maybeTopLevelCapability());
1236
1237 Rooted<PromiseObject*> resultPromise(cx, CreatePromiseObjectForAsync(cx));
1238 if (!resultPromise) {
1239 return nullptr;
1240 }
1241
1242 module->setInitialTopLevelCapability(resultPromise);
1243 return resultPromise;
1244 }
1245
1246 void ModuleObject::setInitialTopLevelCapability(
1247 Handle<PromiseObject*> capability) {
1248 cyclicModuleFields()->topLevelCapability = capability;
1249 }
1250
1251 ListObject* ModuleObject::asyncParentModules() const {
1252 return cyclicModuleFields()->asyncParentModules;
1253 }
1254
1255 bool ModuleObject::appendAsyncParentModule(JSContext* cx,
1256 Handle<ModuleObject*> self,
1257 Handle<ModuleObject*> parent) {
1258 Rooted<Value> parentValue(cx, ObjectValue(*parent));
1259 return self->asyncParentModules()->append(cx, parentValue);
1260 }
1261
1262 Maybe<uint32_t> ModuleObject::maybePendingAsyncDependencies() const {
1263 return cyclicModuleFields()->maybePendingAsyncDependencies();
1264 }
1265
1266 uint32_t ModuleObject::pendingAsyncDependencies() const {
1267 return maybePendingAsyncDependencies().value();
1268 }
1269
1270 Maybe<uint32_t> ModuleObject::maybeAsyncEvaluatingPostOrder() const {
1271 return cyclicModuleFields()->maybeAsyncEvaluatingPostOrder();
1272 }
1273
1274 uint32_t ModuleObject::getAsyncEvaluatingPostOrder() const {
1275 return cyclicModuleFields()->maybeAsyncEvaluatingPostOrder().value();
1276 }
1277
1278 void ModuleObject::clearAsyncEvaluatingPostOrder() {
1279 MOZ_ASSERT(status() == ModuleStatus::Evaluated);
1280
1281 JSRuntime* rt = runtimeFromMainThread();
1282 MaybeResetPostOrderCounter(rt, getAsyncEvaluatingPostOrder());
1283
1284 cyclicModuleFields()->clearAsyncEvaluatingPostOrder();
1285 }
1286
1287 void ModuleObject::setPendingAsyncDependencies(uint32_t newValue) {
1288 cyclicModuleFields()->setPendingAsyncDependencies(newValue);
1289 }
1290
1291 void ModuleObject::setCycleRoot(ModuleObject* cycleRoot) {
1292 cyclicModuleFields()->cycleRoot = cycleRoot;
1293 }
1294
1295 ModuleObject* ModuleObject::getCycleRoot() const {
1296 MOZ_RELEASE_ASSERT(cyclicModuleFields()->cycleRoot);
1297 return cyclicModuleFields()->cycleRoot;
1298 }
1299
1300 bool ModuleObject::hasSyntheticModuleFields() const {
1301 bool result = !getReservedSlot(SyntheticModuleFieldsSlot).isUndefined();
1302 MOZ_ASSERT_IF(result, !hasCyclicModuleFields());
1303 return result;
1304 }
1305
1306 SyntheticModuleFields* ModuleObject::syntheticModuleFields() {
1307 MOZ_ASSERT(!hasCyclicModuleFields());
1308 void* ptr = getReservedSlot(SyntheticModuleFieldsSlot).toPrivate();
1309 MOZ_ASSERT(ptr);
1310 return static_cast<SyntheticModuleFields*>(ptr);
1311 }
1312 const SyntheticModuleFields* ModuleObject::syntheticModuleFields() const {
1313 return const_cast<ModuleObject*>(this)->syntheticModuleFields();
1314 }
1315
1316 bool ModuleObject::hasTopLevelCapability() const {
1317 return cyclicModuleFields()->topLevelCapability;
1318 }
1319
1320 bool ModuleObject::hadEvaluationError() const {
1321 if (hasSyntheticModuleFields()) {
1322 return false;
1323 }
1324
1325 ModuleStatus fullStatus = cyclicModuleFields()->status;
1326 return fullStatus == ModuleStatus::Evaluated_Error;
1327 }
1328
1329 void ModuleObject::setEvaluationError(HandleValue newValue) {
1330 MOZ_ASSERT(status() != ModuleStatus::Unlinked);
1331 MOZ_ASSERT(!hadEvaluationError());
1332
1333 cyclicModuleFields()->status = ModuleStatus::Evaluated_Error;
1334 cyclicModuleFields()->evaluationError = newValue;
1335
1336 MOZ_ASSERT(status() == ModuleStatus::Evaluated);
1337 MOZ_ASSERT(hadEvaluationError());
1338 }
1339
1340 Value ModuleObject::maybeEvaluationError() const {
1341 return cyclicModuleFields()->evaluationError;
1342 }
1343
1344 Value ModuleObject::evaluationError() const {
1345 MOZ_ASSERT(hadEvaluationError());
1346 return maybeEvaluationError();
1347 }
1348
1349 JSObject* ModuleObject::metaObject() const {
1350 return cyclicModuleFields()->metaObject;
1351 }
1352
1353 void ModuleObject::setMetaObject(JSObject* obj) {
1354 MOZ_ASSERT(obj);
1355 MOZ_ASSERT(!metaObject());
1356 cyclicModuleFields()->metaObject = obj;
1357 }
1358
1359 /* static */
1360 void ModuleObject::trace(JSTracer* trc, JSObject* obj) {
1361 ModuleObject& module = obj->as<ModuleObject>();
1362 if (module.hasCyclicModuleFields()) {
1363 module.cyclicModuleFields()->trace(trc);
1364 }
1365 if (module.hasSyntheticModuleFields()) {
1366 module.syntheticModuleFields()->trace(trc);
1367 }
1368 }
1369
1370 /* static */
1371 bool ModuleObject::instantiateFunctionDeclarations(JSContext* cx,
1372 Handle<ModuleObject*> self) {
1373 #ifdef DEBUG
1374 MOZ_ASSERT(self->status() == ModuleStatus::Linking);
1375 if (!AssertFrozen(cx, self)) {
1376 return false;
1377 }
1378 #endif
1379 // |self| initially manages this vector.
1380 UniquePtr<FunctionDeclarationVector>& funDecls =
1381 self->cyclicModuleFields()->functionDeclarations;
1382 if (!funDecls) {
1383 JS_ReportErrorASCII(
1384 cx, "Module function declarations have already been instantiated");
1385 return false;
1386 }
1387
1388 Rooted<ModuleEnvironmentObject*> env(cx, &self->initialEnvironment());
1389 RootedObject obj(cx);
1390 RootedValue value(cx);
1391 RootedFunction fun(cx);
1392 Rooted<PropertyName*> name(cx);
1393
1394 for (GCThingIndex funIndex : *funDecls) {
1395 fun.set(self->script()->getFunction(funIndex));
1396 obj = Lambda(cx, fun, env);
1397 if (!obj) {
1398 return false;
1399 }
1400
1401 name = fun->fullExplicitName()->asPropertyName();
1402 value = ObjectValue(*obj);
1403 if (!SetProperty(cx, env, name, value)) {
1404 return false;
1405 }
1406 }
1407
1408 // Free the vector, now its contents are no longer needed.
1409 funDecls.reset();
1410
1411 return true;
1412 }
1413
1414 /* static */
1415 bool ModuleObject::execute(JSContext* cx, Handle<ModuleObject*> self) {
1416 #ifdef DEBUG
1417 MOZ_ASSERT(self->status() == ModuleStatus::Evaluating ||
1418 self->status() == ModuleStatus::EvaluatingAsync ||
1419 self->status() == ModuleStatus::Evaluated);
1420 MOZ_ASSERT(!self->hadEvaluationError());
1421 if (!AssertFrozen(cx, self)) {
1422 return false;
1423 }
1424 #endif
1425
1426 RootedScript script(cx, self->script());
1427
1428 auto guardA = mozilla::MakeScopeExit([&] {
1429 if (self->hasTopLevelAwait()) {
1430 // Handled in AsyncModuleExecutionFulfilled and
1431 // AsyncModuleExecutionRejected.
1432 return;
1433 }
1434 ModuleObject::onTopLevelEvaluationFinished(self);
1435 });
1436
1437 Rooted<ModuleEnvironmentObject*> env(cx, self->environment());
1438 if (!env) {
1439 JS_ReportErrorASCII(cx,
1440 "Module declarations have not yet been instantiated");
1441 return false;
1442 }
1443
1444 Rooted<Value> ignored(cx);
1445 return Execute(cx, script, env, &ignored);
1446 }
1447
1448 /* static */
1449 void ModuleObject::onTopLevelEvaluationFinished(ModuleObject* module) {
1450 // ScriptSlot is used by debugger to access environments during evaluating
1451 // the top-level script.
1452 // Clear the reference at exit to prevent us keeping this alive unnecessarily.
1453 module->setReservedSlot(ScriptSlot, UndefinedValue());
1454 }
1455
1456 /* static */
1457 ModuleNamespaceObject* ModuleObject::createNamespace(
1458 JSContext* cx, Handle<ModuleObject*> self,
1459 MutableHandle<UniquePtr<ExportNameVector>> exports) {
1460 MOZ_ASSERT(!self->namespace_());
1461
1462 Rooted<UniquePtr<IndirectBindingMap>> bindings(cx);
1463 bindings = cx->make_unique<IndirectBindingMap>();
1464 if (!bindings) {
1465 return nullptr;
1466 }
1467
1468 auto* ns = ModuleNamespaceObject::create(cx, self, exports, &bindings);
1469 if (!ns) {
1470 return nullptr;
1471 }
1472
1473 self->initReservedSlot(NamespaceSlot, ObjectValue(*ns));
1474 return ns;
1475 }
1476
1477 void ModuleObject::clearNamespaceOnFailure() {
1478 setReservedSlot(NamespaceSlot, UndefinedValue());
1479 }
1480
1481 /* static */
1482 bool ModuleObject::createEnvironment(JSContext* cx,
1483 Handle<ModuleObject*> self) {
1484 Rooted<ModuleEnvironmentObject*> env(
1485 cx, ModuleEnvironmentObject::create(cx, self));
1486 if (!env) {
1487 return false;
1488 }
1489
1490 self->setInitialEnvironment(env);
1491 return true;
1492 }
1493
1494 /*static*/
1495 bool ModuleObject::createSyntheticEnvironment(JSContext* cx,
1496 Handle<ModuleObject*> self,
1497 JS::HandleVector<Value> values) {
1498 Rooted<ModuleEnvironmentObject*> env(
1499 cx, ModuleEnvironmentObject::createSynthetic(cx, self));
1500 if (!env) {
1501 return false;
1502 }
1503
1504 // We expect one property per synthetic value plus one for the *namespace*
1505 // binding.
1506 MOZ_ASSERT(env->shape()->propMapLength() == values.length() + 1);
1507
1508 for (uint32_t i = 0; i < values.length(); i++) {
1509 env->setAliasedBinding(env->firstSyntheticValueSlot() + i, values[i]);
1510 }
1511
1512 self->setInitialEnvironment(env);
1513
1514 return true;
1515 }
1516
1517 ///////////////////////////////////////////////////////////////////////////
1518 // ModuleBuilder
1519
1520 ModuleBuilder::ModuleBuilder(FrontendContext* fc,
1521 const frontend::EitherParser& eitherParser)
1522 : fc_(fc),
1523 eitherParser_(eitherParser),
1524 requestedModuleIndexes_(fc),
1525 importEntries_(fc),
1526 exportEntries_(fc),
1527 exportNames_(fc) {}
1528
1529 bool ModuleBuilder::noteFunctionDeclaration(FrontendContext* fc,
1530 uint32_t funIndex) {
1531 if (!functionDecls_.emplaceBack(funIndex)) {
1532 js::ReportOutOfMemory(fc);
1533 return false;
1534 }
1535 return true;
1536 }
1537
1538 void ModuleBuilder::noteAsync(frontend::StencilModuleMetadata& metadata) {
1539 metadata.isAsync = true;
1540 }
1541
1542 bool ModuleBuilder::buildTables(frontend::StencilModuleMetadata& metadata) {
1543 // https://tc39.es/ecma262/#sec-parsemodule
1544 // 15.2.1.17.1 ParseModule, Steps 4-11.
1545
1546 // Step 4.
1547 metadata.moduleRequests = std::move(moduleRequests_);
1548 metadata.requestedModules = std::move(requestedModules_);
1549
1550 // Step 5.
1551 if (!metadata.importEntries.reserve(importEntries_.count())) {
1552 js::ReportOutOfMemory(fc_);
1553 return false;
1554 }
1555 for (auto r = importEntries_.all(); !r.empty(); r.popFront()) {
1556 frontend::StencilModuleEntry& entry = r.front().value();
1557 metadata.importEntries.infallibleAppend(entry);
1558 }
1559
1560 // Steps 6-11.
1561 for (const frontend::StencilModuleEntry& exp : exportEntries_) {
1562 if (!exp.moduleRequest) {
1563 frontend::StencilModuleEntry* importEntry = importEntryFor(exp.localName);
1564 if (!importEntry) {
1565 if (!metadata.localExportEntries.append(exp)) {
1566 js::ReportOutOfMemory(fc_);
1567 return false;
1568 }
1569 } else {
1570 if (!importEntry->importName) {
1571 if (!metadata.localExportEntries.append(exp)) {
1572 js::ReportOutOfMemory(fc_);
1573 return false;
1574 }
1575 } else {
1576 // All names should have already been marked as used-by-stencil.
1577 auto entry = frontend::StencilModuleEntry::exportFromEntry(
1578 importEntry->moduleRequest, importEntry->importName,
1579 exp.exportName, exp.lineno, exp.column);
1580 if (!metadata.indirectExportEntries.append(entry)) {
1581 js::ReportOutOfMemory(fc_);
1582 return false;
1583 }
1584 }
1585 }
1586 } else if (!exp.importName && !exp.exportName) {
1587 if (!metadata.starExportEntries.append(exp)) {
1588 js::ReportOutOfMemory(fc_);
1589 return false;
1590 }
1591 } else {
1592 if (!metadata.indirectExportEntries.append(exp)) {
1593 js::ReportOutOfMemory(fc_);
1594 return false;
1595 }
1596 }
1597 }
1598
1599 return true;
1600 }
1601
1602 void ModuleBuilder::finishFunctionDecls(
1603 frontend::StencilModuleMetadata& metadata) {
1604 metadata.functionDecls = std::move(functionDecls_);
1605 }
1606
1607 bool frontend::StencilModuleMetadata::createModuleRequestObjects(
1608 JSContext* cx, CompilationAtomCache& atomCache,
1609 MutableHandle<ModuleRequestVector> output) const {
1610 if (!output.reserve(moduleRequests.length())) {
1611 ReportOutOfMemory(cx);
1612 return false;
1613 }
1614
1615 Rooted<ModuleRequestObject*> object(cx);
1616 for (const StencilModuleRequest& request : moduleRequests) {
1617 object = createModuleRequestObject(cx, atomCache, request);
1618 if (!object) {
1619 return false;
1620 }
1621
1622 output.infallibleEmplaceBack(object);
1623 }
1624
1625 return true;
1626 }
1627
1628 ModuleRequestObject* frontend::StencilModuleMetadata::createModuleRequestObject(
1629 JSContext* cx, CompilationAtomCache& atomCache,
1630 const StencilModuleRequest& request) const {
1631 uint32_t numberOfAttributes = request.attributes.length();
1632
1633 Rooted<ImportAttributeVector> attributes(cx);
1634 if (numberOfAttributes > 0) {
1635 if (!attributes.reserve(numberOfAttributes)) {
1636 ReportOutOfMemory(cx);
1637 return nullptr;
1638 }
1639
1640 Rooted<JSAtom*> attributeKey(cx);
1641 Rooted<JSAtom*> attributeValue(cx);
1642 for (uint32_t j = 0; j < numberOfAttributes; ++j) {
1643 attributeKey = atomCache.getExistingAtomAt(cx, request.attributes[j].key);
1644 attributeValue =
1645 atomCache.getExistingAtomAt(cx, request.attributes[j].value);
1646
1647 attributes.infallibleEmplaceBack(attributeKey, attributeValue);
1648 }
1649 }
1650
1651 Rooted<JSAtom*> specifier(cx,
1652 atomCache.getExistingAtomAt(cx, request.specifier));
1653 MOZ_ASSERT(specifier);
1654
1655 Rooted<ModuleRequestObject*> moduleRequestObject(
1656 cx, ModuleRequestObject::create(cx, specifier, attributes));
1657 if (!moduleRequestObject) {
1658 return nullptr;
1659 }
1660
1661 if (request.firstUnsupportedAttributeKey) {
1662 Rooted<JSAtom*> unsupportedAttributeKey(
1663 cx,
1664 atomCache.getExistingAtomAt(cx, request.firstUnsupportedAttributeKey));
1665 moduleRequestObject->setFirstUnsupportedAttributeKey(
1666 unsupportedAttributeKey);
1667 }
1668
1669 return moduleRequestObject;
1670 }
1671
1672 bool frontend::StencilModuleMetadata::createImportEntries(
1673 JSContext* cx, CompilationAtomCache& atomCache,
1674 Handle<ModuleRequestVector> moduleRequests,
1675 MutableHandle<ImportEntryVector> output) const {
1676 if (!output.reserve(importEntries.length())) {
1677 ReportOutOfMemory(cx);
1678 return false;
1679 }
1680
1681 for (const StencilModuleEntry& entry : importEntries) {
1682 Rooted<ModuleRequestObject*> moduleRequest(cx);
1683 moduleRequest = moduleRequests[entry.moduleRequest.value()].get();
1684 MOZ_ASSERT(moduleRequest);
1685
1686 Rooted<JSAtom*> localName(cx);
1687 if (entry.localName) {
1688 localName = atomCache.getExistingAtomAt(cx, entry.localName);
1689 MOZ_ASSERT(localName);
1690 }
1691
1692 Rooted<JSAtom*> importName(cx);
1693 if (entry.importName) {
1694 importName = atomCache.getExistingAtomAt(cx, entry.importName);
1695 MOZ_ASSERT(importName);
1696 }
1697
1698 MOZ_ASSERT(!entry.exportName);
1699
1700 output.infallibleEmplaceBack(moduleRequest, importName, localName,
1701 entry.lineno, entry.column);
1702 }
1703
1704 return true;
1705 }
1706
1707 bool frontend::StencilModuleMetadata::createExportEntries(
1708 JSContext* cx, frontend::CompilationAtomCache& atomCache,
1709 Handle<ModuleRequestVector> moduleRequests,
1710 const frontend::StencilModuleMetadata::EntryVector& input,
1711 MutableHandle<ExportEntryVector> output) const {
1712 if (!output.reserve(output.length() + input.length())) {
1713 ReportOutOfMemory(cx);
1714 return false;
1715 }
1716
1717 for (const frontend::StencilModuleEntry& entry : input) {
1718 Rooted<JSAtom*> exportName(cx);
1719 if (entry.exportName) {
1720 exportName = atomCache.getExistingAtomAt(cx, entry.exportName);
1721 MOZ_ASSERT(exportName);
1722 }
1723
1724 Rooted<ModuleRequestObject*> moduleRequestObject(cx);
1725 if (entry.moduleRequest) {
1726 moduleRequestObject = moduleRequests[entry.moduleRequest.value()].get();
1727 MOZ_ASSERT(moduleRequestObject);
1728 }
1729
1730 Rooted<JSAtom*> localName(cx);
1731 if (entry.localName) {
1732 localName = atomCache.getExistingAtomAt(cx, entry.localName);
1733 MOZ_ASSERT(localName);
1734 }
1735
1736 Rooted<JSAtom*> importName(cx);
1737 if (entry.importName) {
1738 importName = atomCache.getExistingAtomAt(cx, entry.importName);
1739 MOZ_ASSERT(importName);
1740 }
1741
1742 output.infallibleEmplaceBack(exportName, moduleRequestObject, importName,
1743 localName, entry.lineno, entry.column);
1744 }
1745
1746 return true;
1747 }
1748
1749 bool frontend::StencilModuleMetadata::createRequestedModules(
1750 JSContext* cx, CompilationAtomCache& atomCache,
1751 Handle<ModuleRequestVector> moduleRequests,
1752 MutableHandle<RequestedModuleVector> output) const {
1753 if (!output.reserve(requestedModules.length())) {
1754 ReportOutOfMemory(cx);
1755 return false;
1756 }
1757
1758 for (const frontend::StencilModuleEntry& entry : requestedModules) {
1759 Rooted<ModuleRequestObject*> moduleRequest(cx);
1760 moduleRequest = moduleRequests[entry.moduleRequest.value()].get();
1761 MOZ_ASSERT(moduleRequest);
1762
1763 MOZ_ASSERT(!entry.localName);
1764 MOZ_ASSERT(!entry.importName);
1765 MOZ_ASSERT(!entry.exportName);
1766
1767 output.infallibleEmplaceBack(moduleRequest, entry.lineno, entry.column);
1768 }
1769
1770 return true;
1771 }
1772
1773 // Use StencilModuleMetadata data to fill in ModuleObject
1774 bool frontend::StencilModuleMetadata::initModule(
1775 JSContext* cx, FrontendContext* fc,
1776 frontend::CompilationAtomCache& atomCache,
1777 JS::Handle<ModuleObject*> module) const {
1778 Rooted<ModuleRequestVector> moduleRequestsVector(cx);
1779 if (!createModuleRequestObjects(cx, atomCache, &moduleRequestsVector)) {
1780 return false;
1781 }
1782
1783 Rooted<RequestedModuleVector> requestedModulesVector(cx);
1784 if (!createRequestedModules(cx, atomCache, moduleRequestsVector,
1785 &requestedModulesVector)) {
1786 return false;
1787 }
1788
1789 Rooted<ImportEntryVector> importEntriesVector(cx);
1790 if (!createImportEntries(cx, atomCache, moduleRequestsVector,
1791 &importEntriesVector)) {
1792 return false;
1793 }
1794
1795 Rooted<ExportEntryVector> exportEntriesVector(cx);
1796 if (!createExportEntries(cx, atomCache, moduleRequestsVector,
1797 localExportEntries, &exportEntriesVector)) {
1798 return false;
1799 }
1800
1801 Rooted<ExportEntryVector> indirectExportEntriesVector(cx);
1802 if (!createExportEntries(cx, atomCache, moduleRequestsVector,
1803 indirectExportEntries, &exportEntriesVector)) {
1804 return false;
1805 }
1806
1807 Rooted<ExportEntryVector> starExportEntriesVector(cx);
1808 if (!createExportEntries(cx, atomCache, moduleRequestsVector,
1809 starExportEntries, &exportEntriesVector)) {
1810 return false;
1811 }
1812
1813 // Copy the vector of declarations to the ModuleObject.
1814 auto functionDeclsCopy = MakeUnique<FunctionDeclarationVector>();
1815 if (!functionDeclsCopy || !functionDeclsCopy->appendAll(functionDecls)) {
1816 js::ReportOutOfMemory(fc);
1817 return false;
1818 }
1819 module->initFunctionDeclarations(std::move(functionDeclsCopy));
1820
1821 Rooted<ListObject*> asyncParentModulesList(cx, ListObject::create(cx));
1822 if (!asyncParentModulesList) {
1823 return false;
1824 }
1825
1826 module->initAsyncSlots(cx, isAsync, asyncParentModulesList);
1827
1828 module->initImportExportData(
1829 &requestedModulesVector, &importEntriesVector, &exportEntriesVector,
1830 localExportEntries.length(), indirectExportEntries.length(),
1831 starExportEntries.length());
1832
1833 return true;
1834 }
1835
1836 bool ModuleBuilder::processAttributes(frontend::StencilModuleRequest& request,
1837 frontend::ListNode* attributeList) {
1838 using namespace js::frontend;
1839
1840 for (ParseNode* attributeItem : attributeList->contents()) {
1841 BinaryNode* attribute = &attributeItem->as<BinaryNode>();
1842 MOZ_ASSERT(attribute->isKind(ParseNodeKind::ImportAttribute));
1843
1844 auto key = attribute->left()->as<NameNode>().atom();
1845 markUsedByStencil(key);
1846
1847 // Note: This should be driven by a host hook
1848 // (HostGetSupportedImportAttributes), however the infrastructure of said
1849 // host hook is deeply unclear, and so right now embedders will not have
1850 // the ability to alter or extend the set of supported attributes.
1851 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1840723.
1852 if (key == TaggedParserAtomIndex::WellKnown::type()) {
1853 auto value = attribute->right()->as<NameNode>().atom();
1854 markUsedByStencil(value);
1855
1856 StencilModuleImportAttribute attributeStencil(key, value);
1857 if (!request.attributes.append(attributeStencil)) {
1858 js::ReportOutOfMemory(fc_);
1859 return false;
1860 }
1861 } else {
1862 if (!request.firstUnsupportedAttributeKey) {
1863 request.firstUnsupportedAttributeKey = key;
1864 }
1865 }
1866 }
1867
1868 return true;
1869 }
1870
1871 bool ModuleBuilder::processImport(frontend::BinaryNode* importNode) {
1872 using namespace js::frontend;
1873
1874 MOZ_ASSERT(importNode->isKind(ParseNodeKind::ImportDecl));
1875
1876 auto* specList = &importNode->left()->as<ListNode>();
1877 MOZ_ASSERT(specList->isKind(ParseNodeKind::ImportSpecList));
1878
1879 auto* moduleRequest = &importNode->right()->as<BinaryNode>();
1880 MOZ_ASSERT(moduleRequest->isKind(ParseNodeKind::ImportModuleRequest));
1881
1882 auto* moduleSpec = &moduleRequest->left()->as<NameNode>();
1883 MOZ_ASSERT(moduleSpec->isKind(ParseNodeKind::StringExpr));
1884
1885 auto* attributeList = &moduleRequest->right()->as<ListNode>();
1886 MOZ_ASSERT(attributeList->isKind(ParseNodeKind::ImportAttributeList));
1887
1888 auto specifier = moduleSpec->atom();
1889 MaybeModuleRequestIndex moduleRequestIndex =
1890 appendModuleRequest(specifier, attributeList);
1891 if (!moduleRequestIndex.isSome()) {
1892 return false;
1893 }
1894
1895 if (!maybeAppendRequestedModule(moduleRequestIndex, moduleSpec)) {
1896 return false;
1897 }
1898
1899 for (ParseNode* item : specList->contents()) {
1900 uint32_t line;
1901 JS::LimitedColumnNumberOneOrigin column;
1902 eitherParser_.computeLineAndColumn(item->pn_pos.begin, &line, &column);
1903
1904 StencilModuleEntry entry;
1905 TaggedParserAtomIndex localName;
1906 if (item->isKind(ParseNodeKind::ImportSpec)) {
1907 auto* spec = &item->as<BinaryNode>();
1908
1909 auto* importNameNode = &spec->left()->as<NameNode>();
1910 auto* localNameNode = &spec->right()->as<NameNode>();
1911
1912 auto importName = importNameNode->atom();
1913 localName = localNameNode->atom();
1914
1915 markUsedByStencil(localName);
1916 markUsedByStencil(importName);
1917 entry = StencilModuleEntry::importEntry(
1918 moduleRequestIndex, localName, importName, line,
1919 JS::ColumnNumberOneOrigin(column));
1920 } else {
1921 MOZ_ASSERT(item->isKind(ParseNodeKind::ImportNamespaceSpec));
1922 auto* spec = &item->as<UnaryNode>();
1923
1924 auto* localNameNode = &spec->kid()->as<NameNode>();
1925
1926 localName = localNameNode->atom();
1927
1928 markUsedByStencil(localName);
1929 entry = StencilModuleEntry::importNamespaceEntry(
1930 moduleRequestIndex, localName, line,
1931 JS::ColumnNumberOneOrigin(column));
1932 }
1933
1934 if (!importEntries_.put(localName, entry)) {
1935 return false;
1936 }
1937 }
1938
1939 return true;
1940 }
1941
1942 bool ModuleBuilder::processExport(frontend::ParseNode* exportNode) {
1943 using namespace js::frontend;
1944
1945 MOZ_ASSERT(exportNode->isKind(ParseNodeKind::ExportStmt) ||
1946 exportNode->isKind(ParseNodeKind::ExportDefaultStmt));
1947
1948 bool isDefault = exportNode->isKind(ParseNodeKind::ExportDefaultStmt);
1949 ParseNode* kid = isDefault ? exportNode->as<BinaryNode>().left()
1950 : exportNode->as<UnaryNode>().kid();
1951
1952 if (isDefault && exportNode->as<BinaryNode>().right()) {
1953 // This is an export default containing an expression.
1954 auto localName = TaggedParserAtomIndex::WellKnown::default_();
1955 auto exportName = TaggedParserAtomIndex::WellKnown::default_();
1956 return appendExportEntry(exportName, localName);
1957 }
1958
1959 switch (kid->getKind()) {
1960 case ParseNodeKind::ExportSpecList: {
1961 MOZ_ASSERT(!isDefault);
1962 for (ParseNode* item : kid->as<ListNode>().contents()) {
1963 BinaryNode* spec = &item->as<BinaryNode>();
1964 MOZ_ASSERT(spec->isKind(ParseNodeKind::ExportSpec));
1965
1966 NameNode* localNameNode = &spec->left()->as<NameNode>();
1967 NameNode* exportNameNode = &spec->right()->as<NameNode>();
1968
1969 auto localName = localNameNode->atom();
1970 auto exportName = exportNameNode->atom();
1971
1972 if (!appendExportEntry(exportName, localName, spec)) {
1973 return false;
1974 }
1975 }
1976 break;
1977 }
1978
1979 case ParseNodeKind::ClassDecl: {
1980 const ClassNode& cls = kid->as<ClassNode>();
1981 MOZ_ASSERT(cls.names());
1982 auto localName = cls.names()->innerBinding()->atom();
1983 auto exportName =
1984 isDefault ? TaggedParserAtomIndex::WellKnown::default_() : localName;
1985 if (!appendExportEntry(exportName, localName)) {
1986 return false;
1987 }
1988 break;
1989 }
1990
1991 case ParseNodeKind::VarStmt:
1992 case ParseNodeKind::ConstDecl:
1993 case ParseNodeKind::LetDecl: {
1994 for (ParseNode* binding : kid->as<ListNode>().contents()) {
1995 if (binding->isKind(ParseNodeKind::AssignExpr)) {
1996 binding = binding->as<AssignmentNode>().left();
1997 } else {
1998 MOZ_ASSERT(binding->isKind(ParseNodeKind::Name));
1999 }
2000
2001 if (binding->isKind(ParseNodeKind::Name)) {
2002 auto localName = binding->as<NameNode>().atom();
2003 auto exportName = isDefault
2004 ? TaggedParserAtomIndex::WellKnown::default_()
2005 : localName;
2006 if (!appendExportEntry(exportName, localName)) {
2007 return false;
2008 }
2009 } else if (binding->isKind(ParseNodeKind::ArrayExpr)) {
2010 if (!processExportArrayBinding(&binding->as<ListNode>())) {
2011 return false;
2012 }
2013 } else {
2014 MOZ_ASSERT(binding->isKind(ParseNodeKind::ObjectExpr));
2015 if (!processExportObjectBinding(&binding->as<ListNode>())) {
2016 return false;
2017 }
2018 }
2019 }
2020 break;
2021 }
2022
2023 case ParseNodeKind::Function: {
2024 FunctionBox* box = kid->as<FunctionNode>().funbox();
2025 MOZ_ASSERT(!box->isArrow());
2026 auto localName = box->explicitName();
2027 auto exportName =
2028 isDefault ? TaggedParserAtomIndex::WellKnown::default_() : localName;
2029 if (!appendExportEntry(exportName, localName)) {
2030 return false;
2031 }
2032 break;
2033 }
2034
2035 default:
2036 MOZ_CRASH("Unexpected parse node");
2037 }
2038
2039 return true;
2040 }
2041
2042 bool ModuleBuilder::processExportBinding(frontend::ParseNode* binding) {
2043 using namespace js::frontend;
2044
2045 if (binding->isKind(ParseNodeKind::Name)) {
2046 auto name = binding->as<NameNode>().atom();
2047 return appendExportEntry(name, name);
2048 }
2049
2050 if (binding->isKind(ParseNodeKind::ArrayExpr)) {
2051 return processExportArrayBinding(&binding->as<ListNode>());
2052 }
2053
2054 MOZ_ASSERT(binding->isKind(ParseNodeKind::ObjectExpr));
2055 return processExportObjectBinding(&binding->as<ListNode>());
2056 }
2057
2058 bool ModuleBuilder::processExportArrayBinding(frontend::ListNode* array) {
2059 using namespace js::frontend;
2060
2061 MOZ_ASSERT(array->isKind(ParseNodeKind::ArrayExpr));
2062
2063 for (ParseNode* node : array->contents()) {
2064 if (node->isKind(ParseNodeKind::Elision)) {
2065 continue;
2066 }
2067
2068 if (node->isKind(ParseNodeKind::Spread)) {
2069 node = node->as<UnaryNode>().kid();
2070 } else if (node->isKind(ParseNodeKind::AssignExpr)) {
2071 node = node->as<AssignmentNode>().left();
2072 }
2073
2074 if (!processExportBinding(node)) {
2075 return false;
2076 }
2077 }
2078
2079 return true;
2080 }
2081
2082 bool ModuleBuilder::processExportObjectBinding(frontend::ListNode* obj) {
2083 using namespace js::frontend;
2084
2085 MOZ_ASSERT(obj->isKind(ParseNodeKind::ObjectExpr));
2086
2087 for (ParseNode* node : obj->contents()) {
2088 MOZ_ASSERT(node->isKind(ParseNodeKind::MutateProto) ||
2089 node->isKind(ParseNodeKind::PropertyDefinition) ||
2090 node->isKind(ParseNodeKind::Shorthand) ||
2091 node->isKind(ParseNodeKind::Spread));
2092
2093 ParseNode* target;
2094 if (node->isKind(ParseNodeKind::Spread)) {
2095 target = node->as<UnaryNode>().kid();
2096 } else {
2097 if (node->isKind(ParseNodeKind::MutateProto)) {
2098 target = node->as<UnaryNode>().kid();
2099 } else {
2100 target = node->as<BinaryNode>().right();
2101 }
2102
2103 if (target->isKind(ParseNodeKind::AssignExpr)) {
2104 target = target->as<AssignmentNode>().left();
2105 }
2106 }
2107
2108 if (!processExportBinding(target)) {
2109 return false;
2110 }
2111 }
2112
2113 return true;
2114 }
2115
2116 bool ModuleBuilder::processExportFrom(frontend::BinaryNode* exportNode) {
2117 using namespace js::frontend;
2118
2119 MOZ_ASSERT(exportNode->isKind(ParseNodeKind::ExportFromStmt));
2120
2121 auto* specList = &exportNode->left()->as<ListNode>();
2122 MOZ_ASSERT(specList->isKind(ParseNodeKind::ExportSpecList));
2123
2124 auto* moduleRequest = &exportNode->right()->as<BinaryNode>();
2125 MOZ_ASSERT(moduleRequest->isKind(ParseNodeKind::ImportModuleRequest));
2126
2127 auto* moduleSpec = &moduleRequest->left()->as<NameNode>();
2128 MOZ_ASSERT(moduleSpec->isKind(ParseNodeKind::StringExpr));
2129
2130 auto* attributeList = &moduleRequest->right()->as<ListNode>();
2131 MOZ_ASSERT(attributeList->isKind(ParseNodeKind::ImportAttributeList));
2132
2133 auto specifier = moduleSpec->atom();
2134 MaybeModuleRequestIndex moduleRequestIndex =
2135 appendModuleRequest(specifier, attributeList);
2136 if (!moduleRequestIndex.isSome()) {
2137 return false;
2138 }
2139
2140 if (!maybeAppendRequestedModule(moduleRequestIndex, moduleSpec)) {
2141 return false;
2142 }
2143
2144 for (ParseNode* spec : specList->contents()) {
2145 uint32_t line;
2146 JS::LimitedColumnNumberOneOrigin column;
2147 eitherParser_.computeLineAndColumn(spec->pn_pos.begin, &line, &column);
2148
2149 StencilModuleEntry entry;
2150 if (spec->isKind(ParseNodeKind::ExportSpec)) {
2151 auto* importNameNode = &spec->as<BinaryNode>().left()->as<NameNode>();
2152 auto* exportNameNode = &spec->as<BinaryNode>().right()->as<NameNode>();
2153
2154 auto importName = importNameNode->atom();
2155 auto exportName = exportNameNode->atom();
2156 MOZ_ASSERT(exportNames_.has(exportName));
2157
2158 markUsedByStencil(importName);
2159 markUsedByStencil(exportName);
2160 entry = StencilModuleEntry::exportFromEntry(
2161 moduleRequestIndex, importName, exportName, line,
2162 JS::ColumnNumberOneOrigin(column));
2163 } else if (spec->isKind(ParseNodeKind::ExportNamespaceSpec)) {
2164 auto* exportNameNode = &spec->as<UnaryNode>().kid()->as<NameNode>();
2165
2166 auto exportName = exportNameNode->atom();
2167 MOZ_ASSERT(exportNames_.has(exportName));
2168
2169 markUsedByStencil(exportName);
2170 entry = StencilModuleEntry::exportNamespaceFromEntry(
2171 moduleRequestIndex, exportName, line,
2172 JS::ColumnNumberOneOrigin(column));
2173 } else {
2174 MOZ_ASSERT(spec->isKind(ParseNodeKind::ExportBatchSpecStmt));
2175
2176 entry = StencilModuleEntry::exportBatchFromEntry(
2177 moduleRequestIndex, line, JS::ColumnNumberOneOrigin(column));
2178 }
2179
2180 if (!exportEntries_.append(entry)) {
2181 return false;
2182 }
2183 }
2184
2185 return true;
2186 }
2187
2188 frontend::StencilModuleEntry* ModuleBuilder::importEntryFor(
2189 frontend::TaggedParserAtomIndex localName) const {
2190 MOZ_ASSERT(localName);
2191 auto ptr = importEntries_.lookup(localName);
2192 if (!ptr) {
2193 return nullptr;
2194 }
2195
2196 return &ptr->value();
2197 }
2198
2199 ModuleBuilder::NoteExportedNameResult ModuleBuilder::noteExportedName(
2200 frontend::TaggedParserAtomIndex name) {
2201 MOZ_ASSERT(name);
2202 auto addPtr = exportNames_.lookupForAdd(name);
2203 if (addPtr) {
2204 return NoteExportedNameResult::AlreadyDeclared;
2205 }
2206 if (!exportNames_.add(addPtr, name)) {
2207 return NoteExportedNameResult::OutOfMemory;
2208 }
2209 return NoteExportedNameResult::Success;
2210 }
2211
2212 bool ModuleBuilder::appendExportEntry(
2213 frontend::TaggedParserAtomIndex exportName,
2214 frontend::TaggedParserAtomIndex localName, frontend::ParseNode* node) {
2215 MOZ_ASSERT(exportNames_.has(exportName));
2216
2217 uint32_t line = 0;
2218 JS::LimitedColumnNumberOneOrigin column;
2219 if (node) {
2220 eitherParser_.computeLineAndColumn(node->pn_pos.begin, &line, &column);
2221 }
2222
2223 markUsedByStencil(localName);
2224 markUsedByStencil(exportName);
2225 auto entry = frontend::StencilModuleEntry::exportAsEntry(
2226 localName, exportName, line, JS::ColumnNumberOneOrigin(column));
2227 return exportEntries_.append(entry);
2228 }
2229
2230 frontend::MaybeModuleRequestIndex ModuleBuilder::appendModuleRequest(
2231 frontend::TaggedParserAtomIndex specifier,
2232 frontend::ListNode* attributeList) {
2233 markUsedByStencil(specifier);
2234 auto request = frontend::StencilModuleRequest(specifier);
2235
2236 if (!processAttributes(request, attributeList)) {
2237 return MaybeModuleRequestIndex();
2238 }
2239
2240 if (auto ptr = moduleRequestIndexes_.lookup(request)) {
2241 return MaybeModuleRequestIndex(ptr->value());
2242 }
2243
2244 uint32_t index = moduleRequests_.length();
2245 if (!moduleRequests_.append(request) ||
2246 !moduleRequestIndexes_.put(request, index)) {
2247 js::ReportOutOfMemory(fc_);
2248 return MaybeModuleRequestIndex();
2249 }
2250
2251 return MaybeModuleRequestIndex(index);
2252 }
2253
2254 bool ModuleBuilder::maybeAppendRequestedModule(
2255 MaybeModuleRequestIndex moduleRequest, frontend::ParseNode* node) {
2256 uint32_t index = moduleRequest.value();
2257 if (requestedModuleIndexes_.has(index)) {
2258 return true;
2259 }
2260
2261 uint32_t line;
2262 JS::LimitedColumnNumberOneOrigin column;
2263 eitherParser_.computeLineAndColumn(node->pn_pos.begin, &line, &column);
2264
2265 auto entry = frontend::StencilModuleEntry::requestedModule(
2266 moduleRequest, line, JS::ColumnNumberOneOrigin(column));
2267
2268 if (!requestedModules_.append(entry)) {
2269 js::ReportOutOfMemory(fc_);
2270 return false;
2271 }
2272
2273 return requestedModuleIndexes_.put(index);
2274 }
2275
2276 void ModuleBuilder::markUsedByStencil(frontend::TaggedParserAtomIndex name) {
2277 // Imported/exported identifiers must be atomized.
2278 eitherParser_.parserAtoms().markUsedByStencil(
2279 name, frontend::ParserAtom::Atomize::Yes);
2280 }
2281
2282 JSObject* js::GetOrCreateModuleMetaObject(JSContext* cx,
2283 HandleObject moduleArg) {
2284 Handle<ModuleObject*> module = moduleArg.as<ModuleObject>();
2285 if (JSObject* obj = module->metaObject()) {
2286 return obj;
2287 }
2288
2289 RootedObject metaObject(cx, NewPlainObjectWithProto(cx, nullptr));
2290 if (!metaObject) {
2291 return nullptr;
2292 }
2293
2294 JS::ModuleMetadataHook func = cx->runtime()->moduleMetadataHook;
2295 if (!func) {
2296 JS_ReportErrorASCII(cx, "Module metadata hook not set");
2297 return nullptr;
2298 }
2299
2300 RootedValue modulePrivate(cx, JS::GetModulePrivate(module));
2301 if (!func(cx, modulePrivate, metaObject)) {
2302 return nullptr;
2303 }
2304
2305 module->setMetaObject(metaObject);
2306
2307 return metaObject;
2308 }
2309
2310 ModuleObject* js::CallModuleResolveHook(JSContext* cx,
2311 HandleValue referencingPrivate,
2312 HandleObject moduleRequest) {
2313 JS::ModuleResolveHook moduleResolveHook = cx->runtime()->moduleResolveHook;
2314 if (!moduleResolveHook) {
2315 JS_ReportErrorASCII(cx, "Module resolve hook not set");
2316 return nullptr;
2317 }
2318
2319 RootedObject result(cx,
2320 moduleResolveHook(cx, referencingPrivate, moduleRequest));
2321 if (!result) {
2322 return nullptr;
2323 }
2324
2325 if (!result->is<ModuleObject>()) {
2326 JS_ReportErrorASCII(cx, "Module resolve hook did not return Module object");
2327 return nullptr;
2328 }
2329
2330 return &result->as<ModuleObject>();
2331 }
2332
2333 bool ModuleObject::topLevelCapabilityResolve(JSContext* cx,
2334 Handle<ModuleObject*> module) {
2335 RootedValue rval(cx);
2336 Rooted<PromiseObject*> promise(
2337 cx, &module->topLevelCapability()->as<PromiseObject>());
2338 return AsyncFunctionReturned(cx, promise, rval);
2339 }
2340
2341 bool ModuleObject::topLevelCapabilityReject(JSContext* cx,
2342 Handle<ModuleObject*> module,
2343 HandleValue error) {
2344 Rooted<PromiseObject*> promise(
2345 cx, &module->topLevelCapability()->as<PromiseObject>());
2346 return AsyncFunctionThrown(cx, promise, error);
2347 }
2348
2349 // https://tc39.es/proposal-import-attributes/#sec-evaluate-import-call
2350 // NOTE: The caller needs to handle the promise.
2351 static bool EvaluateDynamicImportOptions(
2352 JSContext* cx, HandleValue optionsArg,
2353 MutableHandle<ImportAttributeVector> attributesArrayArg) {
2354 // Step 11. If options is not undefined, then
2355 if (optionsArg.isUndefined()) {
2356 return true;
2357 }
2358
2359 // Step 11.a. If options is not an Object, then
2360 if (!optionsArg.isObject()) {
2361 JS_ReportErrorNumberASCII(
2362 cx, GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE, "import",
2363 "object or undefined", InformalValueTypeName(optionsArg));
2364 return false;
2365 }
2366
2367 RootedObject attributesWrapperObject(cx, &optionsArg.toObject());
2368 RootedValue attributesValue(cx);
2369
2370 // Step 11.b. Let attributesObj be Completion(Get(options, "with")).
2371 RootedId withId(cx, NameToId(cx->names().with));
2372 if (!GetProperty(cx, attributesWrapperObject, attributesWrapperObject, withId,
2373 &attributesValue)) {
2374 return false;
2375 }
2376
2377 // Step 11.e. If attributesObj is not undefined, then
2378 if (attributesValue.isUndefined()) {
2379 return true;
2380 }
2381
2382 // Step 11.e.i. If attributesObj is not an Object, then
2383 if (!attributesValue.isObject()) {
2384 JS_ReportErrorNumberASCII(
2385 cx, GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE, "import",
2386 "object or undefined", InformalValueTypeName(attributesValue));
2387 return false;
2388 }
2389
2390 // Step 11.e.ii. Let entries be
2391 // Completion(EnumerableOwnProperties(attributesObj, key+value)).
2392 RootedObject attributesObject(cx, &attributesValue.toObject());
2393 RootedIdVector attributes(cx);
2394 if (!GetPropertyKeys(cx, attributesObject, JSITER_OWNONLY, &attributes)) {
2395 return false;
2396 }
2397
2398 uint32_t numberOfAttributes = attributes.length();
2399 if (numberOfAttributes == 0) {
2400 return true;
2401 }
2402
2403 // Step 10 (reordered). Let attributes be a new empty List.
2404 if (!attributesArrayArg.reserve(numberOfAttributes)) {
2405 ReportOutOfMemory(cx);
2406 return false;
2407 }
2408
2409 size_t numberOfValidAttributes = 0;
2410
2411 // Step 11.e.iv. For each element entry of entries, do
2412 RootedId key(cx);
2413 RootedValue value(cx);
2414 Rooted<JSAtom*> keyAtom(cx);
2415 Rooted<JSString*> valueString(cx);
2416 for (size_t i = 0; i < numberOfAttributes; i++) {
2417 // Step 11.e.ii.iv.1. Let key be ! Get(entry, "0").
2418 key = attributes[i];
2419
2420 // Step 11.e.ii.iv.2. Let value be ! Get(entry, "1").
2421 if (!GetProperty(cx, attributesObject, attributesObject, key, &value)) {
2422 return false;
2423 }
2424
2425 // Step 11.e.ii.iv.3. If key is a String, then
2426 if (key.isString()) {
2427 // Step 11.f (reordered). If AllImportAttributesSupported(attributes) is
2428 // false, then
2429 //
2430 // Note: This should be driven by a host hook
2431 // (HostGetSupportedImportAttributes), however the infrastructure of said
2432 // host hook is deeply unclear, and so right now embedders will not have
2433 // the ability to alter or extend the set of supported attributes.
2434 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1840723.
2435 bool supported = key.isAtom(cx->names().type);
2436 if (!supported) {
2437 UniqueChars printableKey = AtomToPrintableString(cx, key.toAtom());
2438 if (!printableKey) {
2439 return false;
2440 }
2441 JS_ReportErrorNumberASCII(
2442 cx, GetErrorMessage, nullptr,
2443 JSMSG_IMPORT_ATTRIBUTES_DYNAMIC_IMPORT_UNSUPPORTED_ATTRIBUTE,
2444 printableKey.get());
2445 return false;
2446 }
2447
2448 // Step 10.d.v.3.a. If value is not a String, then
2449 if (!value.isString()) {
2450 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2451 JSMSG_NOT_EXPECTED_TYPE, "import", "string",
2452 InformalValueTypeName(value));
2453 return false;
2454 }
2455
2456 // Step 10.d.v.3.b. Append the ImportAttribute Record { [[Key]]: key,
2457 // [[Value]]: value } to attributes.
2458 keyAtom = key.toAtom();
2459 valueString = value.toString();
2460 attributesArrayArg.infallibleEmplaceBack(keyAtom, valueString);
2461 ++numberOfValidAttributes;
2462 }
2463 }
2464
2465 if (numberOfValidAttributes == 0) {
2466 return true;
2467 }
2468
2469 // Step 10.g (skipped). Sort attributes according to the lexicographic order
2470 // of their [[Key]] fields, treating the value of each such field as a
2471 // sequence of UTF-16 code unit values.
2472 //
2473 // We only support "type", so we can ignore this.
2474
2475 return true;
2476 }
2477
2478 // ShadowRealmImportValue duplicates some of this, so be sure to keep these in
2479 // sync.
2480 JSObject* js::StartDynamicModuleImport(JSContext* cx, HandleScript script,
2481 HandleValue specifierArg,
2482 HandleValue optionsArg) {
2483 RootedObject promiseObject(cx, JS::NewPromiseObject(cx, nullptr));
2484 if (!promiseObject) {
2485 return nullptr;
2486 }
2487
2488 Handle<PromiseObject*> promise = promiseObject.as<PromiseObject>();
2489
2490 JS::ModuleDynamicImportHook importHook =
2491 cx->runtime()->moduleDynamicImportHook;
2492
2493 if (!importHook) {
2494 // Dynamic import can be disabled by a pref and is not supported in all
2495 // contexts (e.g. web workers).
2496 JS_ReportErrorASCII(
2497 cx,
2498 "Dynamic module import is disabled or not supported in this context");
2499 if (!RejectPromiseWithPendingError(cx, promise)) {
2500 return nullptr;
2501 }
2502 return promise;
2503 }
2504
2505 RootedString specifier(cx, ToString(cx, specifierArg));
2506 if (!specifier) {
2507 if (!RejectPromiseWithPendingError(cx, promise)) {
2508 return nullptr;
2509 }
2510 return promise;
2511 }
2512
2513 Rooted<JSAtom*> specifierAtom(cx, AtomizeString(cx, specifier));
2514 if (!specifierAtom) {
2515 if (!RejectPromiseWithPendingError(cx, promise)) {
2516 return nullptr;
2517 }
2518 return promise;
2519 }
2520
2521 Rooted<ImportAttributeVector> attributes(cx);
2522 if (!EvaluateDynamicImportOptions(cx, optionsArg, &attributes)) {
2523 if (!RejectPromiseWithPendingError(cx, promise)) {
2524 return nullptr;
2525 }
2526 return promise;
2527 }
2528
2529 RootedObject moduleRequest(
2530 cx, ModuleRequestObject::create(cx, specifierAtom, attributes));
2531 if (!moduleRequest) {
2532 if (!RejectPromiseWithPendingError(cx, promise)) {
2533 return nullptr;
2534 }
2535 return promise;
2536 }
2537
2538 RootedValue referencingPrivate(cx, script->sourceObject()->getPrivate());
2539 if (!importHook(cx, referencingPrivate, moduleRequest, promise)) {
2540 // If there's no exception pending then the script is terminating
2541 // anyway, so just return nullptr.
2542 if (!cx->isExceptionPending() ||
2543 !RejectPromiseWithPendingError(cx, promise)) {
2544 return nullptr;
2545 }
2546 return promise;
2547 }
2548
2549 return promise;
2550 }
2551
2552 static bool OnRootModuleRejected(JSContext* cx, unsigned argc, Value* vp) {
2553 CallArgs args = CallArgsFromVp(argc, vp);
2554 HandleValue error = args.get(0);
2555
2556 ReportExceptionClosure reportExn(error);
2557 PrepareScriptEnvironmentAndInvoke(cx, cx->global(), reportExn);
2558
2559 args.rval().setUndefined();
2560 return true;
2561 };
2562
2563 bool js::OnModuleEvaluationFailure(JSContext* cx,
2564 HandleObject evaluationPromise,
2565 JS::ModuleErrorBehaviour errorBehaviour) {
2566 if (evaluationPromise == nullptr) {
2567 return false;
2568 }
2569
2570 // To allow module evaluation to happen synchronously throw the error
2571 // immediately. This assumes that any error will already have caused the
2572 // promise to be rejected, and doesn't support top-level await.
2573 if (errorBehaviour == JS::ThrowModuleErrorsSync) {
2574 JS::PromiseState state = JS::GetPromiseState(evaluationPromise);
2575 MOZ_DIAGNOSTIC_ASSERT(state == JS::PromiseState::Rejected ||
2576 state == JS::PromiseState::Fulfilled);
2577
2578 JS::SetSettledPromiseIsHandled(cx, evaluationPromise);
2579 if (state == JS::PromiseState::Fulfilled) {
2580 return true;
2581 }
2582
2583 RootedValue error(cx, JS::GetPromiseResult(evaluationPromise));
2584 JS_SetPendingException(cx, error);
2585 return false;
2586 }
2587
2588 RootedFunction onRejected(
2589 cx, NewHandler(cx, OnRootModuleRejected, evaluationPromise));
2590 if (!onRejected) {
2591 return false;
2592 }
2593
2594 return JS::AddPromiseReactions(cx, evaluationPromise, nullptr, onRejected);
2595 }
2596
2597 // This is used to marshal some of the arguments to FinishDynamicModuleImport
2598 // and pass them through to the promise resolve and reject callbacks. It holds a
2599 // reference to the referencing private to keep it alive until it is needed.
2600 class DynamicImportContextObject : public NativeObject {
2601 public:
2602 enum { ReferencingPrivateSlot = 0, SpecifierSlot, ModuleTypeSlot, SlotCount };
2603
2604 static const JSClass class_;
2605 static const JSClassOps classOps_;
2606
2607 [[nodiscard]] static DynamicImportContextObject* create(
2608 JSContext* cx, Handle<Value> referencingPrivate,
2609 Handle<JSString*> specifier, JS::ModuleType moduleType);
2610
2611 Value referencingPrivate() const;
2612 JSString* specifier() const;
2613 JS::ModuleType moduleType() const;
2614
2615 static void clearReferencingPrivate(JSRuntime* runtime,
2616 DynamicImportContextObject* ic);
2617
2618 static void finalize(JS::GCContext* gcx, JSObject* obj);
2619 };
2620
2621 /* static */
2622 const JSClass DynamicImportContextObject::class_ = {
2623 "DynamicImportContextObject",
2624 JSCLASS_HAS_RESERVED_SLOTS(DynamicImportContextObject::SlotCount) |
2625 JSCLASS_SLOT0_IS_NSISUPPORTS | JSCLASS_FOREGROUND_FINALIZE,
2626 &DynamicImportContextObject::classOps_,
2627 };
2628 static_assert(DynamicImportContextObject::ReferencingPrivateSlot == 0);
2629
2630 /* static */
2631 const JSClassOps DynamicImportContextObject::classOps_ = {
2632 nullptr, // addProperty
2633 nullptr, // delProperty
2634 nullptr, // enumerate
2635 nullptr, // newEnumerate
2636 nullptr, // resolve
2637 nullptr, // mayResolve
2638 DynamicImportContextObject::finalize, // finalize
2639 nullptr, // call
2640 nullptr, // construct
2641 nullptr, // trace
2642 };
2643
2644 /* static */
2645 DynamicImportContextObject* DynamicImportContextObject::create(
2646 JSContext* cx, Handle<Value> referencingPrivate,
2647 Handle<JSString*> specifier, JS::ModuleType moduleType) {
2648 Rooted<DynamicImportContextObject*> self(
2649 cx, NewObjectWithGivenProto<DynamicImportContextObject>(cx, nullptr));
2650 if (!self) {
2651 return nullptr;
2652 }
2653
2654 cx->runtime()->addRefScriptPrivate(referencingPrivate);
2655
2656 self->initReservedSlot(ReferencingPrivateSlot, referencingPrivate);
2657 self->initReservedSlot(SpecifierSlot, StringValue(specifier));
2658 self->initReservedSlot(ModuleTypeSlot, ModuleTypeToValue(moduleType));
2659
2660 return self;
2661 }
2662
2663 Value DynamicImportContextObject::referencingPrivate() const {
2664 return getReservedSlot(ReferencingPrivateSlot);
2665 }
2666
2667 JSString* DynamicImportContextObject::specifier() const {
2668 Value value = getReservedSlot(SpecifierSlot);
2669 if (value.isUndefined()) {
2670 return nullptr;
2671 }
2672
2673 return value.toString();
2674 }
2675
2676 JS::ModuleType DynamicImportContextObject::moduleType() const {
2677 return ValueToModuleType(getReservedSlot(ModuleTypeSlot));
2678 }
2679
2680 /* static */
2681 void DynamicImportContextObject::finalize(JS::GCContext* gcx, JSObject* obj) {
2682 auto* context = &obj->as<DynamicImportContextObject>();
2683 clearReferencingPrivate(gcx->runtime(), context);
2684 }
2685
2686 /* static */
2687 void DynamicImportContextObject::clearReferencingPrivate(
2688 JSRuntime* runtime, DynamicImportContextObject* context) {
2689 Value value = context->referencingPrivate();
2690 if (!value.isUndefined()) {
2691 context->setReservedSlot(ReferencingPrivateSlot, UndefinedValue());
2692 runtime->releaseScriptPrivate(value);
2693 }
2694 }
2695
2696 // Adjustment for Top-level await;
2697 // See: https://github.com/tc39/proposal-dynamic-import/pull/71/files
2698 static bool OnResolvedDynamicModule(JSContext* cx, unsigned argc, Value* vp) {
2699 CallArgs args = CallArgsFromVp(argc, vp);
2700 MOZ_ASSERT(args.get(0).isUndefined());
2701
2702 Rooted<DynamicImportContextObject*> context(
2703 cx, ExtraFromHandler<DynamicImportContextObject>(args));
2704 auto clearRef = mozilla::MakeScopeExit([&] {
2705 DynamicImportContextObject::clearReferencingPrivate(cx->runtime(), context);
2706 });
2707
2708 RootedValue referencingPrivate(cx, context->referencingPrivate());
2709
2710 Rooted<JSAtom*> specifier(cx, AtomizeString(cx, context->specifier()));
2711 if (!specifier) {
2712 return false;
2713 }
2714
2715 Rooted<PromiseObject*> promise(cx, TargetFromHandler<PromiseObject>(args));
2716 RootedObject moduleRequest(
2717 cx, ModuleRequestObject::create(cx, specifier, context->moduleType()));
2718 if (!moduleRequest) {
2719 return RejectPromiseWithPendingError(cx, promise);
2720 }
2721
2722 RootedObject result(
2723 cx, CallModuleResolveHook(cx, referencingPrivate, moduleRequest));
2724 if (!result) {
2725 return RejectPromiseWithPendingError(cx, promise);
2726 }
2727
2728 Rooted<ModuleObject*> module(cx, &result->as<ModuleObject>());
2729 if (module->status() != ModuleStatus::EvaluatingAsync &&
2730 module->status() != ModuleStatus::Evaluated) {
2731 JS_ReportErrorASCII(
2732 cx, "Unevaluated or errored module returned by module resolve hook");
2733 return RejectPromiseWithPendingError(cx, promise);
2734 }
2735
2736 MOZ_ASSERT_IF(module->hasCyclicModuleFields(),
2737 module->getCycleRoot()
2738 ->topLevelCapability()
2739 ->as<PromiseObject>()
2740 .state() == JS::PromiseState::Fulfilled);
2741
2742 RootedObject ns(cx, GetOrCreateModuleNamespace(cx, module));
2743 if (!ns) {
2744 return RejectPromiseWithPendingError(cx, promise);
2745 }
2746
2747 args.rval().setUndefined();
2748 RootedValue value(cx, ObjectValue(*ns));
2749 return PromiseObject::resolve(cx, promise, value);
2750 };
2751
2752 static bool OnRejectedDynamicModule(JSContext* cx, unsigned argc, Value* vp) {
2753 CallArgs args = CallArgsFromVp(argc, vp);
2754 HandleValue error = args.get(0);
2755
2756 Rooted<DynamicImportContextObject*> context(
2757 cx, ExtraFromHandler<DynamicImportContextObject>(args));
2758 auto clearRef = mozilla::MakeScopeExit([&] {
2759 DynamicImportContextObject::clearReferencingPrivate(cx->runtime(), context);
2760 });
2761
2762 RootedValue referencingPrivate(cx, context->referencingPrivate());
2763 Rooted<PromiseObject*> promise(cx, TargetFromHandler<PromiseObject>(args));
2764
2765 args.rval().setUndefined();
2766 return PromiseObject::reject(cx, promise, error);
2767 };
2768
2769 bool js::FinishDynamicModuleImport(JSContext* cx,
2770 HandleObject evaluationPromise,
2771 HandleValue referencingPrivate,
2772 HandleObject moduleRequest,
2773 HandleObject promise) {
2774 // If we do not have an evaluation promise or a module request for the module,
2775 // we can assume that evaluation has failed or been interrupted -- we can
2776 // reject the dynamic module.
2777
2778 if (!evaluationPromise || !moduleRequest) {
2779 return RejectPromiseWithPendingError(cx, promise.as<PromiseObject>());
2780 }
2781
2782 Rooted<JSString*> specifier(
2783 cx, moduleRequest->as<ModuleRequestObject>().specifier());
2784 Rooted<DynamicImportContextObject*> context(
2785 cx, DynamicImportContextObject::create(
2786 cx, referencingPrivate, specifier,
2787 moduleRequest->as<ModuleRequestObject>().moduleType()));
2788 if (!context) {
2789 return false;
2790 }
2791
2792 Rooted<Value> contextValue(cx, ObjectValue(*context));
2793 RootedFunction onResolved(
2794 cx, NewHandlerWithExtraValue(cx, OnResolvedDynamicModule, promise,
2795 contextValue));
2796 if (!onResolved) {
2797 return false;
2798 }
2799
2800 RootedFunction onRejected(
2801 cx, NewHandlerWithExtraValue(cx, OnRejectedDynamicModule, promise,
2802 contextValue));
2803 if (!onRejected) {
2804 return false;
2805 }
2806
2807 if (!JS::AddPromiseReactionsIgnoringUnhandledRejection(
2808 cx, evaluationPromise, onResolved, onRejected)) {
2809 return false;
2810 }
2811
2812 return true;
2813 }