Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: core/modules.rs #13149

Merged
merged 5 commits into from
Dec 21, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions cli/module_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::proc_state::ProcState;
use deno_core::error::AnyError;
use deno_core::futures::future::FutureExt;
use deno_core::futures::Future;
use deno_core::ModuleLoadId;
use deno_core::ModuleLoader;
use deno_core::ModuleSpecifier;
use deno_core::OpState;
Expand Down Expand Up @@ -84,7 +83,6 @@ impl ModuleLoader for CliModuleLoader {
fn prepare_load(
&self,
op_state: Rc<RefCell<OpState>>,
_load_id: ModuleLoadId,
specifier: &ModuleSpecifier,
_maybe_referrer: Option<String>,
is_dynamic: bool,
Expand All @@ -108,7 +106,6 @@ impl ModuleLoader for CliModuleLoader {
};
drop(state);

// TODO(bartlomieju): `prepare_module_load` should take `load_id` param
async move {
ps.prepare_module_load(
vec![specifier],
Expand Down
8 changes: 2 additions & 6 deletions core/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,11 @@ pub use crate::module_specifier::ModuleSpecifier;
pub use crate::module_specifier::DUMMY_SPECIFIER;
pub use crate::modules::FsModuleLoader;
pub use crate::modules::ModuleId;
pub use crate::modules::ModuleLoadId;
pub use crate::modules::ModuleLoader;
pub use crate::modules::ModuleSource;
pub use crate::modules::ModuleSourceFuture;
pub use crate::modules::ModuleType;
pub use crate::modules::NoopModuleLoader;
pub use crate::runtime::CompiledWasmModuleStore;
pub use crate::runtime::SharedArrayBufferStore;
// TODO(bartlomieju): this struct should be implementation
// detail nad not be public
pub use crate::modules::RecursiveModuleLoad;
pub use crate::normalize_path::normalize_path;
pub use crate::ops::serialize_op_result;
pub use crate::ops::Op;
Expand All @@ -91,10 +85,12 @@ pub use crate::resources::AsyncResult;
pub use crate::resources::Resource;
pub use crate::resources::ResourceId;
pub use crate::resources::ResourceTable;
pub use crate::runtime::CompiledWasmModuleStore;
pub use crate::runtime::GetErrorClassFn;
pub use crate::runtime::JsErrorCreateFn;
pub use crate::runtime::JsRuntime;
pub use crate::runtime::RuntimeOptions;
pub use crate::runtime::SharedArrayBufferStore;
pub use crate::runtime::Snapshot;
// pub use crate::runtime_modules::include_js_files!;
pub use crate::extensions::Extension;
Expand Down
124 changes: 59 additions & 65 deletions core/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::task::Context;
use std::task::Poll;

pub type ModuleId = i32;
pub type ModuleLoadId = i32;
pub(crate) type ModuleLoadId = i32;

pub const BOM_CHAR: char = '\u{FEFF}';

Expand Down Expand Up @@ -198,7 +198,7 @@ pub struct ModuleSource {
pub module_url_found: String,
}

pub type PrepareLoadFuture =
pub(crate) type PrepareLoadFuture =
dyn Future<Output = (ModuleLoadId, Result<RecursiveModuleLoad, Error>)>;
pub type ModuleSourceFuture = dyn Future<Output = Result<ModuleSource, Error>>;

Expand Down Expand Up @@ -242,7 +242,6 @@ pub trait ModuleLoader {
fn prepare_load(
&self,
_op_state: Rc<RefCell<OpState>>,
_load_id: ModuleLoadId,
_module_specifier: &ModuleSpecifier,
_maybe_referrer: Option<String>,
_is_dyn_import: bool,
Expand Down Expand Up @@ -344,18 +343,16 @@ enum LoadInit {
}

#[derive(Debug, Eq, PartialEq)]
pub enum LoadState {
pub(crate) enum LoadState {
Init,
LoadingRoot,
LoadingImports,
Done,
}

/// This future is used to implement parallel async module loading.
pub struct RecursiveModuleLoad {
pub(crate) struct RecursiveModuleLoad {
init: LoadInit,
// TODO(bartlomieju): in future this value should
// be randomized
pub id: ModuleLoadId,
pub root_module_id: Option<ModuleId>,
pub root_module_type: Option<ModuleType>,
Expand All @@ -371,15 +368,15 @@ pub struct RecursiveModuleLoad {

impl RecursiveModuleLoad {
/// Starts a new parallel load of the given URL of the main module.
pub fn main(specifier: &str, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
fn main(specifier: &str, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
Self::new(LoadInit::Main(specifier.to_string()), module_map_rc)
}

pub fn side(specifier: &str, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
fn side(specifier: &str, module_map_rc: Rc<RefCell<ModuleMap>>) -> Self {
Self::new(LoadInit::Side(specifier.to_string()), module_map_rc)
}

pub fn dynamic_import(
fn dynamic_import(
specifier: &str,
referrer: &str,
module_type: ModuleType,
Expand All @@ -393,7 +390,7 @@ impl RecursiveModuleLoad {
Self::new(init, module_map_rc)
}

pub fn is_dynamic_import(&self) -> bool {
fn is_dynamic_import(&self) -> bool {
matches!(self.init, LoadInit::DynamicImport(..))
}

Expand Down Expand Up @@ -435,7 +432,7 @@ impl RecursiveModuleLoad {
load
}

pub fn resolve_root(&self) -> Result<ModuleSpecifier, Error> {
fn resolve_root(&self) -> Result<ModuleSpecifier, Error> {
match self.init {
LoadInit::Main(ref specifier) => {
self.loader.resolve(specifier, ".", true)
Expand All @@ -449,7 +446,7 @@ impl RecursiveModuleLoad {
}
}

pub async fn prepare(&self) -> Result<(), Error> {
async fn prepare(&self) -> Result<(), Error> {
let op_state = self.op_state.clone();
let (module_specifier, maybe_referrer) = match self.init {
LoadInit::Main(ref specifier) => {
Expand All @@ -470,21 +467,20 @@ impl RecursiveModuleLoad {
.loader
.prepare_load(
op_state,
self.id,
&module_specifier,
maybe_referrer,
self.is_dynamic_import(),
)
.await
}

pub fn is_currently_loading_main_module(&self) -> bool {
fn is_currently_loading_main_module(&self) -> bool {
!self.is_dynamic_import()
&& matches!(self.init, LoadInit::Main(..))
&& self.state == LoadState::LoadingRoot
}

pub fn register_and_recurse(
pub(crate) fn register_and_recurse(
&mut self,
scope: &mut v8::HandleScope,
module_request: &ModuleRequest,
Expand Down Expand Up @@ -681,12 +677,13 @@ impl Stream for RecursiveModuleLoad {
/// it's `ModuleType::JavaScript`, but if there were import assertions
/// it might be `ModuleType::Json`.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ModuleRequest {
pub(crate) struct ModuleRequest {
pub specifier: ModuleSpecifier,
pub expected_module_type: ModuleType,
}

pub struct ModuleInfo {
pub(crate) struct ModuleInfo {
#[allow(unused)]
pub id: ModuleId,
// Used in "bindings.rs" for "import.meta.main" property value.
pub main: bool,
Expand All @@ -706,7 +703,7 @@ enum SymbolicModule {
}

/// A collection of JS modules.
pub struct ModuleMap {
pub(crate) struct ModuleMap {
// Handling of specifiers and v8 objects
ids_by_handle: HashMap<v8::Global<v8::Module>, ModuleId>,
handles_by_id: HashMap<ModuleId, v8::Global<v8::Module>>,
Expand All @@ -731,7 +728,7 @@ pub struct ModuleMap {
}

impl ModuleMap {
pub fn new(
pub(crate) fn new(
loader: Rc<dyn ModuleLoader>,
op_state: Rc<RefCell<OpState>>,
) -> ModuleMap {
Expand All @@ -753,11 +750,7 @@ impl ModuleMap {

/// Get module id, following all aliases in case of module specifier
/// that had been redirected.
pub fn get_id(
&self,
name: &str,
module_type: ModuleType,
) -> Option<ModuleId> {
fn get_id(&self, name: &str, module_type: ModuleType) -> Option<ModuleId> {
let mut mod_name = name;
loop {
let symbolic_module =
Expand Down Expand Up @@ -805,24 +798,8 @@ impl ModuleMap {
let value_handle = v8::Global::<v8::Value>::new(tc_scope, parsed_json);
self.json_value_store.insert(handle.clone(), value_handle);

let id = self.next_module_id;
self.next_module_id += 1;
self.by_name.insert(
(name.to_string(), ModuleType::Json),
SymbolicModule::Mod(id),
);
self.handles_by_id.insert(id, handle.clone());
self.ids_by_handle.insert(handle, id);
self.info.insert(
id,
ModuleInfo {
id,
main: false,
name: name.to_string(),
requests: vec![],
module_type: ModuleType::Json,
},
);
let id =
self.create_module_info(name, ModuleType::Json, handle, false, vec![]);

Ok(id)
}
Expand Down Expand Up @@ -902,12 +879,30 @@ impl ModuleMap {
}

let handle = v8::Global::<v8::Module>::new(tc_scope, module);
let id = self.create_module_info(
name,
ModuleType::JavaScript,
handle,
main,
requests,
);

Ok(id)
}

fn create_module_info(
&mut self,
name: &str,
module_type: ModuleType,
handle: v8::Global<v8::Module>,
main: bool,
requests: Vec<ModuleRequest>,
) -> ModuleId {
let id = self.next_module_id;
self.next_module_id += 1;
self.by_name.insert(
(name.to_string(), ModuleType::JavaScript),
SymbolicModule::Mod(id),
);
self
.by_name
.insert((name.to_string(), module_type), SymbolicModule::Mod(id));
self.handles_by_id.insert(id, handle.clone());
self.ids_by_handle.insert(handle, id);
self.info.insert(
Expand All @@ -917,21 +912,18 @@ impl ModuleMap {
main,
name: name.to_string(),
requests,
module_type: ModuleType::JavaScript,
module_type,
},
);

Ok(id)
id
}

pub fn get_requested_modules(
&self,
id: ModuleId,
) -> Option<&Vec<ModuleRequest>> {
fn get_requested_modules(&self, id: ModuleId) -> Option<&Vec<ModuleRequest>> {
self.info.get(&id).map(|i| &i.requests)
}

pub fn is_registered(
fn is_registered(
&self,
specifier: &ModuleSpecifier,
module_type: ModuleType,
Expand All @@ -944,24 +936,27 @@ impl ModuleMap {
false
}

pub fn alias(&mut self, name: &str, module_type: ModuleType, target: &str) {
fn alias(&mut self, name: &str, module_type: ModuleType, target: &str) {
self.by_name.insert(
(name.to_string(), module_type),
SymbolicModule::Alias(target.to_string()),
);
}

#[cfg(test)]
pub fn is_alias(&self, name: &str, module_type: ModuleType) -> bool {
fn is_alias(&self, name: &str, module_type: ModuleType) -> bool {
let cond = self.by_name.get(&(name.to_string(), module_type));
matches!(cond, Some(SymbolicModule::Alias(_)))
}

pub fn get_handle(&self, id: ModuleId) -> Option<v8::Global<v8::Module>> {
pub(crate) fn get_handle(
&self,
id: ModuleId,
) -> Option<v8::Global<v8::Module>> {
self.handles_by_id.get(&id).cloned()
}

pub fn get_info(
pub(crate) fn get_info(
&self,
global: &v8::Global<v8::Module>,
) -> Option<&ModuleInfo> {
Expand All @@ -972,11 +967,11 @@ impl ModuleMap {
None
}

pub fn get_info_by_id(&self, id: &ModuleId) -> Option<&ModuleInfo> {
pub(crate) fn get_info_by_id(&self, id: &ModuleId) -> Option<&ModuleInfo> {
self.info.get(id)
}

pub async fn load_main(
pub(crate) async fn load_main(
module_map_rc: Rc<RefCell<ModuleMap>>,
specifier: &str,
) -> Result<RecursiveModuleLoad, Error> {
Expand All @@ -985,7 +980,7 @@ impl ModuleMap {
Ok(load)
}

pub async fn load_side(
pub(crate) async fn load_side(
module_map_rc: Rc<RefCell<ModuleMap>>,
specifier: &str,
) -> Result<RecursiveModuleLoad, Error> {
Expand All @@ -995,7 +990,7 @@ impl ModuleMap {
}

// Initiate loading of a module graph imported using `import()`.
pub fn load_dynamic_import(
pub(crate) fn load_dynamic_import(
module_map_rc: Rc<RefCell<ModuleMap>>,
specifier: &str,
referrer: &str,
Expand Down Expand Up @@ -1036,13 +1031,13 @@ impl ModuleMap {
.push(fut);
}

pub fn has_pending_dynamic_imports(&self) -> bool {
pub(crate) fn has_pending_dynamic_imports(&self) -> bool {
!(self.preparing_dynamic_imports.is_empty()
&& self.pending_dynamic_imports.is_empty())
}

/// Called by `module_resolve_callback` during module instantiation.
pub fn resolve_callback<'s>(
pub(crate) fn resolve_callback<'s>(
&self,
scope: &mut v8::HandleScope<'s>,
specifier: &str,
Expand Down Expand Up @@ -1661,7 +1656,6 @@ mod tests {
fn prepare_load(
&self,
_op_state: Rc<RefCell<OpState>>,
_load_id: ModuleLoadId,
_module_specifier: &ModuleSpecifier,
_maybe_referrer: Option<String>,
_is_dyn_import: bool,
Expand Down