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!: detect conflicting values in DefinePlugin #7045

Merged
merged 4 commits into from
Jul 8, 2024
Merged
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

10 changes: 5 additions & 5 deletions crates/rspack_binding_options/src/options/raw_builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mod raw_to_be_deprecated;
use napi::{bindgen_prelude::FromNapiValue, Env, JsUnknown};
use napi_derive::napi;
use raw_lightning_css_minimizer::RawLightningCssMinimizerRspackPluginOptions;
use rspack_core::{BoxPlugin, Define, DefinePlugin, Plugin, PluginExt, Provide, ProvidePlugin};
use rspack_core::{BoxPlugin, Plugin, PluginExt, Provide, ProvidePlugin};
use rspack_error::Result;
use rspack_ids::{
DeterministicChunkIdsPlugin, DeterministicModuleIdsPlugin, NamedChunkIdsPlugin,
Expand All @@ -43,9 +43,9 @@ use rspack_plugin_hmr::HotModuleReplacementPlugin;
use rspack_plugin_html::HtmlRspackPlugin;
use rspack_plugin_ignore::IgnorePlugin;
use rspack_plugin_javascript::{
api_plugin::APIPlugin, FlagDependencyExportsPlugin, FlagDependencyUsagePlugin,
InferAsyncModulesPlugin, JsPlugin, MangleExportsPlugin, ModuleConcatenationPlugin,
SideEffectsFlagPlugin,
api_plugin::APIPlugin, define_plugin::DefinePlugin, FlagDependencyExportsPlugin,
FlagDependencyUsagePlugin, InferAsyncModulesPlugin, JsPlugin, MangleExportsPlugin,
ModuleConcatenationPlugin, SideEffectsFlagPlugin,
};
use rspack_plugin_json::JsonPlugin;
use rspack_plugin_library::enable_library_plugin;
Expand Down Expand Up @@ -191,7 +191,7 @@ impl BuiltinPlugin {
match self.name {
// webpack also have these plugins
BuiltinPluginName::DefinePlugin => {
let plugin = DefinePlugin::new(downcast_into::<Define>(self.options)?).boxed();
let plugin = DefinePlugin::new(downcast_into(self.options)?).boxed();
plugins.push(plugin);
}
BuiltinPluginName::ProvidePlugin => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ pub struct RawBuiltins {
impl RawBuiltins {
pub fn apply(self) -> rspack_error::Result<Builtins> {
Ok(Builtins {
define: Default::default(),
provide: Default::default(),
})
}
Expand Down
6 changes: 6 additions & 0 deletions crates/rspack_core/src/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ impl Default for CompilationId {
}
}

type ValueCacheVersions = HashMap<String, String>;

static COMPILATION_ID: AtomicU32 = AtomicU32::new(0);

#[derive(Debug)]
Expand Down Expand Up @@ -168,6 +170,8 @@ pub struct Compilation {
pub missing_dependencies: IndexSet<PathBuf, BuildHasherDefault<FxHasher>>,
pub build_dependencies: IndexSet<PathBuf, BuildHasherDefault<FxHasher>>,

pub value_cache_versions: ValueCacheVersions,

import_var_map: DashMap<ModuleIdentifier, ImportVarMap>,

pub module_executor: Option<ModuleExecutor>,
Expand Down Expand Up @@ -250,6 +254,8 @@ impl Compilation {
missing_dependencies: Default::default(),
build_dependencies: Default::default(),

value_cache_versions: ValueCacheVersions::default(),

import_var_map: DashMap::new(),

module_executor,
Expand Down
4 changes: 3 additions & 1 deletion crates/rspack_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ pub use resolver::*;
pub mod concatenated_module;
pub mod reserved_names;

pub use rspack_loader_runner::{get_scheme, ResourceData, Scheme, BUILTIN_LOADER_PREFIX};
pub use rspack_loader_runner::{
get_scheme, AdditionalData, ResourceData, Scheme, BUILTIN_LOADER_PREFIX,
};
pub use rspack_macros::{impl_runtime_module, impl_source_map_config};
pub use rspack_sources;

Expand Down
15 changes: 11 additions & 4 deletions crates/rspack_core/src/normal_module_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ use crate::{
stringify_loaders_and_resource, BoxLoader, BoxModule, CompilerOptions, Context,
DependencyCategory, FuncUseCtx, GeneratorOptions, ModuleExt, ModuleFactory,
ModuleFactoryCreateData, ModuleFactoryResult, ModuleIdentifier, ModuleRule, ModuleRuleEnforce,
ModuleRuleUse, ModuleRuleUseLoader, ModuleType, NormalModule, ParserOptions, RawModule, Resolve,
ResolveArgs, ResolveOptionsWithDependencyType, ResolveResult, Resolver, ResolverFactory,
ResourceData, ResourceParsedData, RunnerContext, SharedPluginDriver,
ModuleRuleUse, ModuleRuleUseLoader, ModuleType, NormalModule, ParserAndGenerator, ParserOptions,
RawModule, Resolve, ResolveArgs, ResolveOptionsWithDependencyType, ResolveResult, Resolver,
ResolverFactory, ResourceData, ResourceParsedData, RunnerContext, SharedPluginDriver,
};

define_hook!(NormalModuleFactoryBeforeResolve: AsyncSeriesBail(data: &mut ModuleFactoryCreateData) -> bool);
Expand All @@ -26,6 +26,7 @@ define_hook!(NormalModuleFactoryResolveForScheme: AsyncSeriesBail(data: &mut Mod
define_hook!(NormalModuleFactoryAfterResolve: AsyncSeriesBail(data: &mut ModuleFactoryCreateData, create_data: &mut NormalModuleCreateData) -> bool);
define_hook!(NormalModuleFactoryCreateModule: AsyncSeriesBail(data: &mut ModuleFactoryCreateData, create_data: &mut NormalModuleCreateData) -> BoxModule);
define_hook!(NormalModuleFactoryModule: AsyncSeries(data: &mut ModuleFactoryCreateData, create_data: &mut NormalModuleCreateData, module: &mut BoxModule));
define_hook!(NormalModuleFactoryParser: SyncSeries(module_type: &ModuleType, parser: &mut dyn ParserAndGenerator, parser_options: Option<&ParserOptions>));
define_hook!(NormalModuleFactoryResolveLoader: AsyncSeriesBail(context: &Context, resolver: &Resolver, l: &ModuleRuleUseLoader) -> BoxLoader);

pub enum NormalModuleFactoryResolveResult {
Expand All @@ -42,6 +43,7 @@ pub struct NormalModuleFactoryHooks {
pub after_resolve: NormalModuleFactoryAfterResolveHook,
pub create_module: NormalModuleFactoryCreateModuleHook,
pub module: NormalModuleFactoryModuleHook,
pub parser: NormalModuleFactoryParserHook,
/// Webpack resolves loaders in `NormalModuleFactory`,
/// Rspack resolves it when normalizing configuration.
/// So this hook is used to resolve inline loader (inline loader requests).
Expand Down Expand Up @@ -500,7 +502,7 @@ impl NormalModuleFactory {
resolved_generator_options,
);
let resolved_side_effects = self.calculate_side_effects(&resolved_module_rules);
let resolved_parser_and_generator = self
let mut resolved_parser_and_generator = self
.plugin_driver
.registered_parser_and_generator_builder
.get(&resolved_module_type)
Expand All @@ -513,6 +515,11 @@ impl NormalModuleFactory {
resolved_parser_options.as_ref(),
resolved_generator_options.as_ref(),
);
self.plugin_driver.normal_module_factory_hooks.parser.call(
&resolved_module_type,
resolved_parser_and_generator.as_mut(),
resolved_parser_options.as_ref(),
)?;

let mut create_data = {
let mut create_data = NormalModuleCreateData {
Expand Down
30 changes: 1 addition & 29 deletions crates/rspack_core/src/options/builtins.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,10 @@
use std::fmt::Debug;

use rspack_error::Result;
pub use rspack_swc_visitors::{Define, Provide};
pub use rspack_swc_visitors::Provide;

use crate::{ApplyContext, CompilerOptions, Plugin, PluginContext};

#[derive(Debug)]
pub struct DefinePlugin {
options: Define,
}

impl DefinePlugin {
pub fn new(options: Define) -> Self {
Self { options }
}
}

impl Plugin for DefinePlugin {
fn name(&self) -> &'static str {
"rspack.DefinePlugin"
}

fn apply(
&self,
_ctx: PluginContext<&mut ApplyContext>,
options: &mut CompilerOptions,
) -> Result<()> {
options.builtins.define.extend(self.options.clone());
Ok(())
}
}

#[derive(Debug)]
pub struct ProvidePlugin {
options: Provide,
Expand Down Expand Up @@ -67,8 +41,6 @@ pub struct DecoratorOptions {

#[derive(Debug, Clone, Default)]
pub struct Builtins {
// TODO: refactor to string-replacement based
pub define: Define,
// TODO: refactor to string-replacement based
pub provide: Provide,
}
Expand Down
18 changes: 17 additions & 1 deletion crates/rspack_core/src/parser_and_generator.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use std::any::Any;
use std::fmt::Debug;

use derivative::Derivative;
use rspack_error::{Result, TWithDiagnosticArray};
use rspack_loader_runner::{AdditionalData, ResourceData};
use rspack_sources::BoxSource;
use rspack_util::ext::AsAny;
use rspack_util::source_map::SourceMapKind;
use swc_core::common::Span;

Expand Down Expand Up @@ -80,7 +82,7 @@ pub struct GenerateContext<'a> {
pub concatenation_scope: Option<&'a mut ConcatenationScope>,
}

pub trait ParserAndGenerator: Send + Sync + Debug {
pub trait ParserAndGenerator: Send + Sync + Debug + AsAny {
/// The source types that the generator can generate (the source types you can make requests for)
fn source_types(&self) -> &[SourceType];
/// Parse the source and return the dependencies and the ast or source
Expand All @@ -102,3 +104,17 @@ pub trait ParserAndGenerator: Send + Sync + Debug {
_cg: &ChunkGraph,
) -> Option<String>;
}

impl dyn ParserAndGenerator + '_ {
pub fn downcast_ref<D: Any>(&self) -> Option<&D> {
self.as_any().downcast_ref::<D>()
}

pub fn downcast_mut<D: Any>(&mut self) -> Option<&mut D> {
self.as_any_mut().downcast_mut::<D>()
}

pub fn is<D: Any>(&self) -> bool {
self.downcast_ref::<D>().is_some()
}
}
29 changes: 15 additions & 14 deletions crates/rspack_plugin_extract_css/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@ repository = "https://github.com/web-infra-dev/rspack"
version = "0.1.0"

[dependencies]
async-trait = { workspace = true }
once_cell = { workspace = true }
regex = { workspace = true }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hash = { path = "../rspack_hash" }
rspack_hook = { path = "../rspack_hook" }
rspack_identifier = { path = "../rspack_identifier" }
rspack_plugin_css = { path = "../rspack_plugin_css" }
rspack_plugin_runtime = { path = "../rspack_plugin_runtime" }
rspack_util = { path = "../rspack_util" }
rustc-hash = { workspace = true }
serde_json = { workspace = true }
ustr = { workspace = true }
async-trait = { workspace = true }
once_cell = { workspace = true }
regex = { workspace = true }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hash = { path = "../rspack_hash" }
rspack_hook = { path = "../rspack_hook" }
rspack_identifier = { path = "../rspack_identifier" }
rspack_plugin_css = { path = "../rspack_plugin_css" }
rspack_plugin_javascript = { path = "../rspack_plugin_javascript" }
rspack_plugin_runtime = { path = "../rspack_plugin_runtime" }
rspack_util = { path = "../rspack_util" }
rustc-hash = { workspace = true }
serde_json = { workspace = true }
ustr = { workspace = true }
4 changes: 2 additions & 2 deletions crates/rspack_plugin_extract_css/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![feature(let_chains)]
pub mod css_dependency;
mod css_module;
mod parser_and_generator;
pub use parser_and_generator::{CssExtractJsonData, CssExtractJsonDataList};
mod parser_plugin;
pub use parser_plugin::{CssExtractJsonData, CssExtractJsonDataList};
pub mod plugin;
mod runtime;
Loading
Loading