From 1ab16e2426819af2c534e8a99b98f244626de512 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 5 Mar 2023 18:42:52 -0400 Subject: refactor(core): InternalModuleLoader checks if all files were used (#18005) This commit changes "InternalModuleLoader" from "deno_core" to store a list of used modules during snapshotting. If a module was not used during snapshotting "InternalModuleLoader" will panic in its "Drop" handler signaling to the embedder that they made a mistake somewhere. --- core/modules.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'core') diff --git a/core/modules.rs b/core/modules.rs index b6220bb3b..3d335f8eb 100644 --- a/core/modules.rs +++ b/core/modules.rs @@ -328,6 +328,7 @@ pub type InternalModuleLoaderCb = pub struct InternalModuleLoader { module_loader: Rc, esm_sources: Vec, + used_esm_sources: RefCell>, maybe_load_callback: Option, } @@ -336,6 +337,7 @@ impl Default for InternalModuleLoader { Self { module_loader: Rc::new(NoopModuleLoader), esm_sources: vec![], + used_esm_sources: RefCell::new(HashMap::default()), maybe_load_callback: None, } } @@ -347,14 +349,43 @@ impl InternalModuleLoader { esm_sources: Vec, maybe_load_callback: Option, ) -> Self { + let used_esm_sources: HashMap = esm_sources + .iter() + .map(|file_source| (file_source.specifier.to_string(), false)) + .collect(); + InternalModuleLoader { module_loader: module_loader.unwrap_or_else(|| Rc::new(NoopModuleLoader)), esm_sources, + used_esm_sources: RefCell::new(used_esm_sources), maybe_load_callback, } } } +impl Drop for InternalModuleLoader { + fn drop(&mut self) { + let used_esm_sources = self.used_esm_sources.get_mut(); + let unused_modules: Vec<_> = used_esm_sources + .iter() + .filter(|(_s, v)| !*v) + .map(|(s, _)| s) + .collect(); + + if !unused_modules.is_empty() { + let mut msg = + "Following modules were passed to InternalModuleLoader but never used:\n" + .to_string(); + for m in unused_modules { + msg.push_str(" - "); + msg.push_str(m); + msg.push('\n'); + } + panic!("{}", msg); + } + } +} + impl ModuleLoader for InternalModuleLoader { fn resolve( &self, @@ -400,6 +431,12 @@ impl ModuleLoader for InternalModuleLoader { .find(|file_source| file_source.specifier == module_specifier.as_str()); if let Some(file_source) = maybe_file_source { + { + let mut used_esm_sources = self.used_esm_sources.borrow_mut(); + let used = used_esm_sources.get_mut(&file_source.specifier).unwrap(); + *used = true; + } + let result = if let Some(load_callback) = &self.maybe_load_callback { load_callback(file_source) } else { -- cgit v1.2.3