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

feat: runtime template with dojang #8851

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ swc_node_comments = { version = "=5.0.0" }

pnp = { version = "0.9.0" }

rspack_dojang = { version = "0.1.9" }
rspack_dojang = { version = "0.1.10" }


# all rspack workspace dependencies
Expand Down
10 changes: 10 additions & 0 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,16 @@ export interface RawEnvironment {
const?: boolean
arrowFunction?: boolean
nodePrefixForCoreModules?: boolean
asyncFunction?: boolean
bigIntLiteral?: boolean
destructuring?: boolean
document?: boolean
dynamicImport?: boolean
forOf?: boolean
globalThis?: boolean
module?: boolean
optionalChaining?: boolean
templateLiteral?: boolean
}

export interface RawEvalDevToolModulePluginOptions {
Expand Down
10 changes: 10 additions & 0 deletions crates/rspack/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2247,6 +2247,16 @@ impl OutputOptionsBuilder {
r#const: tp.and_then(|t| t.r#const),
arrow_function: tp.and_then(|t| t.arrow_function),
node_prefix_for_core_modules: tp.and_then(|t| t.node_prefix_for_core_modules),
async_function: tp.and_then(|t| t.async_function),
big_int_literal: tp.and_then(|t| t.big_int_literal),
destructuring: tp.and_then(|t| t.destructuring),
for_of: tp.and_then(|t| t.for_of),
global_this: tp.and_then(|t| t.global_this),
optional_chaining: tp.and_then(|t| t.optional_chaining),
document: tp.and_then(|t| t.document),
dynamic_import: tp.and_then(|t| t.dynamic_import),
template_literal: tp.and_then(|t| t.template_literal),
module: tp.and_then(|t| t.module),
};

OutputOptions {
Expand Down
20 changes: 20 additions & 0 deletions crates/rspack_binding_values/src/raw_options/raw_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ pub struct RawEnvironment {
pub r#const: Option<bool>,
pub arrow_function: Option<bool>,
pub node_prefix_for_core_modules: Option<bool>,
pub async_function: Option<bool>,
pub big_int_literal: Option<bool>,
pub destructuring: Option<bool>,
pub document: Option<bool>,
pub dynamic_import: Option<bool>,
pub for_of: Option<bool>,
pub global_this: Option<bool>,
pub module: Option<bool>,
pub optional_chaining: Option<bool>,
pub template_literal: Option<bool>,
}

impl From<RawEnvironment> for Environment {
Expand All @@ -54,6 +64,16 @@ impl From<RawEnvironment> for Environment {
r#const: value.r#const,
arrow_function: value.arrow_function,
node_prefix_for_core_modules: value.node_prefix_for_core_modules,
async_function: value.async_function,
big_int_literal: value.big_int_literal,
destructuring: value.destructuring,
document: value.document,
dynamic_import: value.dynamic_import,
for_of: value.for_of,
global_this: value.global_this,
module: value.module,
optional_chaining: value.optional_chaining,
template_literal: value.template_literal,
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ ropey = { workspace = true }
rspack_ast = { workspace = true }
rspack_cacheable = { workspace = true }
rspack_collections = { workspace = true }
rspack_dojang = { workspace = true }
rspack_error = { workspace = true }
rspack_fs = { workspace = true }
rspack_futures = { workspace = true }
Expand Down
8 changes: 7 additions & 1 deletion crates/rspack_core/src/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ use crate::{
DependencyType, Entry, EntryData, EntryOptions, EntryRuntime, Entrypoint, ExecuteModuleId,
Filename, ImportVarMap, LocalFilenameFn, Logger, ModuleFactory, ModuleGraph, ModuleGraphPartial,
ModuleIdentifier, ModuleIdsArtifact, PathData, ResolverFactory, RuntimeGlobals, RuntimeModule,
RuntimeSpecMap, SharedPluginDriver, SideEffectsOptimizeArtifact, SourceType, Stats,
RuntimeSpecMap, RuntimeTemplate, SharedPluginDriver, SideEffectsOptimizeArtifact, SourceType,
Stats,
};

pub type BuildDependency = (
Expand Down Expand Up @@ -219,6 +220,7 @@ pub struct Compilation {
pub build_dependencies: IndexSet<ArcPath, BuildHasherDefault<FxHasher>>,

pub value_cache_versions: ValueCacheVersions,
pub runtime_template: RuntimeTemplate,

import_var_map: IdentifierDashMap<ImportVarMap>,

Expand Down Expand Up @@ -273,6 +275,8 @@ impl Compilation {
output_filesystem: Arc<dyn WritableFileSystem>,
) -> Self {
let incremental = Incremental::new(options.experiments.incremental);
let runtime_template = RuntimeTemplate::new(options.output.environment);

Self {
id: CompilationId::new(),
hot_index: 0,
Expand Down Expand Up @@ -341,6 +345,7 @@ impl Compilation {

intermediate_filesystem,
output_filesystem,
runtime_template,
}
}

Expand Down Expand Up @@ -2142,6 +2147,7 @@ impl Compilation {
module.attach(*chunk_ukey);

self.chunk_graph.add_module(runtime_module_identifier);
self.runtime_template.add_templates(module.template());
self
.chunk_graph
.connect_chunk_and_module(*chunk_ukey, runtime_module_identifier);
Expand Down
15 changes: 14 additions & 1 deletion crates/rspack_core/src/init_fragment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ fn first<C>(fragments: Vec<Box<dyn InitFragment<C>>>) -> Box<dyn InitFragment<C>
pub trait InitFragmentRenderContext {
fn add_runtime_requirements(&mut self, requirement: RuntimeGlobals);
fn runtime_condition_expression(&mut self, runtime_condition: &RuntimeCondition) -> String;
fn returning_function(&self, return_value: &str, args: &str) -> String;
}

pub trait InitFragment<C>: IntoAny + DynHash + DynClone + Debug + Sync + Send {
Expand Down Expand Up @@ -269,6 +270,10 @@ impl InitFragmentRenderContext for GenerateContext<'_> {
self.runtime_requirements,
)
}

fn returning_function(&self, return_value: &str, args: &str) -> String {
self.runtime_template.returning_function(return_value, args)
}
}

pub struct ChunkRenderContext;
Expand All @@ -281,6 +286,10 @@ impl InitFragmentRenderContext for ChunkRenderContext {
fn runtime_condition_expression(&mut self, _runtime_condition: &RuntimeCondition) -> String {
unreachable!("should not call runtime condition expression in chunk render context")
}

fn returning_function(&self, _return_value: &str, _args: &str) -> String {
unreachable!("should not call returning function in chunk render context")
}
}

#[derive(Debug, Clone, Hash)]
Expand Down Expand Up @@ -359,7 +368,11 @@ impl<C: InitFragmentRenderContext> InitFragment<C> for ESMExportInitFragment {
.iter()
.map(|s| {
let prop = property_name(&s.0)?;
Ok(format!("{}: function() {{ return {}; }}", prop, s.1))
Ok(format!(
"{}: {}",
prop,
context.returning_function(&s.1, "")
))
})
.collect::<Result<Vec<_>>>()?
.join(",\n ")
Expand Down
2 changes: 2 additions & 0 deletions crates/rspack_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub use dependencies_block::{
AsyncDependenciesBlock, AsyncDependenciesBlockIdentifier, DependenciesBlock,
};
mod fake_namespace_object;
mod runtime_template;
pub use runtime_template::*;
mod template;
pub use fake_namespace_object::*;
pub use template::Template;
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_core/src/normal_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,7 @@ impl Module for NormalModule {
requested_source_type: *source_type,
runtime,
concatenation_scope: concatenation_scope.as_mut(),
runtime_template: &compilation.runtime_template,
},
)?;
code_generation_result.add(*source_type, CachedSource::new(generation_result).boxed());
Expand Down
52 changes: 51 additions & 1 deletion crates/rspack_core/src/options/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,11 +468,21 @@ pub struct LibraryCustomUmdObject {
pub root: Option<Vec<String>>,
}

#[derive(Debug)]
#[derive(Debug, Clone, Copy)]
pub struct Environment {
pub r#const: Option<bool>,
pub arrow_function: Option<bool>,
pub node_prefix_for_core_modules: Option<bool>,
pub async_function: Option<bool>,
pub big_int_literal: Option<bool>,
pub destructuring: Option<bool>,
pub document: Option<bool>,
pub dynamic_import: Option<bool>,
pub for_of: Option<bool>,
pub global_this: Option<bool>,
pub module: Option<bool>,
pub optional_chaining: Option<bool>,
pub template_literal: Option<bool>,
}

impl Environment {
Expand All @@ -487,4 +497,44 @@ impl Environment {
pub fn supports_node_prefix_for_core_modules(&self) -> bool {
self.node_prefix_for_core_modules.unwrap_or_default()
}

pub fn supports_async_function(&self) -> bool {
self.async_function.unwrap_or_default()
}

pub fn supports_big_int_literal(&self) -> bool {
self.big_int_literal.unwrap_or_default()
}

pub fn supports_destructuring(&self) -> bool {
self.destructuring.unwrap_or_default()
}

pub fn supports_document(&self) -> bool {
self.document.unwrap_or_default()
}

pub fn supports_dynamic_import(&self) -> bool {
self.dynamic_import.unwrap_or_default()
}

pub fn supports_for_of(&self) -> bool {
self.for_of.unwrap_or_default()
}

pub fn supports_global_this(&self) -> bool {
self.global_this.unwrap_or_default()
}

pub fn supports_module(&self) -> bool {
self.module.unwrap_or_default()
}

pub fn supports_optional_chaining(&self) -> bool {
self.optional_chaining.unwrap_or_default()
}

pub fn supports_template_literal(&self) -> bool {
self.template_literal.unwrap_or_default()
}
}
4 changes: 3 additions & 1 deletion crates/rspack_core/src/parser_and_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use swc_core::common::Span;
use crate::{
AsyncDependenciesBlock, BoxDependency, BoxLoader, BuildInfo, BuildMeta, CodeGenerationData,
Compilation, CompilerOptions, DependencyTemplate, Module, ModuleDependency, ModuleIdentifier,
ModuleLayer, ModuleType, NormalModule, ParserOptions, RuntimeGlobals, RuntimeSpec, SourceType,
ModuleLayer, ModuleType, NormalModule, ParserOptions, RuntimeGlobals, RuntimeSpec,
RuntimeTemplate, SourceType,
};
use crate::{ChunkGraph, ConcatenationScope, Context, ModuleGraph};

Expand Down Expand Up @@ -82,6 +83,7 @@ pub struct GenerateContext<'a> {
pub requested_source_type: SourceType,
pub runtime: Option<&'a RuntimeSpec>,
pub concatenation_scope: Option<&'a mut ConcatenationScope>,
pub runtime_template: &'a RuntimeTemplate,
}

#[cacheable_dyn]
Expand Down
3 changes: 3 additions & 0 deletions crates/rspack_core/src/runtime_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ pub trait RuntimeModule: Module + CustomSourceRuntimeModule {
fn should_isolate(&self) -> bool {
true
}
fn template(&self) -> Vec<(String, String)> {
vec![]
}

fn generate_with_custom(
&self,
Expand Down
Loading
Loading