1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
//! Boa's implementation of the ECMAScript's module system.
//!
//! This module contains the [`Module`] type, which represents an [**Abstract Module Record**][module],
//! a [`ModuleLoader`] trait for custom module loader implementations, and [`SimpleModuleLoader`],
//! the default `ModuleLoader` for [`Context`] which can be used for most simple usecases.
//!
//! Every module roughly follows the same lifecycle:
//! - Parse using [`Module::parse`].
//! - Load all its dependencies using [`Module::load`].
//! - Link its dependencies together using [`Module::link`].
//! - Evaluate the module and its dependencies using [`Module::evaluate`].
//!
//! The [`ModuleLoader`] trait allows customizing the "load" step on the lifecycle
//! of a module, which allows doing things like fetching modules from urls, having multiple
//! "modpaths" from where to import modules, or using Rust futures to avoid blocking the main thread
//! on loads.
//!
//! More information:
//! - [ECMAScript reference][spec]
//!
//! [spec]: https://tc39.es/ecma262/#sec-modules
//! [module]: https://tc39.es/ecma262/#sec-abstract-module-records
mod loader;
mod namespace;
mod source;
mod synthetic;
use boa_parser::source::ReadChar;
pub use loader::*;
pub use namespace::ModuleNamespace;
use source::SourceTextModule;
pub use synthetic::{SyntheticModule, SyntheticModuleInitializer};
use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::hash::Hash;
use std::rc::Rc;
use rustc_hash::FxHashSet;
use boa_gc::{Finalize, Gc, GcRefCell, Trace};
use boa_interner::Interner;
use boa_parser::{Parser, Source};
use boa_profiler::Profiler;
use crate::{
builtins::promise::{PromiseCapability, PromiseState},
environments::DeclarativeEnvironment,
object::{JsObject, JsPromise},
realm::Realm,
Context, HostDefined, JsError, JsResult, JsString, JsValue, NativeFunction,
};
/// ECMAScript's [**Abstract module record**][spec].
///
/// [spec]: https://tc39.es/ecma262/#sec-abstract-module-records
#[derive(Clone, Trace, Finalize)]
pub struct Module {
inner: Gc<ModuleRepr>,
}
impl std::fmt::Debug for Module {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Module")
.field("realm", &self.inner.realm.addr())
.field("namespace", &self.inner.namespace)
.field("kind", &self.inner.kind)
.finish()
}
}
#[derive(Trace, Finalize)]
struct ModuleRepr {
realm: Realm,
namespace: GcRefCell<Option<JsObject>>,
kind: ModuleKind,
host_defined: HostDefined,
}
/// The kind of a [`Module`].
#[derive(Debug, Trace, Finalize)]
pub(crate) enum ModuleKind {
/// A [**Source Text Module Record**](https://tc39.es/ecma262/#sec-source-text-module-records)
SourceText(SourceTextModule),
/// A [**Synthetic Module Record**](https://tc39.es/proposal-json-modules/#sec-synthetic-module-records)
Synthetic(SyntheticModule),
}
impl ModuleKind {
/// Returns the inner `SourceTextModule`.
pub(crate) fn as_source_text(&self) -> Option<&SourceTextModule> {
match self {
ModuleKind::SourceText(src) => Some(src),
ModuleKind::Synthetic(_) => None,
}
}
}
/// Return value of the [`Module::resolve_export`] operation.
///
/// Indicates how to access a specific export in a module.
#[derive(Debug, Clone)]
pub(crate) struct ResolvedBinding {
module: Module,
binding_name: BindingName,
}
/// The local name of the resolved binding within its containing module.
///
/// Note that a resolved binding can resolve to a single binding inside a module (`export var a = 1"`)
/// or to a whole module namespace (`export * as ns from "mod.js"`).
#[derive(Debug, Clone)]
pub(crate) enum BindingName {
/// A local binding.
Name(JsString),
/// The whole namespace of the containing module.
Namespace,
}
impl ResolvedBinding {
/// Gets the module from which the export resolved.
pub(crate) const fn module(&self) -> &Module {
&self.module
}
/// Gets the binding associated with the resolved export.
pub(crate) fn binding_name(&self) -> BindingName {
self.binding_name.clone()
}
}
#[derive(Debug, Clone)]
struct GraphLoadingState {
capability: PromiseCapability,
loading: Cell<bool>,
pending_modules: Cell<usize>,
visited: RefCell<HashSet<Module>>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum ResolveExportError {
NotFound,
Ambiguous,
}
impl Module {
/// Abstract operation [`ParseModule ( sourceText, realm, hostDefined )`][spec].
///
/// Parses the provided `src` as an ECMAScript module, returning an error if parsing fails.
///
/// [spec]: https://tc39.es/ecma262/#sec-parsemodule
pub fn parse<R: ReadChar>(
src: Source<'_, R>,
realm: Option<Realm>,
context: &mut Context,
) -> JsResult<Self> {
let _timer = Profiler::global().start_event("Module parsing", "Main");
let mut parser = Parser::new(src);
parser.set_identifier(context.next_parser_identifier());
let module = parser.parse_module(context.interner_mut())?;
let src = SourceTextModule::new(module, context.interner());
Ok(Self {
inner: Gc::new(ModuleRepr {
realm: realm.unwrap_or_else(|| context.realm().clone()),
namespace: GcRefCell::default(),
kind: ModuleKind::SourceText(src),
host_defined: HostDefined::default(),
}),
})
}
/// Abstract operation [`CreateSyntheticModule ( exportNames, evaluationSteps, realm )`][spec].
///
/// Creates a new Synthetic Module from its list of exported names, its evaluation steps and
/// optionally a root realm.
///
/// [spec]: https://tc39.es/proposal-json-modules/#sec-createsyntheticmodule
#[inline]
pub fn synthetic(
export_names: &[JsString],
evaluation_steps: SyntheticModuleInitializer,
realm: Option<Realm>,
context: &mut Context,
) -> Self {
let names = export_names.iter().cloned().collect();
let realm = realm.unwrap_or_else(|| context.realm().clone());
let synth = SyntheticModule::new(names, evaluation_steps);
Self {
inner: Gc::new(ModuleRepr {
realm,
namespace: GcRefCell::default(),
kind: ModuleKind::Synthetic(synth),
host_defined: HostDefined::default(),
}),
}
}
/// Gets the realm of this `Module`.
#[inline]
#[must_use]
pub fn realm(&self) -> &Realm {
&self.inner.realm
}
/// Returns the [`ECMAScript specification`][spec] defined [`\[\[HostDefined\]\]`][`HostDefined`] field of the [`Module`].
///
/// [spec]: https://tc39.es/ecma262/#sec-abstract-module-records
#[inline]
#[must_use]
pub fn host_defined(&self) -> &HostDefined {
&self.inner.host_defined
}
/// Gets the kind of this `Module`.
pub(crate) fn kind(&self) -> &ModuleKind {
&self.inner.kind
}
/// Gets the declarative environment of this `Module`.
pub(crate) fn environment(&self) -> Option<Gc<DeclarativeEnvironment>> {
match self.kind() {
ModuleKind::SourceText(src) => src.environment(),
ModuleKind::Synthetic(syn) => syn.environment(),
}
}
/// Abstract method [`LoadRequestedModules ( [ hostDefined ] )`][spec].
///
/// Prepares the module for linking by loading all its module dependencies. Returns a `JsPromise`
/// that will resolve when the loading process either completes or fails.
///
/// [spec]: https://tc39.es/ecma262/#table-abstract-methods-of-module-records
#[allow(clippy::missing_panics_doc)]
#[inline]
pub fn load(&self, context: &mut Context) -> JsPromise {
match self.kind() {
ModuleKind::SourceText(_) => {
// Concrete method [`LoadRequestedModules ( [ hostDefined ] )`][spec].
//
// [spec]: https://tc39.es/ecma262/#sec-LoadRequestedModules
// 1. If hostDefined is not present, let hostDefined be empty.
// 2. Let pc be ! NewPromiseCapability(%Promise%).
let pc = PromiseCapability::new(
&context.intrinsics().constructors().promise().constructor(),
context,
)
.expect(
"capability creation must always succeed when using the `%Promise%` intrinsic",
);
// 4. Perform InnerModuleLoading(state, module).
self.inner_load(
// 3. Let state be the GraphLoadingState Record {
// [[IsLoading]]: true, [[PendingModulesCount]]: 1, [[Visited]]: « »,
// [[PromiseCapability]]: pc, [[HostDefined]]: hostDefined
// }.
&Rc::new(GraphLoadingState {
capability: pc.clone(),
loading: Cell::new(true),
pending_modules: Cell::new(1),
visited: RefCell::default(),
}),
context,
);
// 5. Return pc.[[Promise]].
JsPromise::from_object(pc.promise().clone())
.expect("promise created from the %Promise% intrinsic is always native")
}
ModuleKind::Synthetic(_) => SyntheticModule::load(context),
}
}
/// Abstract operation [`InnerModuleLoading`][spec].
///
/// [spec]: https://tc39.es/ecma262/#sec-InnerModuleLoading
fn inner_load(&self, state: &Rc<GraphLoadingState>, context: &mut Context) {
// 1. Assert: state.[[IsLoading]] is true.
assert!(state.loading.get());
if let ModuleKind::SourceText(src) = self.kind() {
// continues on `inner_load
src.inner_load(self, state, context);
if !state.loading.get() {
return;
}
}
// 3. Assert: state.[[PendingModulesCount]] ≥ 1.
assert!(state.pending_modules.get() >= 1);
// 4. Set state.[[PendingModulesCount]] to state.[[PendingModulesCount]] - 1.
state.pending_modules.set(state.pending_modules.get() - 1);
// 5. If state.[[PendingModulesCount]] = 0, then
if state.pending_modules.get() == 0 {
// a. Set state.[[IsLoading]] to false.
state.loading.set(false);
// b. For each Cyclic Module Record loaded of state.[[Visited]], do
// i. If loaded.[[Status]] is new, set loaded.[[Status]] to unlinked.
// By default, all modules start on `unlinked`.
// c. Perform ! Call(state.[[PromiseCapability]].[[Resolve]], undefined, « undefined »).
state
.capability
.resolve()
.call(&JsValue::undefined(), &[], context)
.expect("marking a module as loaded should not fail");
}
// 6. Return unused.
}
/// Abstract method [`GetExportedNames([exportStarSet])`][spec].
///
/// Returns a list of all the names exported from this module.
///
/// # Note
///
/// This must only be called if the [`JsPromise`] returned by [`Module::load`] has fulfilled.
///
/// [spec]: https://tc39.es/ecma262/#table-abstract-methods-of-module-records
fn get_exported_names(
&self,
export_star_set: &mut Vec<Module>,
interner: &Interner,
) -> FxHashSet<JsString> {
match self.kind() {
ModuleKind::SourceText(src) => src.get_exported_names(self, export_star_set, interner),
ModuleKind::Synthetic(synth) => synth.get_exported_names(),
}
}
/// Abstract method [`ResolveExport(exportName [, resolveSet])`][spec].
///
/// Returns the corresponding local binding of a binding exported by this module.
/// The spec requires that this operation must be idempotent; calling this multiple times
/// with the same `export_name` and `resolve_set` should always return the same result.
///
/// # Note
///
/// This must only be called if the [`JsPromise`] returned by [`Module::load`] has fulfilled.
///
/// [spec]: https://tc39.es/ecma262/#table-abstract-methods-of-module-records
#[allow(clippy::mutable_key_type)]
pub(crate) fn resolve_export(
&self,
export_name: JsString,
resolve_set: &mut FxHashSet<(Self, JsString)>,
interner: &Interner,
) -> Result<ResolvedBinding, ResolveExportError> {
match self.kind() {
ModuleKind::SourceText(src) => {
src.resolve_export(self, &export_name, resolve_set, interner)
}
ModuleKind::Synthetic(synth) => synth.resolve_export(self, export_name),
}
}
/// Abstract method [`Link() `][spec].
///
/// Prepares this module for evaluation by resolving all its module dependencies and initializing
/// its environment.
///
/// # Note
///
/// This must only be called if the [`JsPromise`] returned by [`Module::load`] has fulfilled.
///
/// [spec]: https://tc39.es/ecma262/#table-abstract-methods-of-module-records
#[allow(clippy::missing_panics_doc)]
#[inline]
pub fn link(&self, context: &mut Context) -> JsResult<()> {
match self.kind() {
ModuleKind::SourceText(src) => src.link(self, context),
ModuleKind::Synthetic(synth) => {
synth.link(self, context);
Ok(())
}
}
}
/// Abstract operation [`InnerModuleLinking ( module, stack, index )`][spec].
///
/// [spec]: https://tc39.es/ecma262/#sec-InnerModuleLinking
fn inner_link(
&self,
stack: &mut Vec<Module>,
index: usize,
context: &mut Context,
) -> JsResult<usize> {
match self.kind() {
ModuleKind::SourceText(src) => src.inner_link(self, stack, index, context),
// If module is not a Cyclic Module Record, then
ModuleKind::Synthetic(synth) => {
// a. Perform ? module.Link().
synth.link(self, context);
// b. Return index.
Ok(index)
}
}
}
/// Abstract method [`Evaluate()`][spec].
///
/// Evaluates this module, returning a promise for the result of the evaluation of this module
/// and its dependencies.
/// If the promise is rejected, hosts are expected to handle the promise rejection and rethrow
/// the evaluation error.
///
/// # Note
///
/// This must only be called if the [`Module::link`] method finished successfully.
///
/// [spec]: https://tc39.es/ecma262/#table-abstract-methods-of-module-records
#[inline]
pub fn evaluate(&self, context: &mut Context) -> JsPromise {
match self.kind() {
ModuleKind::SourceText(src) => src.evaluate(self, context),
ModuleKind::Synthetic(synth) => synth.evaluate(self, context),
}
}
/// Abstract operation [`InnerModuleLinking ( module, stack, index )`][spec].
///
/// [spec]: https://tc39.es/ecma262/#sec-InnerModuleLinking
fn inner_evaluate(
&self,
stack: &mut Vec<Module>,
index: usize,
context: &mut Context,
) -> JsResult<usize> {
match self.kind() {
ModuleKind::SourceText(src) => src.inner_evaluate(self, stack, index, None, context),
// 1. If module is not a Cyclic Module Record, then
ModuleKind::Synthetic(synth) => {
// a. Let promise be ! module.Evaluate().
let promise: JsPromise = synth.evaluate(self, context);
let state = promise.state();
match state {
PromiseState::Pending => {
unreachable!("b. Assert: promise.[[PromiseState]] is not pending.")
}
// d. Return index.
PromiseState::Fulfilled(_) => Ok(index),
// c. If promise.[[PromiseState]] is rejected, then
// i. Return ThrowCompletion(promise.[[PromiseResult]]).
PromiseState::Rejected(err) => Err(JsError::from_opaque(err)),
}
}
}
}
/// Loads, links and evaluates this module, returning a promise that will resolve after the module
/// finishes its lifecycle.
///
/// # Examples
/// ```
/// # use std::{path::Path, rc::Rc};
/// # use boa_engine::{Context, Source, Module, JsValue};
/// # use boa_engine::builtins::promise::PromiseState;
/// # use boa_engine::module::{ModuleLoader, SimpleModuleLoader};
/// let loader = Rc::new(SimpleModuleLoader::new(Path::new(".")).unwrap());
/// let mut context = &mut Context::builder()
/// .module_loader(loader.clone())
/// .build()
/// .unwrap();
///
/// let source = Source::from_bytes("1 + 3");
///
/// let module = Module::parse(source, None, context).unwrap();
///
/// loader.insert(Path::new("main.mjs").to_path_buf(), module.clone());
///
/// let promise = module.load_link_evaluate(context);
///
/// context.run_jobs();
///
/// assert_eq!(
/// promise.state(),
/// PromiseState::Fulfilled(JsValue::undefined())
/// );
/// ```
#[allow(dropping_copy_types)]
#[inline]
pub fn load_link_evaluate(&self, context: &mut Context) -> JsPromise {
let main_timer = Profiler::global().start_event("Module evaluation", "Main");
let promise = self
.load(context)
.then(
Some(
NativeFunction::from_copy_closure_with_captures(
|_, _, module, context| {
module.link(context)?;
Ok(JsValue::undefined())
},
self.clone(),
)
.to_js_function(context.realm()),
),
None,
context,
)
.then(
Some(
NativeFunction::from_copy_closure_with_captures(
|_, _, module, context| Ok(module.evaluate(context).into()),
self.clone(),
)
.to_js_function(context.realm()),
),
None,
context,
);
// The main_timer needs to be dropped before the Profiler is.
drop(main_timer);
Profiler::global().drop();
promise
}
/// Abstract operation [`GetModuleNamespace ( module )`][spec].
///
/// Gets the [**Module Namespace Object**][ns] that represents this module's exports.
///
/// [spec]: https://tc39.es/ecma262/#sec-getmodulenamespace
/// [ns]: https://tc39.es/ecma262/#sec-module-namespace-exotic-objects
pub fn namespace(&self, context: &mut Context) -> JsObject {
// 1. Assert: If module is a Cyclic Module Record, then module.[[Status]] is not new or unlinked.
// 2. Let namespace be module.[[Namespace]].
// 3. If namespace is empty, then
// 4. Return namespace.
self.inner
.namespace
.borrow_mut()
.get_or_insert_with(|| {
// a. Let exportedNames be module.GetExportedNames().
let exported_names =
self.get_exported_names(&mut Vec::default(), context.interner());
// b. Let unambiguousNames be a new empty List.
let unambiguous_names = exported_names
.into_iter()
// c. For each element name of exportedNames, do
.filter_map(|name| {
// i. Let resolution be module.ResolveExport(name).
// ii. If resolution is a ResolvedBinding Record, append name to unambiguousNames.
self.resolve_export(
name.clone(),
&mut HashSet::default(),
context.interner(),
)
.ok()
.map(|_| name)
})
.collect();
// d. Set namespace to ModuleNamespaceCreate(module, unambiguousNames).
ModuleNamespace::create(self.clone(), unambiguous_names, context)
})
.clone()
}
}
impl PartialEq for Module {
#[inline]
fn eq(&self, other: &Self) -> bool {
Gc::ptr_eq(&self.inner, &other.inner)
}
}
impl Eq for Module {}
impl Hash for Module {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(self.inner.as_ref(), state);
}
}