From 73a718c8a4c2eaadc813b498681e65b2e2d2d06f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Juli=C3=A1n=20Espina?= Date: Fri, 9 Jun 2023 00:28:04 +0000 Subject: [PATCH] Add convenience methods to `ModuleLoader` (#3007) * Add convenience methods to `ModuleLoader` * Document special behaviour of `SimpleModuleLoader` --- boa_engine/src/module/mod.rs | 26 ++++++++++++++++++++++++++ boa_examples/src/bin/modules.rs | 5 +++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/boa_engine/src/module/mod.rs b/boa_engine/src/module/mod.rs index c9e798f603..abd610d04e 100644 --- a/boa_engine/src/module/mod.rs +++ b/boa_engine/src/module/mod.rs @@ -108,6 +108,26 @@ pub trait ModuleLoader { context: &mut Context<'_>, ); + /// Registers a new module into the module loader. + /// + /// This is a convenience method for module loaders caching already parsed modules, since it + /// allows registering a new module through the `&dyn ModuleLoader` provided by + /// [`Context::module_loader`]. + /// + /// Does nothing by default. + fn register_module(&self, _specifier: JsString, _module: Module) {} + + /// Gets the module associated with the provided specifier. + /// + /// This is a convenience method for module loaders caching already parsed modules, since it + /// allows getting a cached module through the `&dyn ModuleLoader` provided by + /// [`Context::module_loader`]. + /// + /// Returns `None` by default. + fn get_module(&self, _specifier: JsString) -> Option { + None + } + /// Host hooks [`HostGetImportMetaProperties ( moduleRecord )`][meta] and /// [`HostFinalizeImportMeta ( importMeta, moduleRecord )`][final]. /// @@ -153,6 +173,12 @@ impl ModuleLoader for IdleModuleLoader { } /// A simple module loader that loads modules relative to a root path. +/// +/// # Note +/// +/// This loader only works by using the type methods [`SimpleModuleLoader::insert`] and +/// [`SimpleModuleLoader::get`]. The utility methods on [`ModuleLoader`] don't work at the moment, +/// but we'll unify both APIs in the future. #[derive(Debug)] pub struct SimpleModuleLoader { root: PathBuf, diff --git a/boa_examples/src/bin/modules.rs b/boa_examples/src/bin/modules.rs index f1ea129e80..2d9435adf0 100644 --- a/boa_examples/src/bin/modules.rs +++ b/boa_examples/src/bin/modules.rs @@ -44,8 +44,9 @@ fn main() -> Result<(), Box> { module.clone(), ); - // The lifecycle of the module is tracked using promises, which can be a bit cumbersome - // for simple uses but that use case is better suited by the `Module::load_link_evaluate` method. + // The lifecycle of the module is tracked using promises which can be a bit cumbersome to use. + // If you just want to directly execute a module, you can use the `Module::load_link_evaluate` + // method to skip all the boilerplate. // This does the full version for demonstration purposes. // // parse -> load -> link -> evaluate