From 559c26697a21da978406d8edf381165853dcb9f1 Mon Sep 17 00:00:00 2001 From: shulaoda Date: Wed, 21 Aug 2024 17:51:43 +0800 Subject: [PATCH 1/2] refactor: resolve conflict dependency location --- .../src/build_chunk_graph/code_splitter.rs | 20 +++--- crates/rspack_core/src/chunk_group.rs | 15 +---- crates/rspack_core/src/context_module.rs | 22 +++---- crates/rspack_core/src/dependencies_block.rs | 65 +++---------------- .../src/dependency/dependency_location.rs | 65 +++++++++++++------ crates/rspack_core/src/lib.rs | 2 +- crates/rspack_core/src/stats/mod.rs | 9 +-- .../commonjs/common_js_require_dependency.rs | 35 +++++----- .../commonjs/require_header_dependency.rs | 25 +++---- .../common_js_imports_parse_plugin.rs | 15 ++--- .../src/parser_plugin/compatibility_plugin.rs | 10 +-- .../src/parser_plugin/import_parser_plugin.rs | 10 ++- .../src/parser_plugin/worker_plugin.rs | 10 ++- .../src/utils/eval/eval_binary_expr.rs | 17 +++-- .../src/utils/eval/mod.rs | 8 +-- .../src/module.rs | 11 +++- .../cannot-resolve-with-loader/stats.err | 2 +- .../factorize/empty-dependency/stats.err | 2 +- .../mismatched-module-type/stats.err | 2 +- .../tests/statsAPICases/chunks.js | 2 +- 20 files changed, 154 insertions(+), 193 deletions(-) diff --git a/crates/rspack_core/src/build_chunk_graph/code_splitter.rs b/crates/rspack_core/src/build_chunk_graph/code_splitter.rs index 05375b3656f..88c36667b6e 100644 --- a/crates/rspack_core/src/build_chunk_graph/code_splitter.rs +++ b/crates/rspack_core/src/build_chunk_graph/code_splitter.rs @@ -18,8 +18,8 @@ use crate::{ add_connection_states, assign_depth, assign_depths, get_entry_runtime, merge_runtime, AsyncDependenciesBlockIdentifier, ChunkGroup, ChunkGroupKind, ChunkGroupOptions, ChunkGroupUkey, ChunkLoading, ChunkUkey, Compilation, ConnectionId, ConnectionState, DependenciesBlock, - EntryDependency, EntryRuntime, GroupOptions, Logger, ModuleDependency, ModuleGraph, - ModuleIdentifier, OriginLocation, RuntimeSpec, SyntheticDependencyLocation, + DependencyLocation, EntryDependency, EntryRuntime, GroupOptions, Logger, ModuleDependency, + ModuleGraph, ModuleIdentifier, RuntimeSpec, SyntheticDependencyLocation, }; #[derive(Debug, Clone)] @@ -249,7 +249,7 @@ pub(super) struct CodeSplitter<'me> { fn add_chunk_in_group( group_options: Option<&GroupOptions>, module_id: ModuleIdentifier, - loc: Option, + loc: Option, request: Option, ) -> ChunkGroup { let options = ChunkGroupOptions::new( @@ -419,9 +419,9 @@ impl<'me> CodeSplitter<'me> { )); for request in requests { - let loc = Some(OriginLocation::Synthetic(SyntheticDependencyLocation { - name: name.clone(), - })); + let loc = Some(DependencyLocation::Synthetic( + SyntheticDependencyLocation::new(&name), + )); entrypoint.add_origin(None, loc, request); } @@ -1248,7 +1248,7 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on let chunk_name = block.get_group_options().and_then(|o| o.name()); let entry_options = block.get_group_options().and_then(|o| o.entry_options()); let request = block.request().clone(); - let loc = block.loc().cloned(); + let loc = block.loc(); let cgi = if let Some(entry_options) = entry_options { let cgi = @@ -1343,7 +1343,7 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on .block_by_id(&block_id) .expect("should have block"); let request = block.request().clone(); - let loc = block.loc().cloned(); + let loc = block.loc(); if self .compilation @@ -1367,7 +1367,7 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on let mut chunk_group = add_chunk_in_group( block.get_group_options(), module_id, - block.loc().map(|l| OriginLocation::Real(l.clone())), + block.loc(), block.request().clone(), ); let chunk = self.compilation.chunk_by_ukey.expect_get_mut(&chunk_ukey); @@ -1443,7 +1443,7 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on .compilation .chunk_group_by_ukey .expect_get_mut(&chunk_group_ukey); - chunk_group.add_origin(None, loc.map(OriginLocation::Real), request); + chunk_group.add_origin(None, loc, request); } } diff --git a/crates/rspack_core/src/chunk_group.rs b/crates/rspack_core/src/chunk_group.rs index 8450e84ebf9..f723a1efec0 100644 --- a/crates/rspack_core/src/chunk_group.rs +++ b/crates/rspack_core/src/chunk_group.rs @@ -15,21 +15,10 @@ use crate::{ use crate::{ChunkLoading, ChunkUkey, Compilation}; use crate::{LibraryOptions, ModuleIdentifier, PublicPath}; -#[derive(Debug, Clone)] -pub struct SyntheticDependencyLocation { - pub name: String, -} - -#[derive(Debug, Clone)] -pub enum OriginLocation { - Real(DependencyLocation), - Synthetic(SyntheticDependencyLocation), -} - #[derive(Debug, Clone)] pub struct OriginRecord { pub module_id: Option, - pub loc: Option, + pub loc: Option, pub request: Option, } @@ -313,7 +302,7 @@ impl ChunkGroup { pub fn add_origin( &mut self, module_id: Option, - loc: Option, + loc: Option, request: Option, ) { self.origins.push(OriginRecord { diff --git a/crates/rspack_core/src/context_module.rs b/crates/rspack_core/src/context_module.rs index 8b156c19554..c057e28282a 100644 --- a/crates/rspack_core/src/context_module.rs +++ b/crates/rspack_core/src/context_module.rs @@ -22,10 +22,11 @@ use crate::{ AsyncDependenciesBlockIdentifier, BoxDependency, BuildContext, BuildInfo, BuildMeta, BuildMetaDefaultObject, BuildMetaExportsType, BuildResult, ChunkGraph, ChunkGroupOptions, CodeGenerationResult, Compilation, ConcatenationScope, ContextElementDependency, - DependenciesBlock, Dependency, DependencyCategory, DependencyId, DependencyType, - DynamicImportMode, ExportsType, FactoryMeta, FakeNamespaceObjectMode, GroupOptions, - ImportAttributes, LibIdentOptions, Module, ModuleLayer, ModuleType, Resolve, ResolveInnerOptions, - ResolveOptionsWithDependencyType, ResolverFactory, RuntimeGlobals, RuntimeSpec, SourceType, + DependenciesBlock, Dependency, DependencyCategory, DependencyId, DependencyLocation, + DependencyType, DynamicImportMode, ExportsType, FactoryMeta, FakeNamespaceObjectMode, + GroupOptions, ImportAttributes, LibIdentOptions, Module, ModuleLayer, ModuleType, + RealDependencyLocation, Resolve, ResolveInnerOptions, ResolveOptionsWithDependencyType, + ResolverFactory, RuntimeGlobals, RuntimeSpec, SourceType, }; #[derive(Debug, Clone)] @@ -1110,15 +1111,13 @@ impl ContextModule { if matches!(self.options.context_options.mode, ContextMode::LazyOnce) && !context_element_dependencies.is_empty() { + let loc = RealDependencyLocation::new( + self.options.context_options.start, + self.options.context_options.end, + ); let mut block = AsyncDependenciesBlock::new( self.identifier, - Some( - ( - self.options.context_options.start, - self.options.context_options.end, - ) - .into(), - ), + Some(DependencyLocation::Real(loc)), None, context_element_dependencies .into_iter() @@ -1132,6 +1131,7 @@ impl ContextModule { blocks.push(Box::new(block)); } else if matches!(self.options.context_options.mode, ContextMode::Lazy) { let mut index = 0; + // TODO(shulaoda): add loc for ContextElementDependency and AsyncDependenciesBlock for context_element_dependency in context_element_dependencies { let group_options = self .options diff --git a/crates/rspack_core/src/dependencies_block.rs b/crates/rspack_core/src/dependencies_block.rs index f3e1f6a9e50..30481916797 100644 --- a/crates/rspack_core/src/dependencies_block.rs +++ b/crates/rspack_core/src/dependencies_block.rs @@ -1,16 +1,15 @@ -use std::{borrow::Cow, fmt::Display, hash::Hash, sync::Arc}; +use std::{borrow::Cow, hash::Hash}; -use derivative::Derivative; use rspack_collections::Identifier; use rspack_error::{ miette::{self, Diagnostic}, thiserror::{self, Error}, }; use rspack_util::ext::DynHash; -use swc_core::common::{BytePos, SourceMap}; use crate::{ - BoxDependency, Compilation, DependencyId, GroupOptions, ModuleIdentifier, RuntimeSpec, + BoxDependency, Compilation, DependencyId, DependencyLocation, GroupOptions, ModuleIdentifier, + RuntimeSpec, }; pub trait DependenciesBlock { @@ -43,53 +42,6 @@ pub fn dependencies_block_update_hash( } } -#[derive(Derivative)] -#[derivative(Debug, Clone)] -pub struct DependencyLocation { - start: u32, - end: u32, - #[derivative(Debug = "ignore")] - source: Option>, -} - -impl DependencyLocation { - pub fn new(start: u32, end: u32, source: Option>) -> Self { - Self { start, end, source } - } - - #[inline] - pub fn start(&self) -> u32 { - self.start - } - - #[inline] - pub fn end(&self) -> u32 { - self.end - } -} - -impl From<(u32, u32)> for DependencyLocation { - fn from(value: (u32, u32)) -> Self { - Self { - start: value.0, - end: value.1, - source: None, - } - } -} - -impl Display for DependencyLocation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if let Some(source) = &self.source { - let pos = source.lookup_char_pos(BytePos(self.start + 1)); - let pos = format!("{}:{}", pos.line, pos.col.0); - f.write_str(format!("{}-{}", pos, self.end - self.start).as_str()) - } else { - Ok(()) - } - } -} - #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct AsyncDependenciesBlockIdentifier(Identifier); @@ -124,10 +76,9 @@ impl AsyncDependenciesBlock { dependencies: Vec, request: Option, ) -> Self { - let loc_str: Cow = loc.clone().map_or_else( - || "".into(), - |loc| format!("|loc={}:{}", loc.start(), loc.end()).into(), - ); + let loc_str: Cow = loc + .clone() + .map_or_else(|| "".into(), |loc| format!("|loc={loc}").into()); let modifier_str: Cow = modifier.map_or_else( || "".into(), @@ -182,8 +133,8 @@ impl AsyncDependenciesBlock { std::mem::take(&mut self.blocks) } - pub fn loc(&self) -> Option<&DependencyLocation> { - self.loc.as_ref() + pub fn loc(&self) -> Option { + self.loc.clone() } pub fn parent(&self) -> &ModuleIdentifier { diff --git a/crates/rspack_core/src/dependency/dependency_location.rs b/crates/rspack_core/src/dependency/dependency_location.rs index 0addb9fb117..fc4519f31af 100644 --- a/crates/rspack_core/src/dependency/dependency_location.rs +++ b/crates/rspack_core/src/dependency/dependency_location.rs @@ -26,6 +26,16 @@ impl RealDependencyLocation { } } +impl From<(u32, u32)> for RealDependencyLocation { + fn from(range: (u32, u32)) -> Self { + Self { + start: range.0, + end: range.1, + source: None, + } + } +} + impl From for RealDependencyLocation { fn from(span: swc_core::common::Span) -> Self { Self { @@ -38,49 +48,62 @@ impl From for RealDependencyLocation { impl fmt::Display for RealDependencyLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let source = &self.source.clone().expect("missing sourcemap"); - let (start, end) = source.look_up_range_pos(self.start, self.end); + if let Some(source) = &self.source { + let (start, end) = source.look_up_range_pos(self.start, self.end); - if start.line == end.line { - if start.column == end.column { - return write!(f, "{}:{}", start.line, start.column); + if start.line == end.line { + if start.column == end.column { + return write!(f, "{}:{}", start.line, start.column); + } + + return write!(f, "{}:{}-{}", start.line, start.column, end.column); } - return write!(f, "{}:{}-{}", start.line, start.column, end.column); + write!( + f, + "{}:{}-{}:{}", + start.line, start.column, end.line, end.column + ) + } else { + write!(f, "{}:{}", self.start, self.end) } - - write!( - f, - "{}:{}-{}:{}", - start.line, start.column, end.line, end.column - ) } } #[derive(Debug, Clone)] -pub struct SyntheticDependencyName { +pub struct SyntheticDependencyLocation { pub name: String, } -impl SyntheticDependencyName { +impl SyntheticDependencyLocation { pub fn new(name: &str) -> Self { - SyntheticDependencyName { + SyntheticDependencyLocation { name: name.to_string(), } } } -impl fmt::Display for SyntheticDependencyName { +impl fmt::Display for SyntheticDependencyLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name) } } -// #[derive(Debug, Clone)] -// pub enum DependencyLocation { -// Real(RealDependencyLocation), -// Synthetic(SyntheticDependencyName), -// } +#[derive(Debug, Clone)] +pub enum DependencyLocation { + Real(RealDependencyLocation), + Synthetic(SyntheticDependencyLocation), +} + +impl fmt::Display for DependencyLocation { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let loc = match self { + DependencyLocation::Real(real) => real.to_string(), + DependencyLocation::Synthetic(synthetic) => synthetic.to_string(), + }; + write!(f, "{loc}") + } +} #[derive(Debug, Clone, Copy)] pub struct SourcePosition { diff --git a/crates/rspack_core/src/lib.rs b/crates/rspack_core/src/lib.rs index d8a6fcbd4b7..dce5faf30c7 100644 --- a/crates/rspack_core/src/lib.rs +++ b/crates/rspack_core/src/lib.rs @@ -10,7 +10,7 @@ use std::{fmt, sync::Arc}; mod dependencies_block; pub mod diagnostics; pub use dependencies_block::{ - AsyncDependenciesBlock, AsyncDependenciesBlockIdentifier, DependenciesBlock, DependencyLocation, + AsyncDependenciesBlock, AsyncDependenciesBlockIdentifier, DependenciesBlock, }; mod fake_namespace_object; mod template; diff --git a/crates/rspack_core/src/stats/mod.rs b/crates/rspack_core/src/stats/mod.rs index 0b0b71a3eba..3be0208003f 100644 --- a/crates/rspack_core/src/stats/mod.rs +++ b/crates/rspack_core/src/stats/mod.rs @@ -18,8 +18,8 @@ pub use r#struct::*; use crate::{ BoxModule, BoxRuntimeModule, Chunk, ChunkGroupOrderKey, ChunkGroupUkey, ChunkUkey, Compilation, - ExecutedRuntimeModule, LogType, ModuleGraph, ModuleIdentifier, OriginLocation, ProvidedExports, - SourceType, UsedExports, + ExecutedRuntimeModule, LogType, ModuleGraph, ModuleIdentifier, ProvidedExports, SourceType, + UsedExports, }; #[derive(Debug, Clone)] @@ -350,10 +350,7 @@ impl Stats<'_> { loc: origin .loc .as_ref() - .map(|loc| match loc { - OriginLocation::Real(l) => format!("{l}"), - OriginLocation::Synthetic(l) => l.name.to_string(), - }) + .map(|loc| loc.to_string()) .unwrap_or_default(), request: origin.request.clone().unwrap_or_default(), } diff --git a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_require_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_require_dependency.rs index b871c5bc479..f6b54ad099f 100644 --- a/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_require_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/commonjs/common_js_require_dependency.rs @@ -1,37 +1,31 @@ -use std::sync::Arc; - -use rspack_core::{module_id, Compilation, RuntimeSpec}; -use rspack_core::{AsContextDependency, Dependency, DependencyCategory, DependencyLocation}; +use rspack_core::{module_id, Compilation, RealDependencyLocation, RuntimeSpec}; +use rspack_core::{AsContextDependency, Dependency, DependencyCategory}; use rspack_core::{DependencyId, DependencyTemplate}; use rspack_core::{DependencyType, ErrorSpan, ModuleDependency}; use rspack_core::{TemplateContext, TemplateReplaceSource}; -use swc_core::common::SourceMap; #[derive(Debug, Clone)] pub struct CommonJsRequireDependency { id: DependencyId, request: String, optional: bool, - loc: DependencyLocation, - span: Option, + range: Option, + range_expr: RealDependencyLocation, } impl CommonJsRequireDependency { pub fn new( request: String, - span: Option, - start: u32, - end: u32, - source: Option>, + range: Option, + range_expr: RealDependencyLocation, optional: bool, ) -> Self { - let loc = DependencyLocation::new(start, end, source); Self { id: DependencyId::new(), request, optional, - loc, - span, + range, + range_expr, } } } @@ -41,6 +35,10 @@ impl Dependency for CommonJsRequireDependency { &self.id } + fn loc(&self) -> Option { + self.range.clone().map(|range| range.to_string()) + } + fn category(&self) -> &DependencyCategory { &DependencyCategory::CommonJS } @@ -50,7 +48,10 @@ impl Dependency for CommonJsRequireDependency { } fn span(&self) -> Option { - self.span + self + .range + .clone() + .map(|range| ErrorSpan::new(range.start, range.end)) } } @@ -79,8 +80,8 @@ impl DependencyTemplate for CommonJsRequireDependency { code_generatable_context: &mut TemplateContext, ) { source.replace( - self.loc.start(), - self.loc.end() - 1, + self.range_expr.start, + self.range_expr.end - 1, module_id( code_generatable_context.compilation, &self.id, diff --git a/crates/rspack_plugin_javascript/src/dependency/commonjs/require_header_dependency.rs b/crates/rspack_plugin_javascript/src/dependency/commonjs/require_header_dependency.rs index 105c1b31531..f0db79cd24c 100644 --- a/crates/rspack_plugin_javascript/src/dependency/commonjs/require_header_dependency.rs +++ b/crates/rspack_plugin_javascript/src/dependency/commonjs/require_header_dependency.rs @@ -1,22 +1,21 @@ -use std::sync::Arc; - -use rspack_core::{AsContextDependency, AsModuleDependency, Compilation, Dependency, RuntimeSpec}; -use rspack_core::{DependencyId, DependencyLocation}; +use rspack_core::DependencyId; +use rspack_core::{ + AsContextDependency, AsModuleDependency, Compilation, Dependency, RealDependencyLocation, + RuntimeSpec, +}; use rspack_core::{DependencyTemplate, RuntimeGlobals, TemplateContext}; -use swc_core::common::SourceMap; #[derive(Debug, Clone)] pub struct RequireHeaderDependency { id: DependencyId, - loc: DependencyLocation, + range: RealDependencyLocation, } impl RequireHeaderDependency { - pub fn new(start: u32, end: u32, source: Option>) -> Self { - let loc = DependencyLocation::new(start, end, source); + pub fn new(range: RealDependencyLocation) -> Self { Self { id: DependencyId::new(), - loc, + range, } } } @@ -25,6 +24,10 @@ impl Dependency for RequireHeaderDependency { fn id(&self) -> &DependencyId { &self.id } + + fn loc(&self) -> Option { + Some(self.range.to_string()) + } } impl AsModuleDependency for RequireHeaderDependency {} @@ -42,8 +45,8 @@ impl DependencyTemplate for RequireHeaderDependency { } = code_generatable_context; runtime_requirements.insert(RuntimeGlobals::REQUIRE); source.replace( - self.loc.start(), - self.loc.end() - 1, + self.range.start, + self.range.end, RuntimeGlobals::REQUIRE.name(), None, ); diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/common_js_imports_parse_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/common_js_imports_parse_plugin.rs index 9f520d365fb..a9172bc98c2 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/common_js_imports_parse_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/common_js_imports_parse_plugin.rs @@ -113,12 +113,11 @@ impl CommonJsImportsParserPlugin { param: &BasicEvaluatedExpression, ) -> Option { param.is_string().then(|| { + let range_expr: RealDependencyLocation = param.range().into(); let dep = CommonJsRequireDependency::new( param.string().to_string(), Some(span.into()), - param.range().0, - param.range().1, - Some(parser.source_map.clone()), + range_expr.with_source(parser.source_map.clone()), parser.in_try, ); parser.dependencies.push(Box::new(dep)); @@ -177,12 +176,11 @@ impl CommonJsImportsParserPlugin { } } if !is_expression { + let range: RealDependencyLocation = call_expr.callee.span().into(); parser .presentational_dependencies .push(Box::new(RequireHeaderDependency::new( - call_expr.callee.span().real_lo(), - call_expr.callee.span().hi().0, - Some(parser.source_map.clone()), + range.with_source(parser.source_map.clone()), ))); return Some(true); } @@ -195,12 +193,11 @@ impl CommonJsImportsParserPlugin { { self.process_require_context(parser, call_expr, ¶m); } else { + let range: RealDependencyLocation = call_expr.callee.span().into(); parser .presentational_dependencies .push(Box::new(RequireHeaderDependency::new( - call_expr.callee.span().real_lo(), - call_expr.callee.span_hi().0, - Some(parser.source_map.clone()), + range.with_source(parser.source_map.clone()), ))); } Some(true) diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs index 6d42b53a1c1..63d39a7e4f7 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/compatibility_plugin.rs @@ -1,5 +1,5 @@ use rspack_core::{ - ConstDependency, ContextDependency, DependencyLocation, RuntimeGlobals, SpanExt, + ConstDependency, ContextDependency, RealDependencyLocation, RuntimeGlobals, SpanExt, }; use swc_core::{common::Spanned, ecma::ast::CallExpr}; @@ -15,7 +15,7 @@ const NESTED_WEBPACK_IDENTIFIER_TAG: &str = "_identifier__nested_webpack_identif struct NestedRequireData { name: String, update: bool, - loc: DependencyLocation, + loc: RealDependencyLocation, } pub struct CompatibilityPlugin; @@ -67,7 +67,7 @@ impl CompatibilityPlugin { Some(NestedRequireData { name: rename, update: false, - loc: DependencyLocation::new(start, end, Some(parser.source_map.clone())), + loc: RealDependencyLocation::new(start, end).with_source(parser.source_map.clone()), }), ); } @@ -182,8 +182,8 @@ impl JavascriptParserPlugin for CompatibilityPlugin { let name = nested_require_data.name.clone(); if !nested_require_data.update { deps.push(ConstDependency::new( - nested_require_data.loc.start(), - nested_require_data.loc.end(), + nested_require_data.loc.start, + nested_require_data.loc.end, name.clone().into(), None, )); diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/import_parser_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/import_parser_plugin.rs index edb0162a5ed..fc1a9cab507 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/import_parser_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/import_parser_plugin.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use rspack_core::{ AsyncDependenciesBlock, DependencyLocation, DynamicImportMode, ErrorSpan, GroupOptions, - ImportAttributes, + ImportAttributes, RealDependencyLocation, }; use rspack_core::{ChunkGroupOptions, DynamicImportFetchPriority}; use rspack_core::{ContextNameSpaceObject, ContextOptions, DependencyCategory, SpanExt}; @@ -128,13 +128,11 @@ impl JavascriptParserPlugin for ImportParserPlugin { exports, attributes, )); + let loc = + RealDependencyLocation::new(span.start, span.end).with_source(parser.source_map.clone()); let mut block = AsyncDependenciesBlock::new( *parser.module_identifier, - Some(DependencyLocation::new( - span.start, - span.end, - Some(parser.source_map.clone()), - )), + Some(DependencyLocation::Real(loc)), None, vec![dep], Some(param.string().clone()), diff --git a/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs b/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs index e729816f46a..f9f5667b4e9 100644 --- a/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs +++ b/crates/rspack_plugin_javascript/src/parser_plugin/worker_plugin.rs @@ -5,7 +5,7 @@ use itertools::Itertools; use regex::Regex; use rspack_core::{ AsyncDependenciesBlock, ConstDependency, DependencyLocation, EntryOptions, ErrorSpan, - GroupOptions, SpanExt, + GroupOptions, RealDependencyLocation, SpanExt, }; use rspack_hash::RspackHash; use rustc_hash::{FxHashMap, FxHashSet}; @@ -97,13 +97,11 @@ fn add_dependencies( output_options.worker_public_path.clone(), Some(span), )); + let loc = + RealDependencyLocation::new(span.start, span.end).with_source(parser.source_map.clone()); let mut block = AsyncDependenciesBlock::new( *parser.module_identifier, - Some(DependencyLocation::new( - span.start, - span.end, - Some(parser.source_map.clone()), - )), + Some(DependencyLocation::Real(loc)), None, vec![dep], None, diff --git a/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs b/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs index 7190a60466e..a6f58993b5e 100644 --- a/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs +++ b/crates/rspack_plugin_javascript/src/utils/eval/eval_binary_expr.rs @@ -1,4 +1,4 @@ -use rspack_core::{DependencyLocation, SpanExt}; +use rspack_core::{RealDependencyLocation, SpanExt}; use swc_core::{ common::Spanned, ecma::ast::{BinExpr, BinaryOp}, @@ -512,17 +512,16 @@ pub fn eval_binary_expression( } fn join_locations( - start: Option<&DependencyLocation>, - end: Option<&DependencyLocation>, + start: Option<&RealDependencyLocation>, + end: Option<&RealDependencyLocation>, ) -> (u32, u32) { match (start, end) { (None, None) => unreachable!("invalid range"), - (None, Some(end)) => (end.start(), end.end()), - (Some(start), None) => (start.start(), start.end()), - (Some(start), Some(end)) => join_ranges( - Some((start.start(), start.end())), - Some((end.start(), end.end())), - ), + (None, Some(end)) => (end.start, end.end), + (Some(start), None) => (start.start, start.end), + (Some(start), Some(end)) => { + join_ranges(Some((start.start, start.end)), Some((end.start, end.end))) + } } } diff --git a/crates/rspack_plugin_javascript/src/utils/eval/mod.rs b/crates/rspack_plugin_javascript/src/utils/eval/mod.rs index e4acae62216..d329332dd19 100644 --- a/crates/rspack_plugin_javascript/src/utils/eval/mod.rs +++ b/crates/rspack_plugin_javascript/src/utils/eval/mod.rs @@ -11,7 +11,7 @@ mod eval_unary_expr; use bitflags::bitflags; use num_bigint::BigInt; -use rspack_core::DependencyLocation; +use rspack_core::RealDependencyLocation; use swc_core::atoms::Atom; use swc_core::common::Span; @@ -60,7 +60,7 @@ type Regexp = (String, String); // (expr, flags) #[derive(Debug, Clone)] pub struct BasicEvaluatedExpression { ty: Ty, - range: Option, + range: Option, falsy: bool, truthy: bool, side_effects: bool, @@ -442,7 +442,7 @@ impl BasicEvaluatedExpression { } pub fn set_range(&mut self, start: u32, end: u32) { - self.range = Some(DependencyLocation::new(start, end, None)) + self.range = Some(RealDependencyLocation::new(start, end)) } pub fn set_template_string( @@ -525,7 +525,7 @@ impl BasicEvaluatedExpression { pub fn range(&self) -> (u32, u32) { let range = self.range.clone().expect("range should not empty"); - (range.start(), range.end()) + (range.start, range.end) } pub fn prefix(&self) -> Option<&BasicEvaluatedExpression> { diff --git a/crates/rspack_plugin_lazy_compilation/src/module.rs b/crates/rspack_plugin_lazy_compilation/src/module.rs index 94f58eec537..a12d595f9c2 100644 --- a/crates/rspack_plugin_lazy_compilation/src/module.rs +++ b/crates/rspack_plugin_lazy_compilation/src/module.rs @@ -7,8 +7,8 @@ use rspack_core::{ AsyncDependenciesBlock, AsyncDependenciesBlockIdentifier, BoxDependency, BuildContext, BuildInfo, BuildMeta, BuildResult, CodeGenerationData, CodeGenerationResult, Compilation, ConcatenationScope, Context, DependenciesBlock, DependencyId, FactoryMeta, Module, - ModuleFactoryCreateData, ModuleIdentifier, ModuleLayer, ModuleType, RuntimeGlobals, RuntimeSpec, - SourceType, TemplateContext, + ModuleFactoryCreateData, ModuleIdentifier, ModuleLayer, ModuleType, RealDependencyLocation, + RuntimeGlobals, RuntimeSpec, SourceType, TemplateContext, }; use rspack_error::{Diagnosable, Diagnostic, Result}; use rspack_plugin_javascript::dependency::CommonJsRequireDependency; @@ -136,7 +136,12 @@ impl Module for LazyCompilationProxyModule { _build_context: BuildContext<'_>, _compilation: Option<&Compilation>, ) -> Result { - let client_dep = CommonJsRequireDependency::new(self.client.clone(), None, 0, 0, None, false); + let client_dep = CommonJsRequireDependency::new( + self.client.clone(), + None, + RealDependencyLocation::new(0, 0), + false, + ); let mut dependencies = vec![]; let mut blocks = vec![]; diff --git a/packages/rspack-test-tools/tests/diagnosticsCases/factorize/cannot-resolve-with-loader/stats.err b/packages/rspack-test-tools/tests/diagnosticsCases/factorize/cannot-resolve-with-loader/stats.err index ffdc4d0508c..a2e53cf1982 100644 --- a/packages/rspack-test-tools/tests/diagnosticsCases/factorize/cannot-resolve-with-loader/stats.err +++ b/packages/rspack-test-tools/tests/diagnosticsCases/factorize/cannot-resolve-with-loader/stats.err @@ -1,4 +1,4 @@ -ERROR in ./index.js +ERROR in ./index.js 45:59 × Module not found: Can't resolve './a' in '/tests/diagnosticsCases/factorize/cannot-resolve-with-loader' ╭─[2:0] 1 │ // THIS SHOULD BE INCLUDED IN THE DIAGNOSTIC diff --git a/packages/rspack-test-tools/tests/diagnosticsCases/factorize/empty-dependency/stats.err b/packages/rspack-test-tools/tests/diagnosticsCases/factorize/empty-dependency/stats.err index d80ded7633d..047f5fd0f40 100644 --- a/packages/rspack-test-tools/tests/diagnosticsCases/factorize/empty-dependency/stats.err +++ b/packages/rspack-test-tools/tests/diagnosticsCases/factorize/empty-dependency/stats.err @@ -1,4 +1,4 @@ -ERROR in ./index.js +ERROR in ./index.js 0:11 × Empty dependency: Expected a non-empty request ╭─[1:0] 1 │ require("") diff --git a/packages/rspack-test-tools/tests/diagnosticsCases/factorize/mismatched-module-type/stats.err b/packages/rspack-test-tools/tests/diagnosticsCases/factorize/mismatched-module-type/stats.err index 4345ffff0a1..aa9d9c9de22 100644 --- a/packages/rspack-test-tools/tests/diagnosticsCases/factorize/mismatched-module-type/stats.err +++ b/packages/rspack-test-tools/tests/diagnosticsCases/factorize/mismatched-module-type/stats.err @@ -116,5 +116,5 @@ ERROR in ./app.ts help: You may need an appropriate loader to handle this file type. -ERROR in ./index.js +ERROR in ./index.js 639:659 × No parser registered for 'ts' \ No newline at end of file diff --git a/packages/rspack-test-tools/tests/statsAPICases/chunks.js b/packages/rspack-test-tools/tests/statsAPICases/chunks.js index 803aceb173c..49f47eea9e2 100644 --- a/packages/rspack-test-tools/tests/statsAPICases/chunks.js +++ b/packages/rspack-test-tools/tests/statsAPICases/chunks.js @@ -110,7 +110,7 @@ module.exports = { ], "origins": Array [ Object { - "loc": "2:9-46", + "loc": "2:9-55", "module": "/tests/fixtures/chunk-b.js", "moduleId": "725", "moduleIdentifier": "/tests/fixtures/chunk-b.js", From 2cf571c9382a50ac808105dbeebf2e82eb0460ea Mon Sep 17 00:00:00 2001 From: shulaoda Date: Wed, 21 Aug 2024 18:16:07 +0800 Subject: [PATCH 2/2] chore: update snapshots --- .../__snapshots__/StatsTestCases.basictest.js.snap | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/webpack-test/__snapshots__/StatsTestCases.basictest.js.snap b/tests/webpack-test/__snapshots__/StatsTestCases.basictest.js.snap index d6481b8c978..9a61ef195b6 100644 --- a/tests/webpack-test/__snapshots__/StatsTestCases.basictest.js.snap +++ b/tests/webpack-test/__snapshots__/StatsTestCases.basictest.js.snap @@ -724,7 +724,7 @@ Rspack x.x.x compiled successfully" `; exports[`StatsTestCases should print correct stats for module-not-found-error 1`] = ` -"ERROR in ./index.js +"ERROR in ./index.js 0:17 × Module not found: Can't resolve 'buffer' in 'Xdir/module-not-found-error' ╭─[1:0] 1 │ require('buffer') @@ -732,7 +732,7 @@ exports[`StatsTestCases should print correct stats for module-not-found-error 1` 2 │ require('os') ╰──── -ERROR in ./index.js +ERROR in ./index.js 18:31 × Module not found: Can't resolve 'os' in 'Xdir/module-not-found-error' ╭─[2:0] 1 │ require('buffer') @@ -763,7 +763,7 @@ modules with errors 53 bytes [errors] ./index.js 19 bytes [built] [code generated] ./inner.js 53 bytes [built] [code generated] -ERROR in ./not-existing.js +ERROR in ./not-existing.js 0:25 × Module not found: Can't resolve 'does-not-exist' in 'Xdir/module-trace-disabled-in-error' ╭──── 1 │ require('does-not-exist') @@ -796,7 +796,7 @@ modules with errors 53 bytes [errors] ./index.js 19 bytes [built] [code generated] ./inner.js 53 bytes [built] [code generated] -ERROR in ./not-existing.js +ERROR in ./not-existing.js 0:25 × Module not found: Can't resolve 'does-not-exist' in 'Xdir/module-trace-enabled-in-error' ╭──── 1 │ require('does-not-exist') @@ -1115,7 +1115,7 @@ LOG from LogTestPlugin Error + 14 hidden lines -ERROR in ./index.js +ERROR in ./index.js 0:25 × Module not found: Can't resolve 'does-not-exist' in 'Xdir/preset-errors-only-error' ╭──── 1 │ require('does-not-exist')