Skip to content

Commit bacc120

Browse files
authored
refactor: improve runtime module macro (#12941)
* refactor: attach chunk ukey to runtime module in macro * refactor: generate runtime module identifier in macro * refactor: generate runtime module identifier in macro * refactor: generate runtime module identifier in macro * refactor: generate runtime module identifier in macro * refactor: generate runtime module identifier in macro
1 parent 157f887 commit bacc120

File tree

103 files changed

+392
-1082
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

103 files changed

+392
-1082
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/rspack_binding_api/src/module.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -772,6 +772,7 @@ pub struct JsAddingRuntimeModule {
772772
impl From<JsAddingRuntimeModule> for RuntimeModuleFromJs {
773773
fn from(value: JsAddingRuntimeModule) -> Self {
774774
Self {
775+
chunk: None,
775776
id: Identifier::from(value.name),
776777
full_hash: value.full_hash,
777778
dependent_hash: value.dependent_hash,

crates/rspack_core/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ dyn-clone = { workspace = true }
1919
either = { workspace = true }
2020
futures = { workspace = true }
2121
hashlink = { workspace = true }
22+
heck = { workspace = true }
2223
hex = { workspace = true }
2324
indexmap = { workspace = true, features = ["rayon"] }
2425
indoc = { workspace = true }

crates/rspack_core/src/runtime_module.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ use rspack_collections::Identifier;
77
use crate::{ChunkUkey, Compilation, Module, RuntimeGlobals};
88

99
#[async_trait]
10-
pub trait RuntimeModule: Module + CustomSourceRuntimeModule {
11-
fn name(&self) -> Identifier;
12-
fn attach(&mut self, _chunk: ChunkUkey) {}
10+
pub trait RuntimeModule:
11+
Module + CustomSourceRuntimeModule + AttachableRuntimeModule + NamedRuntimeModule
12+
{
1313
fn stage(&self) -> RuntimeModuleStage {
1414
RuntimeModuleStage::Normal
1515
}
@@ -39,6 +39,16 @@ pub trait RuntimeModule: Module + CustomSourceRuntimeModule {
3939
}
4040
}
4141

42+
#[async_trait]
43+
pub trait AttachableRuntimeModule {
44+
fn attach(&mut self, chunk: ChunkUkey);
45+
}
46+
47+
#[async_trait]
48+
pub trait NamedRuntimeModule {
49+
fn name(&self) -> Identifier;
50+
}
51+
4252
#[async_trait]
4353
pub trait CustomSourceRuntimeModule {
4454
fn set_custom_source(&mut self, source: String);

crates/rspack_core/src/runtime_template.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::{
44
};
55

66
use cow_utils::CowUtils;
7+
use heck::ToSnakeCase;
78
use itertools::Itertools;
89
use regex::{Captures, Regex};
910
use rspack_collections::Identifier;
@@ -229,6 +230,23 @@ impl RuntimeTemplate {
229230
"webpack/runtime/"
230231
}
231232

233+
pub fn create_runtime_module_identifier(&self, name: &str) -> Identifier {
234+
let module_name = if let Some(name) = name.strip_suffix("RuntimeModule") {
235+
name
236+
} else {
237+
name
238+
};
239+
Identifier::from(format!(
240+
"{}{}",
241+
self.runtime_module_prefix(),
242+
module_name.to_snake_case()
243+
))
244+
}
245+
246+
pub fn create_custom_runtime_module_identifier(&self, custom: &str) -> Identifier {
247+
Identifier::from(format!("{}{custom}", self.runtime_module_prefix()))
248+
}
249+
232250
pub fn create_module_codegen_runtime_template(&self) -> ModuleCodegenRuntimeTemplate {
233251
ModuleCodegenRuntimeTemplate::new(self.compiler_options.clone())
234252
}

crates/rspack_macros/src/runtime_module.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@ pub fn impl_runtime_module(
1212
let origin_fields = input.fields.clone();
1313

1414
if let syn::Fields::Named(ref mut fields) = input.fields {
15+
fields.named.push(
16+
syn::Field::parse_named
17+
.parse2(quote! { pub id: ::rspack_collections::Identifier })
18+
.expect("Failed to parse new field for id"),
19+
);
20+
fields.named.push(
21+
syn::Field::parse_named
22+
.parse2(quote! { pub chunk: Option<::rspack_core::ChunkUkey> })
23+
.expect("Failed to parse new field for chunk"),
24+
);
1525
fields.named.push(
1626
syn::Field::parse_named
1727
.parse2(quote! { pub source_map_kind: ::rspack_util::source_map::SourceMapKind })
@@ -41,23 +51,40 @@ pub fn impl_runtime_module(
4151
let field_tys: Vec<&syn::Type> = origin_fields.iter().map(|field| &field.ty).collect();
4252
let with_default = quote! {
4353
#[allow(clippy::too_many_arguments)]
44-
fn with_default(#(#field_names: #field_tys,)*) -> Self {
54+
fn with_default(runtime_template: &::rspack_core::RuntimeTemplate, #(#field_names: #field_tys,)*) -> Self {
4555
Self {
4656
source_map_kind: ::rspack_util::source_map::SourceMapKind::empty(),
4757
custom_source: None,
4858
cached_generated_code: Default::default(),
59+
chunk: None,
60+
id: runtime_template.create_runtime_module_identifier(stringify!(#name)),
4961
#(#field_names,)*
5062
}
5163
}
5264
};
5365

66+
let with_name = quote! {
67+
#[allow(clippy::too_many_arguments)]
68+
fn with_name(runtime_template: &::rspack_core::RuntimeTemplate, name: &str, #(#field_names: #field_tys,)*) -> Self {
69+
Self {
70+
source_map_kind: ::rspack_util::source_map::SourceMapKind::empty(),
71+
custom_source: None,
72+
cached_generated_code: Default::default(),
73+
chunk: None,
74+
id: runtime_template.create_custom_runtime_module_identifier(name),
75+
#(#field_names,)*
76+
}
77+
}
78+
};
5479
quote! {
5580
#[rspack_cacheable::cacheable]
5681
#input
5782

5883
impl #impl_generics #name #ty_generics #where_clause {
5984
#with_default
6085

86+
#with_name
87+
6188
async fn get_generated_code(
6289
&self,
6390
compilation: &::rspack_core::Compilation,
@@ -96,8 +123,21 @@ pub fn impl_runtime_module(
96123
}
97124
}
98125

126+
impl #impl_generics ::rspack_core::AttachableRuntimeModule for #name #ty_generics #where_clause {
127+
fn attach(&mut self, chunk: ::rspack_core::ChunkUkey) -> () {
128+
self.chunk = Some(chunk);
129+
}
130+
}
131+
132+
impl #impl_generics ::rspack_core::NamedRuntimeModule for #name #ty_generics #where_clause {
133+
fn name(&self) -> ::rspack_collections::Identifier {
134+
self.id
135+
}
136+
}
137+
99138
impl #impl_generics rspack_collections::Identifiable for #name #ty_generics #where_clause {
100139
fn identifier(&self) -> rspack_collections::Identifier {
140+
use rspack_core::NamedRuntimeModule;
101141
self.name()
102142
}
103143
}
@@ -150,6 +190,7 @@ pub fn impl_runtime_module(
150190
}
151191

152192
fn readable_identifier(&self, _context: &::rspack_core::Context) -> std::borrow::Cow<str> {
193+
use rspack_core::NamedRuntimeModule;
153194
self.name().as_str().into()
154195
}
155196

@@ -194,6 +235,7 @@ pub fn impl_runtime_module(
194235
runtime: Option<&::rspack_core::RuntimeSpec>,
195236
) -> rspack_error::Result<::rspack_hash::RspackHashDigest> {
196237
use rspack_util::ext::DynHash;
238+
use rspack_core::NamedRuntimeModule;
197239
let mut hasher = rspack_hash::RspackHash::from(&compilation.options.output);
198240
self.name().dyn_hash(&mut hasher);
199241
self.stage().dyn_hash(&mut hasher);

crates/rspack_macros_test/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ tracing = { workspace = true }
2323
trybuild = { workspace = true }
2424

2525
[package.metadata.cargo-shear]
26-
ignored = ["tracing", "rspack_cacheable", "async-trait", "rspack_hash", "tokio"]
26+
ignored = ["tracing", "rspack_cacheable", "rspack_collections", "async-trait", "rspack_hash", "tokio"]
2727

2828
[lints]
2929
workspace = true

crates/rspack_macros_test/tests/runtime_module.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::marker::PhantomData;
22

3-
use rspack_collections::Identifier;
43
use rspack_core::{Compilation, RuntimeModule, rspack_sources::Source};
54
use rspack_macros::impl_runtime_module;
65

@@ -15,10 +14,6 @@ fn with_generic() {
1514

1615
#[async_trait::async_trait]
1716
impl<T: std::fmt::Debug + Send + Sync + Eq + 'static> RuntimeModule for Foo<T> {
18-
fn name(&self) -> Identifier {
19-
todo!()
20-
}
21-
2217
async fn generate(&self, _: &Compilation) -> rspack_error::Result<String> {
2318
todo!()
2419
}

crates/rspack_plugin_css/src/runtime/mod.rs

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use std::{borrow::Cow, ptr::NonNull, sync::LazyLock};
22

3-
use rspack_collections::Identifier;
43
use rspack_core::{
5-
BooleanMatcher, ChunkGroupOrderKey, ChunkUkey, Compilation, CrossOriginLoading, RuntimeGlobals,
4+
BooleanMatcher, ChunkGroupOrderKey, Compilation, CrossOriginLoading, RuntimeGlobals,
65
RuntimeModule, RuntimeModuleStage, RuntimeTemplate, compile_boolean_matcher, impl_runtime_module,
76
};
87
use rspack_plugin_runtime::{
@@ -42,10 +41,7 @@ static CSS_LOADING_WITH_PRELOAD_RUNTIME_REQUIREMENTS: LazyLock<RuntimeGlobals> =
4241

4342
#[impl_runtime_module]
4443
#[derive(Debug)]
45-
pub struct CssLoadingRuntimeModule {
46-
id: Identifier,
47-
chunk: Option<ChunkUkey>,
48-
}
44+
pub struct CssLoadingRuntimeModule {}
4945

5046
impl CssLoadingRuntimeModule {
5147
pub fn get_runtime_requirements_basic() -> RuntimeGlobals {
@@ -67,13 +63,7 @@ impl CssLoadingRuntimeModule {
6763

6864
impl CssLoadingRuntimeModule {
6965
pub fn new(runtime_template: &RuntimeTemplate) -> Self {
70-
Self::with_default(
71-
Identifier::from(format!(
72-
"{}css_loading",
73-
runtime_template.runtime_module_prefix()
74-
)),
75-
None,
76-
)
66+
Self::with_default(runtime_template)
7767
}
7868

7969
fn template_id(&self, id: TemplateId) -> String {
@@ -105,10 +95,6 @@ enum TemplateId {
10595

10696
#[async_trait::async_trait]
10797
impl RuntimeModule for CssLoadingRuntimeModule {
108-
fn name(&self) -> Identifier {
109-
self.id
110-
}
111-
11298
fn template(&self) -> Vec<(String, String)> {
11399
vec![
114100
(
@@ -395,10 +381,6 @@ installedChunks[chunkId] = 0;
395381
}
396382
}
397383

398-
fn attach(&mut self, chunk: ChunkUkey) {
399-
self.chunk = Some(chunk);
400-
}
401-
402384
fn stage(&self) -> RuntimeModuleStage {
403385
RuntimeModuleStage::Attach
404386
}

crates/rspack_plugin_esm_library/src/plugin.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use tokio::sync::RwLock;
3232
use crate::{
3333
chunk_link::ChunkLinkContext, dependency::dyn_import::DynamicImportDependencyTemplate,
3434
ensure_entry_exports::ensure_entry_exports, esm_lib_parser_plugin::EsmLibParserPlugin,
35-
preserve_modules::preserve_modules, runtime::RegisterModuleRuntime,
35+
preserve_modules::preserve_modules, runtime::EsmRegisterModuleRuntimeModule,
3636
};
3737

3838
pub static RSPACK_ESM_RUNTIME_CHUNK: &str = "RSPACK_ESM_RUNTIME";
@@ -362,15 +362,20 @@ async fn additional_chunk_runtime_requirements(
362362
#[plugin_hook(CompilationRuntimeRequirementInTree for EsmLibraryPlugin)]
363363
async fn runtime_requirements_in_tree(
364364
&self,
365-
_compilation: &Compilation,
365+
compilation: &Compilation,
366366
chunk_ukey: &ChunkUkey,
367367
_all_runtime_requirements: &RuntimeGlobals,
368368
runtime_requirements: &RuntimeGlobals,
369369
_runtime_requirements_mut: &mut RuntimeGlobals,
370370
runtime_modules_to_add: &mut Vec<(ChunkUkey, Box<dyn RuntimeModule>)>,
371371
) -> Result<Option<()>> {
372372
if runtime_requirements.contains(RuntimeGlobals::REQUIRE) {
373-
runtime_modules_to_add.push((*chunk_ukey, Box::new(RegisterModuleRuntime::default())));
373+
runtime_modules_to_add.push((
374+
*chunk_ukey,
375+
Box::new(EsmRegisterModuleRuntimeModule::new(
376+
&compilation.runtime_template,
377+
)),
378+
));
374379
}
375380

376381
Ok(None)

0 commit comments

Comments
 (0)