From 825334366ef1b70190d38f2e3ea42cbd7596a929 Mon Sep 17 00:00:00 2001 From: Hana Date: Mon, 4 Dec 2023 22:22:22 +0800 Subject: [PATCH] feat: align module error --- crates/node_binding/binding.d.ts | 4 +- .../src/options/raw_module/js_loader.rs | 11 +- .../rspack_binding_values/src/compilation.rs | 10 +- crates/rspack_core/src/cache/mod.rs | 15 +- .../src/cache/occasion/build_module.rs | 332 +++++++++--------- .../rspack_core/src/compiler/compilation.rs | 18 +- crates/rspack_core/src/compiler/queue.rs | 123 ++++--- crates/rspack_core/src/context_module.rs | 2 +- .../rspack_core/src/context_module_factory.rs | 2 +- crates/rspack_core/src/dependencies_block.rs | 6 +- crates/rspack_core/src/diagnostics.rs | 4 + crates/rspack_core/src/external_module.rs | 2 +- crates/rspack_core/src/lib.rs | 1 + .../mf/container/container_entry_module.rs | 2 +- .../container_entry_module_factory.rs | 2 +- .../src/mf/container/remote_module.rs | 2 +- .../src/mf/sharing/consume_shared_module.rs | 2 +- .../src/mf/sharing/provide_shared_module.rs | 2 +- .../sharing/provide_shared_module_factory.rs | 2 +- crates/rspack_core/src/module.rs | 2 +- crates/rspack_core/src/normal_module.rs | 5 +- .../rspack_core/src/normal_module_factory.rs | 17 +- .../rspack_core/src/plugin/plugin_driver.rs | 6 +- crates/rspack_core/src/raw_module.rs | 2 +- .../rspack_core/src/tree_shaking/optimizer.rs | 2 +- crates/rspack_error/src/diagnostic.rs | 182 ++++++++-- crates/rspack_error/src/emitter.rs | 53 ++- crates/rspack_error/src/error.rs | 8 +- crates/rspack_error/src/lib.rs | 32 +- crates/rspack_loader_runner/src/runner.rs | 6 +- crates/rspack_loader_sass/src/lib.rs | 10 +- crates/rspack_loader_swc/src/lib.rs | 6 +- crates/rspack_plugin_asset/src/lib.rs | 2 +- crates/rspack_plugin_copy/src/lib.rs | 14 +- .../src/parser_and_generator/mod.rs | 2 +- .../rspack_plugin_css/src/swc_css_compiler.rs | 2 +- crates/rspack_plugin_css/src/visitors/mod.rs | 13 +- crates/rspack_plugin_html/src/parser.rs | 8 +- .../src/parser_and_generator/mod.rs | 6 +- .../rspack_plugin_javascript/src/utils/mod.rs | 12 +- .../dependency/import_meta_scanner.rs | 8 +- .../src/visitors/dependency/mod.rs | 6 +- crates/rspack_plugin_json/src/lib.rs | 4 +- .../rspack_plugin_swc_js_minimizer/src/lib.rs | 4 +- .../src/lib.rs | 6 +- .../src/parser_and_generator.rs | 10 +- 46 files changed, 589 insertions(+), 381 deletions(-) create mode 100644 crates/rspack_core/src/diagnostics.rs diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index a3b0ae2ffb2f..5a135a6cd657 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -34,7 +34,7 @@ export class JsCompilation { getMissingDependencies(): Array getBuildDependencies(): Array pushDiagnostic(severity: "error" | "warning", title: string, message: string): void - pushNativeDiagnostics(diagnostics: ExternalObject<'Diagnostic[]'>): void + pushNativeDiagnostics(diagnostics: ExternalObject<'RspackDiagnostic[]'>): void getStats(): JsStats getAssetPath(filename: string, data: PathData): string getAssetPathWithInfo(filename: string, data: PathData): PathWithInfo @@ -345,7 +345,7 @@ export interface JsLoaderContext { * Internal loader diagnostic * @internal */ - diagnosticsExternal: ExternalObject<'Diagnostic[]'> + diagnosticsExternal: ExternalObject<'RspackDiagnostic[]'> } export interface JsModule { diff --git a/crates/rspack_binding_options/src/options/raw_module/js_loader.rs b/crates/rspack_binding_options/src/options/raw_module/js_loader.rs index 1ba821c24274..52bb37ded60f 100644 --- a/crates/rspack_binding_options/src/options/raw_module/js_loader.rs +++ b/crates/rspack_binding_options/src/options/raw_module/js_loader.rs @@ -5,7 +5,7 @@ use std::{ use napi_derive::napi; use rspack_core::{rspack_sources::SourceMap, Content, ResourceData}; -use rspack_error::Diagnostic; +use rspack_error::RspackDiagnostic; use rspack_loader_runner::AdditionalData; use rustc_hash::FxHashSet as HashSet; use tracing::{span_enabled, Level}; @@ -261,8 +261,8 @@ pub struct JsLoaderContext { pub context_external: External, /// Internal loader diagnostic /// @internal - #[napi(ts_type = "ExternalObject<'Diagnostic[]'>")] - pub diagnostics_external: External>, + #[napi(ts_type = "ExternalObject<'RspackDiagnostic[]'>")] + pub diagnostics_external: External>, } impl TryFrom<&rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>> @@ -322,7 +322,10 @@ impl TryFrom<&rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>> additional_data_external: External::new(cx.additional_data.clone()), context_external: External::new(cx.context.clone()), - diagnostics_external: External::new(cx.__diagnostics.clone()), + diagnostics_external: External::new({ + eprintln!("Should be able to pipe diagnostic errors"); + vec![] + }), }) } } diff --git a/crates/rspack_binding_values/src/compilation.rs b/crates/rspack_binding_values/src/compilation.rs index ec57e2c4c66f..8c18cbb2294a 100644 --- a/crates/rspack_binding_values/src/compilation.rs +++ b/crates/rspack_binding_values/src/compilation.rs @@ -10,7 +10,7 @@ use rspack_core::rspack_sources::BoxSource; use rspack_core::AssetInfo; use rspack_core::ModuleIdentifier; use rspack_core::{rspack_sources::SourceExt, NormalModuleSource}; -use rspack_error::Diagnostic; +use rspack_error::RspackDiagnostic; use rspack_identifier::Identifier; use rspack_napi_shared::NapiResultExt; @@ -315,14 +315,14 @@ impl JsCompilation { #[napi(ts_args_type = r#"severity: "error" | "warning", title: string, message: string"#)] pub fn push_diagnostic(&mut self, severity: String, title: String, message: String) { let diagnostic = match severity.as_str() { - "warning" => rspack_error::Diagnostic::warn(title, message, 0, 0), - _ => rspack_error::Diagnostic::error(title, message, 0, 0), + "warning" => rspack_error::RspackDiagnostic::warn(title, message, 0, 0), + _ => rspack_error::RspackDiagnostic::error(title, message, 0, 0), }; self.inner.push_diagnostic(diagnostic); } - #[napi(ts_args_type = r#"diagnostics: ExternalObject<'Diagnostic[]'>"#)] - pub fn push_native_diagnostics(&mut self, mut diagnostics: External>) { + #[napi(ts_args_type = r#"diagnostics: ExternalObject<'RspackDiagnostic[]'>"#)] + pub fn push_native_diagnostics(&mut self, mut diagnostics: External>) { while let Some(diagnostic) = diagnostics.pop() { self.inner.push_diagnostic(diagnostic); } diff --git a/crates/rspack_core/src/cache/mod.rs b/crates/rspack_core/src/cache/mod.rs index cc3af1c9487f..419eb5b603ad 100644 --- a/crates/rspack_core/src/cache/mod.rs +++ b/crates/rspack_core/src/cache/mod.rs @@ -14,7 +14,10 @@ mod snapshot; mod storage; pub use local::*; use occasion::{ - BuildModuleOccasion, CodeGenerateOccasion, CreateChunkAssetsOccasion, ResolveModuleOccasion, + // BuildModuleOccasion, + CodeGenerateOccasion, + CreateChunkAssetsOccasion, + ResolveModuleOccasion, }; use snapshot::SnapshotManager; use storage::new_storage; @@ -24,7 +27,7 @@ pub struct Cache { is_idle: AtomicBool, snapshot_manager: Arc, pub resolve_module_occasion: ResolveModuleOccasion, - pub build_module_occasion: BuildModuleOccasion, + // pub build_module_occasion: BuildModuleOccasion, pub code_generate_occasion: CodeGenerateOccasion, pub create_chunk_assets_occasion: CreateChunkAssetsOccasion, } @@ -39,10 +42,10 @@ impl Cache { new_storage(&options.cache), snapshot_manager.clone(), ), - build_module_occasion: BuildModuleOccasion::new( - new_storage(&options.cache), - snapshot_manager, - ), + // build_module_occasion: BuildModuleOccasion::new( + // new_storage(&options.cache), + // snapshot_manager, + // ), code_generate_occasion: CodeGenerateOccasion::new(new_storage(&options.cache)), create_chunk_assets_occasion: CreateChunkAssetsOccasion::new(new_storage(&options.cache)), } diff --git a/crates/rspack_core/src/cache/occasion/build_module.rs b/crates/rspack_core/src/cache/occasion/build_module.rs index c5142e4d05eb..59d0f9e74850 100644 --- a/crates/rspack_core/src/cache/occasion/build_module.rs +++ b/crates/rspack_core/src/cache/occasion/build_module.rs @@ -1,180 +1,180 @@ -use std::{collections::HashMap, path::Path, sync::Arc}; +// use std::{collections::HashMap, path::Path, sync::Arc}; -use futures::Future; -use rkyv::AlignedVec; -use rspack_error::{Result, TWithDiagnosticArray}; -use rspack_identifier::Identifier; +// use futures::Future; +// use rkyv::AlignedVec; +// use rspack_error::{Result, TWithDiagnosticArray}; +// use rspack_identifier::Identifier; -use crate::{ - cache::snapshot::{Snapshot, SnapshotManager}, - cache::storage, - BoxModule, BuildExtraDataType, BuildResult, DependencyTemplate, ModuleDependency, - NormalModuleSource, -}; +// use crate::{ +// cache::snapshot::{Snapshot, SnapshotManager}, +// cache::storage, +// BoxModule, BuildExtraDataType, BuildResult, DependencyTemplate, ModuleDependency, +// NormalModuleSource, +// }; -#[derive(Debug, Clone)] -pub struct NormalModuleStorageData { - source: NormalModuleSource, - code_generation_dependencies: Option>>, - presentational_dependencies: Option>>, -} +// #[derive(Debug, Clone)] +// pub struct NormalModuleStorageData { +// source: NormalModuleSource, +// code_generation_dependencies: Option>>, +// presentational_dependencies: Option>>, +// } -type NormalModuleStorageExtraData = HashMap; +// type NormalModuleStorageExtraData = HashMap; -type Storage = dyn storage::Storage<( - // file system info, None when not cacheable - Option, - // build result - TWithDiagnosticArray, - // module data - Option, - // parser and generator data - Option, -)>; +// type Storage = dyn storage::Storage<( +// // file system info, None when not cacheable +// Option, +// // build result +// TWithDiagnosticArray, +// // module data +// Option, +// // parser and generator data +// Option, +// )>; -#[derive(Debug)] -pub struct BuildModuleOccasion { - storage: Option>, - snapshot_manager: Arc, -} +// #[derive(Debug)] +// pub struct BuildModuleOccasion { +// storage: Option>, +// snapshot_manager: Arc, +// } -impl BuildModuleOccasion { - pub fn new(storage: Option>, snapshot_manager: Arc) -> Self { - Self { - storage, - snapshot_manager, - } - } +// impl BuildModuleOccasion { +// pub fn new(storage: Option>, snapshot_manager: Arc) -> Self { +// Self { +// storage, +// snapshot_manager, +// } +// } - pub fn remove_cache(&self, id: &Identifier) { - if let Some(s) = self.storage.as_ref() { - s.remove(id); - } - } +// pub fn remove_cache(&self, id: &Identifier) { +// if let Some(s) = self.storage.as_ref() { +// s.remove(id); +// } +// } - pub async fn use_cache<'a, G, F>( - &self, - module: &'a mut BoxModule, - generator: G, - ) -> Result<(Result>, bool)> - where - G: Fn(&'a mut BoxModule) -> F, - F: Future, &'a mut BoxModule)>>, - { - let storage = match &self.storage { - Some(s) => s, - // no cache return directly - None => return Ok((Ok(generator(module).await?.0), false)), - }; +// pub async fn use_cache<'a, G, F>( +// &self, +// module: &'a mut BoxModule, +// generator: G, +// ) -> Result<(Result>, bool)> +// where +// G: Fn(&'a mut BoxModule) -> F, +// F: Future, &'a mut BoxModule)>>, +// { +// let storage = match &self.storage { +// Some(s) => s, +// // no cache return directly +// None => return Ok((Ok(generator(module).await?.0), false)), +// }; - let mut need_cache = false; - let mut last_build_result = None; - let id = module.identifier().to_owned(); - if module.as_normal_module().is_some() { - // normal module - // TODO cache all module type - if let Some((snapshot, data, module_data, extra_data)) = storage.get(&id) { - let valid = if let Some(snapshot) = snapshot { - self - .snapshot_manager - .check_snapshot_valid(&snapshot) - .await - .unwrap_or(false) - } else { - false - }; - if valid { - if let Some(module) = module.as_normal_module_mut() { - if let Some(module_data) = module_data { - *module.source_mut() = module_data.source; - *module.code_generation_dependencies_mut() = module_data.code_generation_dependencies; - *module.presentational_dependencies_mut() = module_data.presentational_dependencies; - } - if let Some(extra_data) = extra_data { - module.parser_and_generator_mut().resume(&extra_data); - } - } - return Ok((Ok(data), true)); - } else { - last_build_result = Some(data.inner); - } - }; - need_cache = true; - } +// let mut need_cache = false; +// let mut last_build_result = None; +// let id = module.identifier().to_owned(); +// if module.as_normal_module().is_some() { +// // normal module +// // TODO cache all module type +// if let Some((snapshot, data, module_data, extra_data)) = storage.get(&id) { +// let valid = if let Some(snapshot) = snapshot { +// self +// .snapshot_manager +// .check_snapshot_valid(&snapshot) +// .await +// .unwrap_or(false) +// } else { +// false +// }; +// if valid { +// if let Some(module) = module.as_normal_module_mut() { +// if let Some(module_data) = module_data { +// *module.source_mut() = module_data.source; +// *module.code_generation_dependencies_mut() = module_data.code_generation_dependencies; +// *module.presentational_dependencies_mut() = module_data.presentational_dependencies; +// } +// if let Some(extra_data) = extra_data { +// module.parser_and_generator_mut().resume(&extra_data); +// } +// } +// return Ok((Ok(data), true)); +// } else { +// last_build_result = Some(data.inner); +// } +// }; +// need_cache = true; +// } - // run generator and save to cache - let (mut data, module) = generator(module).await?; +// // run generator and save to cache +// let (mut data, module) = generator(module).await?; - if need_cache { - let module = module - .as_normal_module() - .expect("Only normal module supports build cache"); - // only resume the build_meta to make sure other modules will not be affected - if matches!(module.source(), NormalModuleSource::BuiltFailed(_)) - && let Some(last_result) = last_build_result - { - data.inner.build_meta = last_result.build_meta; - return Ok((Ok(data), false)); - } +// if need_cache { +// let module = module +// .as_normal_module() +// .expect("Only normal module supports build cache"); +// // only resume the build_meta to make sure other modules will not be affected +// if matches!(module.source(), NormalModuleSource::BuiltFailed(_)) +// && let Some(last_result) = last_build_result +// { +// data.inner.build_meta = last_result.build_meta; +// return Ok((Ok(data), false)); +// } - if data.inner.build_info.cacheable { - let mut paths: Vec<&Path> = Vec::new(); - paths.extend( - data - .inner - .build_info - .file_dependencies - .iter() - .map(|i| i.as_path()), - ); - paths.extend( - data - .inner - .build_info - .context_dependencies - .iter() - .map(|i| i.as_path()), - ); - paths.extend( - data - .inner - .build_info - .missing_dependencies - .iter() - .map(|i| i.as_path()), - ); - paths.extend( - data - .inner - .build_info - .build_dependencies - .iter() - .map(|i| i.as_path()), - ); +// if data.inner.build_info.cacheable { +// let mut paths: Vec<&Path> = Vec::new(); +// paths.extend( +// data +// .inner +// .build_info +// .file_dependencies +// .iter() +// .map(|i| i.as_path()), +// ); +// paths.extend( +// data +// .inner +// .build_info +// .context_dependencies +// .iter() +// .map(|i| i.as_path()), +// ); +// paths.extend( +// data +// .inner +// .build_info +// .missing_dependencies +// .iter() +// .map(|i| i.as_path()), +// ); +// paths.extend( +// data +// .inner +// .build_info +// .build_dependencies +// .iter() +// .map(|i| i.as_path()), +// ); - let snapshot = self - .snapshot_manager - .create_snapshot(&paths, |option| &option.module) - .await?; - let mut extra_data = HashMap::new(); - module.parser_and_generator().store(&mut extra_data); - storage.set( - id, - ( - Some(snapshot), - data.clone(), - Some(NormalModuleStorageData { - source: module.source().clone(), - code_generation_dependencies: module.code_generation_dependencies().clone(), - presentational_dependencies: module.presentational_dependencies().clone(), - }), - Some(extra_data), - ), - ); - } else if matches!(module.source(), NormalModuleSource::BuiltSucceed(_)) { - storage.set(id, (None, data.clone(), None, None)); - } - } - Ok((Ok(data), false)) - } -} +// let snapshot = self +// .snapshot_manager +// .create_snapshot(&paths, |option| &option.module) +// .await?; +// let mut extra_data = HashMap::new(); +// module.parser_and_generator().store(&mut extra_data); +// storage.set( +// id, +// ( +// Some(snapshot), +// data.clone(), +// Some(NormalModuleStorageData { +// source: module.source().clone(), +// code_generation_dependencies: module.code_generation_dependencies().clone(), +// presentational_dependencies: module.presentational_dependencies().clone(), +// }), +// Some(extra_data), +// ), +// ); +// } else if matches!(module.source(), NormalModuleSource::BuiltSucceed(_)) { +// storage.set(id, (None, data.clone(), None, None)); +// } +// } +// Ok((Ok(data), false)) +// } +// } diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index ab27cac3bcf1..ce2b461e0ca9 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -14,7 +14,7 @@ use itertools::Itertools; use rayon::prelude::{ IntoParallelIterator, IntoParallelRefIterator, ParallelBridge, ParallelIterator, }; -use rspack_error::{internal_error, Diagnostic, Result, Severity, TWithDiagnosticArray}; +use rspack_error::{internal_error, Result, RspackDiagnostic, Severity, TWithDiagnosticArray}; use rspack_futures::FuturesResults; use rspack_hash::{RspackHash, RspackHashDigest}; use rspack_identifier::{Identifiable, IdentifierMap, IdentifierSet}; @@ -78,7 +78,7 @@ pub struct Compilation { pub async_entrypoints: Vec, assets: CompilationAssets, pub emitted_assets: DashSet>, - diagnostics: IndexSet>, + diagnostics: IndexSet>, logging: CompilationLogging, pub plugin_driver: SharedPluginDriver, pub resolver_factory: Arc, @@ -314,22 +314,22 @@ impl Compilation { &self.entrypoints } - pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) { + pub fn push_diagnostic(&mut self, diagnostic: RspackDiagnostic) { self.diagnostics.insert(diagnostic); } - pub fn push_batch_diagnostic(&mut self, diagnostics: Vec) { + pub fn push_batch_diagnostic(&mut self, diagnostics: Vec) { self.diagnostics.extend(diagnostics); } - pub fn get_errors(&self) -> impl Iterator { + pub fn get_errors(&self) -> impl Iterator { self .diagnostics .iter() .filter(|d| matches!(d.severity(), Severity::Error)) } - pub fn get_warnings(&self) -> impl Iterator { + pub fn get_warnings(&self) -> impl Iterator { self .diagnostics .iter() @@ -397,9 +397,9 @@ impl Compilation { &mut self, module_identifiers: HashSet, ) -> Result> { - for id in &module_identifiers { - self.cache.build_module_occasion.remove_cache(id); - } + // for id in &module_identifiers { + // self.cache.build_module_occasion.remove_cache(id); + // } self .update_module_graph(vec![MakeParam::ForceBuildModules( diff --git a/crates/rspack_core/src/compiler/queue.rs b/crates/rspack_core/src/compiler/queue.rs index 11ee98b5228d..6907e50df9fd 100644 --- a/crates/rspack_core/src/compiler/queue.rs +++ b/crates/rspack_core/src/compiler/queue.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use rspack_error::{Diagnostic, Result}; +use rspack_error::{Result, RspackDiagnostic}; use crate::{ cache::Cache, BoxDependency, BuildContext, BuildResult, Compilation, CompilerContext, @@ -56,7 +56,7 @@ pub struct FactorizeTaskResult { pub factory_result: ModuleFactoryResult, pub module_graph_module: Box, pub dependencies: Vec, - pub diagnostics: Vec, + pub diagnostics: Vec, pub is_entry: bool, pub current_profile: Option>, pub exports_info_related: ExportsInfoRelated, @@ -280,7 +280,7 @@ pub struct BuildTask { pub struct BuildTaskResult { pub module: Box, pub build_result: Box, - pub diagnostics: Vec, + pub diagnostics: Vec, pub current_profile: Option>, pub from_cache: bool, } @@ -295,62 +295,89 @@ impl WorkerTask for BuildTask { let mut module = self.module; let compiler_options = self.compiler_options; let resolver_factory = self.resolver_factory; - let cache = self.cache; + // let cache = self.cache; let plugin_driver = self.plugin_driver; - let (build_result, is_cache_valid) = match cache - .build_module_occasion - .use_cache(&mut module, |module| async { - plugin_driver - .build_module(module.as_mut()) - .await - .unwrap_or_else(|e| panic!("Run build_module hook failed: {}", e)); - - let result = module - .build(BuildContext { - compiler_context: CompilerContext { - options: compiler_options.clone(), - resolver_factory: resolver_factory.clone(), - module: Some(module.identifier()), - module_context: module.as_normal_module().and_then(|m| m.get_context()), - }, - plugin_driver: plugin_driver.clone(), - compiler_options: &compiler_options, - }) - .await; - - plugin_driver - .succeed_module(&**module) - .await - .unwrap_or_else(|e| panic!("Run succeed_module hook failed: {}", e)); - - result.map(|t| (t, module)) - }) - .await - { + // match cache + // .build_module_occasion + // .use_cache(&mut module, |module| async { + // plugin_driver + // .build_module(module.as_mut()) + // .await + // .unwrap_or_else(|e| panic!("Run build_module hook failed: {}", e)); + + // let result = module + // .build(BuildContext { + // compiler_context: CompilerContext { + // options: compiler_options.clone(), + // resolver_factory: resolver_factory.clone(), + // module: Some(module.identifier()), + // module_context: module.as_normal_module().and_then(|m| m.get_context()), + // }, + // plugin_driver: plugin_driver.clone(), + // compiler_options: &compiler_options, + // }) + // .await; + + // plugin_driver + // .succeed_module(&**module) + // .await + // .unwrap_or_else(|e| panic!("Run succeed_module hook failed: {}", e)); + + // result.map(|t| (t, module)) + // }) + // .await + let (build_result, module) = match { + plugin_driver + .build_module(module.as_mut()) + .await + .unwrap_or_else(|e| panic!("Run build_module hook failed: {}", e)); + + let result = module + .build(BuildContext { + compiler_context: CompilerContext { + options: compiler_options.clone(), + resolver_factory: resolver_factory.clone(), + module: Some(module.identifier()), + module_context: module.as_normal_module().and_then(|m| m.get_context()), + }, + plugin_driver: plugin_driver.clone(), + compiler_options: &compiler_options, + }) + .await; + + plugin_driver + .succeed_module(&*module) + .await + .unwrap_or_else(|e| panic!("Run succeed_module hook failed: {}", e)); + + result.map(|t| (t, module)) + } { Ok(result) => result, Err(err) => panic!("build module get error: {}", err), }; - if is_cache_valid { - plugin_driver.still_valid_module(module.as_ref()).await?; - } + let is_cache_valid = false; + + // if is_cache_valid { + // plugin_driver.still_valid_module(module.as_ref()).await?; + // } if let Some(current_profile) = &self.current_profile { current_profile.mark_building_end(); } - build_result.map(|build_result| { - let (build_result, diagnostics) = build_result.split_into_parts(); - - TaskResult::Build(Box::new(BuildTaskResult { - module, - build_result: Box::new(build_result), - diagnostics, - current_profile: self.current_profile, - from_cache: is_cache_valid, - })) - }) + // build_result.map(|build_result| { + let (build_result, diagnostics) = build_result.split_into_parts(); + + Ok(TaskResult::Build(Box::new(BuildTaskResult { + module, + build_result: Box::new(build_result), + diagnostics, + current_profile: self.current_profile, + from_cache: is_cache_valid, + }))) + // } } } diff --git a/crates/rspack_core/src/context_module.rs b/crates/rspack_core/src/context_module.rs index d065b06fd9b8..ffb0a58509cb 100644 --- a/crates/rspack_core/src/context_module.rs +++ b/crates/rspack_core/src/context_module.rs @@ -10,7 +10,7 @@ use std::{ use itertools::Itertools; use once_cell::sync::Lazy; use regex::{Captures, Regex}; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::{Identifiable, Identifier}; use rspack_regex::RspackRegex; diff --git a/crates/rspack_core/src/context_module_factory.rs b/crates/rspack_core/src/context_module_factory.rs index 226de9a0acb6..a54619e9ca89 100644 --- a/crates/rspack_core/src/context_module_factory.rs +++ b/crates/rspack_core/src/context_module_factory.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use tracing::instrument; use crate::{ diff --git a/crates/rspack_core/src/dependencies_block.rs b/crates/rspack_core/src/dependencies_block.rs index 97af82a1b3c5..f1ae31d022c0 100644 --- a/crates/rspack_core/src/dependencies_block.rs +++ b/crates/rspack_core/src/dependencies_block.rs @@ -1,4 +1,4 @@ -use rspack_error::{Diagnostic, DIAGNOSTIC_POS_DUMMY}; +use rspack_error::{RspackDiagnostic, DIAGNOSTIC_POS_DUMMY}; use serde::Serialize; use ustr::Ustr; @@ -163,7 +163,7 @@ pub struct AsyncDependenciesToInitialChunkError<'a> { pub loc: Option<&'a DependencyLocation>, } -impl<'a> From> for Diagnostic { +impl<'a> From> for RspackDiagnostic { fn from(value: AsyncDependenciesToInitialChunkError<'a>) -> Self { let title = "AsyncDependencyToInitialChunkError".to_string(); let message = format!("It's not allowed to load an initial chunk on demand. The chunk name \"{}\" is already used by an entrypoint.", value.chunk_name); @@ -171,6 +171,6 @@ impl<'a> From> for Diagnostic { .loc .map(|loc| (loc.start as usize, loc.end as usize)) .unwrap_or((DIAGNOSTIC_POS_DUMMY, DIAGNOSTIC_POS_DUMMY)); - Diagnostic::error(title, message, start, end) + RspackDiagnostic::error(title, message, start, end) } } diff --git a/crates/rspack_core/src/diagnostics.rs b/crates/rspack_core/src/diagnostics.rs new file mode 100644 index 000000000000..9d27aeb1c44b --- /dev/null +++ b/crates/rspack_core/src/diagnostics.rs @@ -0,0 +1,4 @@ +use rspack_error::{ + miette::{self, Diagnostic}, + thiserror::{self, Error}, +}; diff --git a/crates/rspack_core/src/external_module.rs b/crates/rspack_core/src/external_module.rs index ce95def7d618..1053db7dbd92 100644 --- a/crates/rspack_core/src/external_module.rs +++ b/crates/rspack_core/src/external_module.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::hash::Hash; use std::iter; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::{Identifiable, Identifier}; use rustc_hash::FxHashMap as HashMap; diff --git a/crates/rspack_core/src/lib.rs b/crates/rspack_core/src/lib.rs index 2291c85b444b..d20e23808a0c 100644 --- a/crates/rspack_core/src/lib.rs +++ b/crates/rspack_core/src/lib.rs @@ -8,6 +8,7 @@ use std::sync::atomic::AtomicBool; use std::{fmt, sync::Arc}; mod dependencies_block; +mod diagnostics; pub mod mf; pub use dependencies_block::{ AsyncDependenciesBlock, AsyncDependenciesBlockIdentifier, DependenciesBlock, DependencyLocation, diff --git a/crates/rspack_core/src/mf/container/container_entry_module.rs b/crates/rspack_core/src/mf/container/container_entry_module.rs index d2b7e7b8939d..95e64f228039 100644 --- a/crates/rspack_core/src/mf/container/container_entry_module.rs +++ b/crates/rspack_core/src/mf/container/container_entry_module.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, hash::Hash}; use async_trait::async_trait; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::{Identifiable, Identifier}; use rspack_sources::{RawSource, Source, SourceExt}; diff --git a/crates/rspack_core/src/mf/container/container_entry_module_factory.rs b/crates/rspack_core/src/mf/container/container_entry_module_factory.rs index 2ffcd830fbea..4888e86b2ad8 100644 --- a/crates/rspack_core/src/mf/container/container_entry_module_factory.rs +++ b/crates/rspack_core/src/mf/container/container_entry_module_factory.rs @@ -1,7 +1,7 @@ // TODO: move to rspack_plugin_mf use async_trait::async_trait; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use super::{ container_entry_dependency::ContainerEntryDependency, diff --git a/crates/rspack_core/src/mf/container/remote_module.rs b/crates/rspack_core/src/mf/container/remote_module.rs index 893cb88a1007..f146de23cce5 100644 --- a/crates/rspack_core/src/mf/container/remote_module.rs +++ b/crates/rspack_core/src/mf/container/remote_module.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::hash::Hash; use async_trait::async_trait; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::{Identifiable, Identifier}; use rspack_sources::{RawSource, Source, SourceExt}; diff --git a/crates/rspack_core/src/mf/sharing/consume_shared_module.rs b/crates/rspack_core/src/mf/sharing/consume_shared_module.rs index 858e86e0d932..24aeaa55050f 100644 --- a/crates/rspack_core/src/mf/sharing/consume_shared_module.rs +++ b/crates/rspack_core/src/mf/sharing/consume_shared_module.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, hash::Hash}; use async_trait::async_trait; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::{Identifiable, Identifier}; use rspack_sources::Source; diff --git a/crates/rspack_core/src/mf/sharing/provide_shared_module.rs b/crates/rspack_core/src/mf/sharing/provide_shared_module.rs index 62025f021a3a..3c42af6b7a4d 100644 --- a/crates/rspack_core/src/mf/sharing/provide_shared_module.rs +++ b/crates/rspack_core/src/mf/sharing/provide_shared_module.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, hash::Hash}; use async_trait::async_trait; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::{Identifiable, Identifier}; use rspack_sources::Source; diff --git a/crates/rspack_core/src/mf/sharing/provide_shared_module_factory.rs b/crates/rspack_core/src/mf/sharing/provide_shared_module_factory.rs index d5ff76a60554..d34dabfa4be9 100644 --- a/crates/rspack_core/src/mf/sharing/provide_shared_module_factory.rs +++ b/crates/rspack_core/src/mf/sharing/provide_shared_module_factory.rs @@ -1,7 +1,7 @@ // TODO: move to rspack_plugin_mf use async_trait::async_trait; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use super::{ provide_shared_dependency::ProvideSharedDependency, provide_shared_module::ProvideSharedModule, diff --git a/crates/rspack_core/src/module.rs b/crates/rspack_core/src/module.rs index a6ee409486b2..83425b0f319c 100644 --- a/crates/rspack_core/src/module.rs +++ b/crates/rspack_core/src/module.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use std::{any::Any, borrow::Cow, fmt::Debug}; use async_trait::async_trait; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::{RspackHash, RspackHashDigest}; use rspack_identifier::{Identifiable, Identifier}; use rspack_sources::Source; diff --git a/crates/rspack_core/src/normal_module.rs b/crates/rspack_core/src/normal_module.rs index ce3f95ff4ed5..c16dc72d73db 100644 --- a/crates/rspack_core/src/normal_module.rs +++ b/crates/rspack_core/src/normal_module.rs @@ -12,7 +12,8 @@ use bitflags::bitflags; use dashmap::DashMap; use derivative::Derivative; use rspack_error::{ - internal_error, Diagnostic, IntoTWithDiagnosticArray, Result, Severity, TWithDiagnosticArray, + internal_error, IntoTWithRspackDiagnosticArray, Result, RspackDiagnostic, Severity, + TWithDiagnosticArray, }; use rspack_hash::RspackHash; use rspack_identifier::Identifiable; @@ -133,7 +134,7 @@ pub enum NormalModuleSource { } impl NormalModuleSource { - pub fn new_built(source: BoxSource, diagnostics: &[Diagnostic]) -> Self { + pub fn new_built(source: BoxSource, diagnostics: &[RspackDiagnostic]) -> Self { if diagnostics.iter().any(|d| d.severity() == Severity::Error) { NormalModuleSource::BuiltFailed( diagnostics diff --git a/crates/rspack_core/src/normal_module_factory.rs b/crates/rspack_core/src/normal_module_factory.rs index 1728419935d1..a376d1331872 100644 --- a/crates/rspack_core/src/normal_module_factory.rs +++ b/crates/rspack_core/src/normal_module_factory.rs @@ -3,7 +3,7 @@ use std::{path::Path, sync::Arc}; use once_cell::sync::Lazy; use regex::Regex; use rspack_error::{ - internal_error, Diagnostic, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, + internal_error, IntoTWithRspackDiagnosticArray, Result, RspackDiagnostic, TWithDiagnosticArray, }; use rspack_loader_runner::{get_scheme, Loader, Scheme}; use sugar_path::{AsPath, SugarPath}; @@ -361,8 +361,7 @@ impl NormalModuleFactory { let module_identifier = ModuleIdentifier::from(format!("missing|{ident}")); let mut file_dependencies = Default::default(); let mut missing_dependencies = Default::default(); - let diagnostics: Vec = internal_error.into(); - let mut diagnostic = diagnostics[0].clone(); + let mut diagnostics: Vec = internal_error.into(); let mut from_cache_result = from_cache; if !data .resolve_options @@ -405,11 +404,11 @@ impl NormalModuleFactory { "{request_without_match_resource}.{}", extension.to_string_lossy() ); - diagnostic = diagnostic.with_notes(vec![format!("Did you mean '{resource}'? - BREAKING CHANGE: The request '{request_without_match_resource}' failed to resolve only because it was resolved as fully specified - (probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\"type\": \"module\"'). - The extension in the request is mandatory for it to be fully specified. - Add the extension to the request.")]); + diagnostics[0].add_notes(vec![format!("Did you mean '{resource}'? + BREAKING CHANGE: The request '{request_without_match_resource}' failed to resolve only because it was resolved as fully specified + (probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\"type\": \"module\"'). + The extension in the request is mandatory for it to be fully specified. + Add the extension to the request.")]); } } } @@ -423,7 +422,7 @@ impl NormalModuleFactory { return Ok(Some( ModuleFactoryResult::new(missing_module) .from_cache(from_cache_result) - .with_diagnostic(vec![diagnostic]), + .with_diagnostic(diagnostics.drain(1..).collect()), )); } } diff --git a/crates/rspack_core/src/plugin/plugin_driver.rs b/crates/rspack_core/src/plugin/plugin_driver.rs index 134db2afd596..f6c4cf6cfa2d 100644 --- a/crates/rspack_core/src/plugin/plugin_driver.rs +++ b/crates/rspack_core/src/plugin/plugin_driver.rs @@ -3,7 +3,7 @@ use std::{ sync::{Arc, Mutex}, }; -use rspack_error::{Diagnostic, Result}; +use rspack_error::{Result, RspackDiagnostic}; use rspack_loader_runner::ResourceData; use rustc_hash::FxHashMap as HashMap; use tracing::instrument; @@ -34,7 +34,7 @@ pub struct PluginDriver { // pub registered_parser: HashMap, pub registered_parser_and_generator_builder: HashMap, /// Collecting error generated by plugin phase, e.g., `Syntax Error` - pub diagnostics: Arc>>, + pub diagnostics: Arc>>, } impl std::fmt::Debug for PluginDriver { @@ -90,7 +90,7 @@ impl PluginDriver { ) } - pub fn take_diagnostic(&self) -> Vec { + pub fn take_diagnostic(&self) -> Vec { let mut diagnostic = self.diagnostics.lock().expect("TODO:"); std::mem::take(&mut diagnostic) } diff --git a/crates/rspack_core/src/raw_module.rs b/crates/rspack_core/src/raw_module.rs index a9ecff5a5a4d..6054244f8b16 100644 --- a/crates/rspack_core/src/raw_module.rs +++ b/crates/rspack_core/src/raw_module.rs @@ -1,7 +1,7 @@ use std::borrow::Cow; use std::hash::Hash; -use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rspack_hash::RspackHash; use rspack_identifier::Identifiable; use rspack_sources::{BoxSource, RawSource, Source, SourceExt}; diff --git a/crates/rspack_core/src/tree_shaking/optimizer.rs b/crates/rspack_core/src/tree_shaking/optimizer.rs index 75bdd59377f0..9cb734d5095e 100644 --- a/crates/rspack_core/src/tree_shaking/optimizer.rs +++ b/crates/rspack_core/src/tree_shaking/optimizer.rs @@ -11,7 +11,7 @@ use petgraph::{ Directed, }; use rspack_error::{ - errors_to_diagnostics, Error, InternalError, IntoTWithDiagnosticArray, Result, Severity, + errors_to_diagnostics, Error, InternalError, IntoTWithRspackDiagnosticArray, Result, Severity, TWithDiagnosticArray, }; use rspack_identifier::{Identifier, IdentifierLinkedSet, IdentifierMap, IdentifierSet}; diff --git a/crates/rspack_error/src/diagnostic.rs b/crates/rspack_error/src/diagnostic.rs index c55d897f0532..9102f106669f 100644 --- a/crates/rspack_error/src/diagnostic.rs +++ b/crates/rspack_error/src/diagnostic.rs @@ -1,4 +1,4 @@ -use std::fmt; +use std::{borrow::Cow, fmt}; use crate::{DiagnosticKind, Error, TraceableRspackError}; @@ -18,6 +18,16 @@ impl From for miette::Severity { } } +impl From for Severity { + fn from(value: miette::Severity) -> Self { + match value { + miette::Severity::Error => Severity::Error, + miette::Severity::Warning => Severity::Warn, + miette::Severity::Advice => unimplemented!("Not supported miette Serverity"), + } + } +} + impl fmt::Display for Severity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( @@ -37,22 +47,74 @@ pub struct DiagnosticSourceInfo { pub source: String, } -#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] -pub struct Diagnostic { - pub(crate) severity: Severity, - pub(crate) message: String, - pub(crate) title: String, +#[derive(Debug, Default, PartialEq, Eq, Hash)] +pub struct RspackLegacyDiagnostic { + pub severity: Severity, + pub message: String, + pub title: String, /// Source code and path of current Diagnostic - pub(crate) source_info: Option, - pub(crate) start: usize, - pub(crate) end: usize, - pub(crate) kind: DiagnosticKind, - pub(crate) notes: Vec, + pub source_info: Option, + pub start: usize, + pub end: usize, + pub kind: DiagnosticKind, + pub notes: Vec, } -impl Diagnostic { +impl RspackLegacyDiagnostic { + pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { + self.kind = kind; + self + } + pub fn with_source_info(mut self, source: DiagnosticSourceInfo) -> Self { + self.source_info = Some(source); + self + } + pub fn with_notes(mut self, notes: Vec) -> Self { + self.notes = notes; + self + } +} + +#[derive(Debug)] +pub enum RspackDiagnostic { + Legacy(RspackLegacyDiagnostic), + Miette(miette::Report), +} + +impl std::hash::Hash for RspackDiagnostic { + fn hash(&self, state: &mut H) { + match self { + RspackDiagnostic::Legacy(l) => l.hash(state), + RspackDiagnostic::Miette(m) => { + m.code().map(|c| c.to_string()).hash(state); + m.to_string().hash(state); + m.severity().map(Severity::from).hash(state); + } + } + } +} + +/// Don't think we should rely on this stuff in [Compilation.diagnostics]. +/// Just have to make sure everything is deduped in the first place +impl PartialEq for RspackDiagnostic { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Legacy(l), Self::Legacy(r)) => l == r, + (Self::Miette(l), Self::Miette(r)) => { + l.code().map(|l| l.to_string()) == r.code().map(|r| r.to_string()) + && l.to_string() == r.to_string() + && l.severity() == r.severity() + } + _ => false, + } + } +} + +impl Eq for RspackDiagnostic {} + +impl RspackDiagnostic { pub fn warn(title: String, message: String, start: usize, end: usize) -> Self { - Self { + Self::Legacy(RspackLegacyDiagnostic { severity: Severity::Warn, title, message, @@ -60,11 +122,11 @@ impl Diagnostic { start, end, ..Default::default() - } + }) } pub fn error(title: String, message: String, start: usize, end: usize) -> Self { - Self { + Self::Legacy(RspackLegacyDiagnostic { severity: Severity::Error, message, source_info: None, @@ -72,47 +134,88 @@ impl Diagnostic { end, title, ..Default::default() - } + }) } - pub fn title(&self) -> &str { - &self.title + pub fn title(&self) -> Cow { + match self { + RspackDiagnostic::Legacy(l) => Cow::Borrowed(&l.title), + RspackDiagnostic::Miette(m) => { + Cow::Owned(m.code().map(|v| v.to_string()).unwrap_or_default()) + } + } } - pub fn message(&self) -> &str { - &self.message + pub fn message(&self) -> Cow { + match self { + RspackDiagnostic::Legacy(l) => Cow::Borrowed(&l.message), + RspackDiagnostic::Miette(m) => Cow::Owned(m.to_string()), + } } pub fn severity(&self) -> Severity { - self.severity + match self { + RspackDiagnostic::Legacy(l) => l.severity, + RspackDiagnostic::Miette(m) => m.severity().map(Into::into).unwrap_or_default(), + } + } + + pub fn kind(&self) -> DiagnosticKind { + match &self { + RspackDiagnostic::Legacy(l) => l.kind, + RspackDiagnostic::Miette(_) => DiagnosticKind::Internal, + } + } + + pub fn notes(&self) -> Vec { + match &self { + RspackDiagnostic::Legacy(l) => l.notes.clone(), + RspackDiagnostic::Miette(_) => todo!(), + } } pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { - self.kind = kind; + match &mut self { + RspackDiagnostic::Legacy(l) => l.kind = kind, + RspackDiagnostic::Miette(_) => { + // Not necessarily to change this, since `[miette::Report]` should already contain its kind. + } + } self } pub fn with_source_info(mut self, source: DiagnosticSourceInfo) -> Self { - self.source_info = Some(source); + match &mut self { + RspackDiagnostic::Legacy(l) => l.source_info = Some(source), + RspackDiagnostic::Miette(_) => { + // noop + } + } self } pub fn with_notes(mut self, notes: Vec) -> Self { - self.notes = notes; + match &mut self { + RspackDiagnostic::Legacy(l) => l.notes = notes, + RspackDiagnostic::Miette(_) => { + // noop + } + } self } + pub fn add_notes(&mut self, notes: Vec) { + match self { + RspackDiagnostic::Legacy(l) => l.notes = notes, + RspackDiagnostic::Miette(_) => { + // noop + } + } + } } -impl From for Vec { +impl From for Vec { fn from(err: Error) -> Self { let diagnostic = match err { - Error::InternalError(err) => Diagnostic { - message: err.error_message().to_string(), - source_info: None, - start: 0, - end: 0, - severity: err.severity(), - ..Default::default() - }, + Error::InternalError(err) => RspackDiagnostic::Miette(err.0), Error::TraceableRspackError(TraceableRspackError { start, end, @@ -122,7 +225,7 @@ impl From for Vec { severity, file_path, file_src, - }) => Diagnostic { + }) => RspackDiagnostic::Legacy(RspackLegacyDiagnostic { message: error_message, source_info: Some(DiagnosticSourceInfo { source: file_src, @@ -134,11 +237,11 @@ impl From for Vec { kind, severity, ..Default::default() - }, + }), Error::BatchErrors(diagnostics) => { return diagnostics .into_iter() - .flat_map(Vec::::from) + .flat_map(Vec::::from) .collect::>() } }; @@ -146,8 +249,11 @@ impl From for Vec { } } -pub fn errors_to_diagnostics(errs: Vec) -> Vec { - errs.into_iter().flat_map(Vec::::from).collect() +pub fn errors_to_diagnostics(errs: Vec) -> Vec { + errs + .into_iter() + .flat_map(Vec::::from) + .collect() } pub const DIAGNOSTIC_POS_DUMMY: usize = 0; diff --git a/crates/rspack_error/src/emitter.rs b/crates/rspack_error/src/emitter.rs index 209c8eab31a9..7c5fda452666 100644 --- a/crates/rspack_error/src/emitter.rs +++ b/crates/rspack_error/src/emitter.rs @@ -1,15 +1,20 @@ -use std::io::Write; +use std::io::{IsTerminal, Write}; use std::path::Path; use anyhow::Context; -use codespan_reporting::diagnostic::{Diagnostic, Label, Severity}; use codespan_reporting::files::SimpleFiles; use codespan_reporting::term::termcolor::{ColorChoice, StandardStream}; use codespan_reporting::term::{self, Config}; +use miette::{Diagnostic, GraphicalReportHandler, GraphicalTheme, IntoDiagnostic}; use sugar_path::SugarPath; use termcolor::{Buffer, ColorSpec, StandardStreamLock, WriteColor}; -use crate::Diagnostic as RspackDiagnostic; +use crate::{RspackDiagnostic, RspackLegacyDiagnostic}; + +/// Detects if's in a terminal. +fn is_terminal() -> bool { + std::io::stdout().is_terminal() && std::io::stderr().is_terminal() +} pub trait FlushDiagnostic { fn flush_diagnostic(&mut self) {} @@ -175,6 +180,46 @@ fn emit_diagnostic( pwd: impl AsRef, files: &mut SimpleFiles, ) -> crate::Result<()> { + match diagnostic { + RspackDiagnostic::Legacy(l) => { + emit_diagnostic_legacy(l, writer, pwd, files)?; + } + RspackDiagnostic::Miette(m) => { + let mut buf = String::new(); + emit_diagnostic_miette(m, &mut buf, pwd, files, writer.supports_color())?; + writer.write_all(buf.as_bytes()).into_diagnostic()?; + } + } + Ok(()) +} + +fn emit_diagnostic_miette( + diagnostic: &miette::Report, + writer: &mut T, + _pwd: impl AsRef, + _files: &mut SimpleFiles, + supports_color: bool, +) -> crate::Result<()> { + let h = GraphicalReportHandler::new().with_theme(if !is_terminal() { + GraphicalTheme::ascii() + } else if supports_color { + GraphicalTheme::unicode() + } else { + GraphicalTheme::unicode_nocolor() + }); + h.render_report(writer, &**diagnostic as &(dyn Diagnostic)) + .into_diagnostic()?; + Ok(()) +} + +fn emit_diagnostic_legacy( + diagnostic: &RspackLegacyDiagnostic, + writer: &mut T, + pwd: impl AsRef, + files: &mut SimpleFiles, +) -> crate::Result<()> { + use codespan_reporting::diagnostic::{Diagnostic, Label}; + let (labels, message) = match &diagnostic.source_info { Some(info) => { let file_path = Path::new(&info.path); @@ -210,7 +255,7 @@ fn emit_diagnostic( writer.reset().map_err(|e| e.into()) } -impl From for Severity { +impl From for codespan_reporting::diagnostic::Severity { fn from(severity: crate::Severity) -> Self { match severity { crate::Severity::Error => Self::Error, diff --git a/crates/rspack_error/src/error.rs b/crates/rspack_error/src/error.rs index e1ea315ac5eb..238a78ab53c3 100644 --- a/crates/rspack_error/src/error.rs +++ b/crates/rspack_error/src/error.rs @@ -8,7 +8,7 @@ use thiserror::Error; use crate::Severity; #[derive(Debug)] -pub struct InternalError(miette::Report); +pub struct InternalError(pub(crate) miette::Report); impl From for InternalError { fn from(value: T) -> Self { @@ -54,7 +54,6 @@ impl fmt::Display for InternalError { } #[derive(Debug, Error, Diagnostic)] -#[diagnostic(code(TraceableError))] #[error("error[{kind}]: {title}")] pub struct TraceableError { title: String, @@ -68,6 +67,11 @@ pub struct TraceableError { } impl TraceableError { + pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { + self.kind = kind; + self + } + pub fn from_source_file( source_file: &SourceFile, start: usize, diff --git a/crates/rspack_error/src/lib.rs b/crates/rspack_error/src/lib.rs index 3f61fdf1a0eb..162c91d38139 100644 --- a/crates/rspack_error/src/lib.rs +++ b/crates/rspack_error/src/lib.rs @@ -21,15 +21,15 @@ pub type Result = std::result::Result; #[derive(Debug)] pub struct TWithDiagnosticArray { pub inner: T, - pub diagnostic: Vec, + pub diagnostic: Vec, } impl TWithDiagnosticArray { - pub fn new(inner: T, diagnostic: Vec) -> Self { + pub fn new(inner: T, diagnostic: Vec) -> Self { Self { inner, diagnostic } } - pub fn diagnostics(&self) -> &Vec { + pub fn diagnostics(&self) -> &Vec { &self.diagnostic } @@ -37,23 +37,23 @@ impl TWithDiagnosticArray { self.inner } - pub fn split_into_parts(self) -> (T, Vec) { + pub fn split_into_parts(self) -> (T, Vec) { (self.inner, self.diagnostic) } } -impl Clone for TWithDiagnosticArray { - fn clone(&self) -> Self { - Self { - inner: self.inner.clone(), - diagnostic: self.diagnostic.clone(), - } - } -} +// impl Clone for TWithDiagnosticArray { +// fn clone(&self) -> Self { +// Self { +// inner: self.inner.clone(), +// diagnostic: self.diagnostic.clone(), +// } +// } +// } // Helper trait to make `TWithDiagnosticArray` conversion more easily. -pub trait IntoTWithDiagnosticArray { - fn with_diagnostic(self, diagnostic: Vec) -> TWithDiagnosticArray +pub trait IntoTWithRspackDiagnosticArray { + fn with_diagnostic(self, diagnostic: Vec) -> TWithDiagnosticArray where Self: Sized + std::fmt::Debug; @@ -68,8 +68,8 @@ pub trait IntoTWithDiagnosticArray { } } -impl IntoTWithDiagnosticArray for T { - fn with_diagnostic(self, diagnostic: Vec) -> TWithDiagnosticArray +impl IntoTWithRspackDiagnosticArray for T { + fn with_diagnostic(self, diagnostic: Vec) -> TWithDiagnosticArray where Self: Sized + std::fmt::Debug, { diff --git a/crates/rspack_loader_runner/src/runner.rs b/crates/rspack_loader_runner/src/runner.rs index dd8106b0a470..b4bc1c926b4d 100644 --- a/crates/rspack_loader_runner/src/runner.rs +++ b/crates/rspack_loader_runner/src/runner.rs @@ -8,7 +8,7 @@ use anymap::CloneAny; use derivative::Derivative; use once_cell::sync::OnceCell; use rspack_error::{ - internal_error, Diagnostic, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, + internal_error, IntoTWithRspackDiagnosticArray, Result, RspackDiagnostic, TWithDiagnosticArray, }; use rspack_sources::SourceMap; use rustc_hash::FxHashSet as HashSet; @@ -185,7 +185,7 @@ pub struct LoaderContext<'c, C> { pub __resource_data: &'c ResourceData, // Only used for cross-crate accessing. // This field should not be accessed in builtin loaders. - pub __diagnostics: Vec, + pub __diagnostics: Vec, } impl<'c, C> LoaderContext<'c, C> { @@ -217,7 +217,7 @@ impl<'c, C> LoaderContext<'c, C> { } /// Emit a diagnostic, it can be a `warning` or `error`. - pub fn emit_diagnostic(&mut self, diagnostic: Diagnostic) { + pub fn emit_diagnostic(&mut self, diagnostic: RspackDiagnostic) { self.__diagnostics.push(diagnostic) } } diff --git a/crates/rspack_loader_sass/src/lib.rs b/crates/rspack_loader_sass/src/lib.rs index af8a80327f9d..a1b1fde0892d 100644 --- a/crates/rspack_loader_sass/src/lib.rs +++ b/crates/rspack_loader_sass/src/lib.rs @@ -15,7 +15,7 @@ use rspack_core::{ ResolveOptionsWithDependencyType, ResolveResult, Resolver, ResolverFactory, }; use rspack_error::{ - internal_error, Diagnostic, DiagnosticKind, Error, InternalError, Result, Severity, + internal_error, RspackDiagnostic, DiagnosticKind, Error, InternalError, Result, Severity, TraceableRspackError, }; use rspack_loader_runner::{Identifiable, Identifier, Loader, LoaderContext}; @@ -349,7 +349,7 @@ impl LegacyImporter for RspackImporter { #[derive(Debug)] struct RspackLogger { // `Sync` is required by the `Logger` trait - tx: mpsc::SyncSender>, + tx: mpsc::SyncSender>, } impl Logger for RspackLogger { @@ -534,7 +534,7 @@ fn sass_log_to_diagnostics( severity: Severity, message: &str, span: Option<&SourceSpan>, -) -> Vec { +) -> Vec { let title = match severity { Severity::Error => "Sass Error", Severity::Warn => "Sass Warning", @@ -545,8 +545,8 @@ fn sass_log_to_diagnostics( Error::TraceableRspackError(e.with_kind(DiagnosticKind::Scss).with_severity(severity)).into() } else { let f = match severity { - Severity::Error => Diagnostic::error, - Severity::Warn => Diagnostic::warn, + Severity::Error => RspackDiagnostic::error, + Severity::Warn => RspackDiagnostic::warn, }; vec![f(title.to_string(), message.to_string(), 0, 0).with_kind(DiagnosticKind::Scss)] } diff --git a/crates/rspack_loader_swc/src/lib.rs b/crates/rspack_loader_swc/src/lib.rs index 135520009509..9955f0683df6 100644 --- a/crates/rspack_loader_swc/src/lib.rs +++ b/crates/rspack_loader_swc/src/lib.rs @@ -11,7 +11,7 @@ use options::SwcCompilerOptionsWithAdditional; pub use options::SwcLoaderJsOptions; use rspack_ast::RspackAst; use rspack_core::{rspack_sources::SourceMap, LoaderRunnerContext, Mode}; -use rspack_error::{internal_error, Diagnostic, Result}; +use rspack_error::{internal_error, Result, RspackDiagnostic}; use rspack_loader_runner::{Identifiable, Identifier, Loader, LoaderContext}; use rspack_plugin_javascript::ast::{self, SourceMapConfig}; use rspack_plugin_javascript::TransformOutput; @@ -70,7 +70,7 @@ impl Loader for SwcLoader { } if swc_options.config.jsc.experimental.plugins.is_some() { - loader_context.emit_diagnostic(Diagnostic::warn( + loader_context.emit_diagnostic(RspackDiagnostic::warn( SWC_LOADER_IDENTIFIER.to_string(), "Experimental plugins are not currently supported.".to_string(), 0, @@ -79,7 +79,7 @@ impl Loader for SwcLoader { } if swc_options.config.jsc.target.is_some() && swc_options.config.env.is_some() { - loader_context.emit_diagnostic(Diagnostic::warn( + loader_context.emit_diagnostic(RspackDiagnostic::warn( SWC_LOADER_IDENTIFIER.to_string(), "`env` and `jsc.target` cannot be used together".to_string(), 0, diff --git a/crates/rspack_plugin_asset/src/lib.rs b/crates/rspack_plugin_asset/src/lib.rs index 3c57817f503c..ea791104aa2c 100644 --- a/crates/rspack_plugin_asset/src/lib.rs +++ b/crates/rspack_plugin_asset/src/lib.rs @@ -17,7 +17,7 @@ use rspack_core::{ PluginRenderManifestHookOutput, RenderManifestArgs, RenderManifestEntry, ResourceData, RuntimeGlobals, SourceType, }; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result}; use rspack_hash::{RspackHash, RspackHashDigest}; use rspack_util::identifier::make_paths_relative; diff --git a/crates/rspack_plugin_copy/src/lib.rs b/crates/rspack_plugin_copy/src/lib.rs index fa1e584c62b6..cb3d4278e161 100644 --- a/crates/rspack_plugin_copy/src/lib.rs +++ b/crates/rspack_plugin_copy/src/lib.rs @@ -15,7 +15,7 @@ use rspack_core::{ rspack_sources::RawSource, AssetInfo, AssetInfoRelated, Compilation, CompilationAsset, CompilationLogger, Filename, Logger, PathData, Plugin, }; -use rspack_error::Diagnostic; +use rspack_error::RspackDiagnostic; use rspack_hash::{HashDigest, HashFunction, HashSalt, RspackHash, RspackHashDigest}; use sugar_path::{AsPath, SugarPath}; @@ -137,7 +137,7 @@ impl CopyRspackPlugin { output_path: &Path, from_type: FromType, file_dependencies: &DashSet, - diagnostics: &DashSet, + diagnostics: &DashSet, compilation: &Compilation, logger: &CompilationLogger, ) -> Option { @@ -232,7 +232,7 @@ impl CopyRspackPlugin { RawSource::Buffer(data) } Err(e) => { - let rspack_err: Vec = rspack_error::Error::from(e).into(); + let rspack_err: Vec = rspack_error::Error::from(e).into(); for err in rspack_err { diagnostics.insert(err); } @@ -289,7 +289,7 @@ impl CopyRspackPlugin { _index: usize, file_dependencies: &DashSet, context_dependencies: &DashSet, - diagnostics: &DashSet, + diagnostics: &DashSet, logger: &CompilationLogger, ) -> Option>> { let orig_from = &pattern.from; @@ -430,7 +430,7 @@ impl CopyRspackPlugin { return None; } - diagnostics.insert(Diagnostic::error( + diagnostics.insert(RspackDiagnostic::error( "CopyRspackPlugin Error".into(), format!("unable to locate '{glob_query}' glob"), 0, @@ -464,7 +464,7 @@ impl CopyRspackPlugin { } // TODO err handler - diagnostics.insert(Diagnostic::error( + diagnostics.insert(RspackDiagnostic::error( "CopyRspackPlugin Error".into(), format!("unable to locate '{glob_query}' glob"), 0, @@ -487,7 +487,7 @@ impl CopyRspackPlugin { return None; } - diagnostics.insert(Diagnostic::error( + diagnostics.insert(RspackDiagnostic::error( "Glob Error".into(), e.msg.to_string(), 0, diff --git a/crates/rspack_plugin_css/src/parser_and_generator/mod.rs b/crates/rspack_plugin_css/src/parser_and_generator/mod.rs index 3ba8f221a97e..b21b931d78eb 100644 --- a/crates/rspack_plugin_css/src/parser_and_generator/mod.rs +++ b/crates/rspack_plugin_css/src/parser_and_generator/mod.rs @@ -15,7 +15,7 @@ use rspack_core::{ ParseContext, ParseResult, ParserAndGenerator, SourceType, TemplateContext, }; use rspack_core::{ModuleInitFragments, RuntimeGlobals}; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use rustc_hash::FxHashSet; use sugar_path::SugarPath; use swc_core::{css::parser::parser::ParserConfig, ecma::atoms::JsWord}; diff --git a/crates/rspack_plugin_css/src/swc_css_compiler.rs b/crates/rspack_plugin_css/src/swc_css_compiler.rs index 5d16efad309a..0a85f302ec29 100644 --- a/crates/rspack_plugin_css/src/swc_css_compiler.rs +++ b/crates/rspack_plugin_css/src/swc_css_compiler.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use rspack_core::rspack_sources::{self, SourceExt}; -use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{internal_error, IntoTWithRspackDiagnosticArray, Result, TWithDiagnosticArray}; use swc_core::common::{input::SourceFileInput, source_map::SourceMapGenConfig, FileName}; use swc_core::common::{Globals, GLOBALS}; use swc_core::css::codegen::{ diff --git a/crates/rspack_plugin_css/src/visitors/mod.rs b/crates/rspack_plugin_css/src/visitors/mod.rs index 6ffc204bc57e..b7e1010af4cd 100644 --- a/crates/rspack_plugin_css/src/visitors/mod.rs +++ b/crates/rspack_plugin_css/src/visitors/mod.rs @@ -1,7 +1,7 @@ use once_cell::sync::Lazy; use regex::Regex; use rspack_core::{BoxDependency, ModuleDependency, SpanExt}; -use rspack_error::{Diagnostic, DiagnosticKind}; +use rspack_error::{DiagnosticKind, RspackDiagnostic}; use swc_core::common::Span; use swc_core::css::ast::{ AtRule, AtRuleName, Function, ImportHref, ImportPrelude, Stylesheet, Token, TokenAndSpan, Url, @@ -19,7 +19,7 @@ static IS_MODULE_REQUEST: Lazy = Lazy::new(|| Regex::new(r"^~").expect("T pub fn analyze_dependencies( ss: &Stylesheet, code_generation_dependencies: &mut Vec>, - diagnostics: &mut Vec, + diagnostics: &mut Vec, ) -> Vec { let mut v = Analyzer { deps: Vec::new(), @@ -38,16 +38,19 @@ pub fn analyze_dependencies( struct Analyzer<'a> { deps: Vec, code_generation_dependencies: &'a mut Vec>, - diagnostics: &'a mut Vec, + diagnostics: &'a mut Vec, nearest_at_import_span: Option, url_function_span: Option, // in_support_contdition: bool, } -fn replace_module_request_prefix(specifier: String, diagnostics: &mut Vec) -> String { +fn replace_module_request_prefix( + specifier: String, + diagnostics: &mut Vec, +) -> String { if IS_MODULE_REQUEST.is_match(&specifier) { diagnostics.push( - Diagnostic::warn( + RspackDiagnostic::warn( "Deprecated '~'".to_string(), "'@import' or 'url()' with a request starts with '~' is deprecated.".to_string(), 0, diff --git a/crates/rspack_plugin_html/src/parser.rs b/crates/rspack_plugin_html/src/parser.rs index 6eaa410e361f..c51ade281d63 100644 --- a/crates/rspack_plugin_html/src/parser.rs +++ b/crates/rspack_plugin_html/src/parser.rs @@ -1,6 +1,6 @@ use rspack_core::ErrorSpan; use rspack_error::{ - Diagnostic, DiagnosticKind, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, + DiagnosticKind, IntoTWithRspackDiagnosticArray, Result, RspackDiagnostic, TWithDiagnosticArray, }; use swc_core::common::{sync::Lrc, FileName, FilePathMapping, SourceFile, SourceMap, GLOBALS}; use swc_html::{ @@ -31,9 +31,11 @@ impl<'a> HtmlCompiler<'a> { let mut errors = vec![]; let document = parse_file_as_document(fm.as_ref(), ParserConfig::default(), &mut errors); - let diagnostics: Vec = errors + let diagnostics: Vec = errors .into_iter() - .flat_map(|error| >::from(html_parse_error_to_traceable_error(error, &fm))) + .flat_map(|error| { + >::from(html_parse_error_to_traceable_error(error, &fm)) + }) .collect(); document .map(|doc| doc.with_diagnostic(diagnostics)) diff --git a/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs b/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs index 72872a8910ea..4fee35b06219 100644 --- a/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs +++ b/crates/rspack_plugin_javascript/src/parser_and_generator/mod.rs @@ -12,7 +12,7 @@ use rspack_core::{ TemplateContext, TemplateReplaceSource, }; use rspack_error::{ - internal_error, Diagnostic, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, + internal_error, IntoTWithRspackDiagnosticArray, Result, RspackDiagnostic, TWithDiagnosticArray, }; use swc_core::common::SyntaxContext; @@ -93,7 +93,7 @@ impl ParserAndGenerator for JavaScriptParserAndGenerator { .. } = parse_context; - let mut diagnostics: Vec = vec![]; + let mut diagnostics: Vec = vec![]; let syntax = syntax_by_module_type( &resource_data.resource_path, module_type, @@ -105,7 +105,7 @@ impl ParserAndGenerator for JavaScriptParserAndGenerator { let original_map = source.map(&MapOptions::new(!compiler_options.devtool.cheap())); let source = source.source(); - let gen_terminate_res = |diagnostics: Vec| { + let gen_terminate_res = |diagnostics: Vec| { Ok( ParseResult { source: create_source( diff --git a/crates/rspack_plugin_javascript/src/utils/mod.rs b/crates/rspack_plugin_javascript/src/utils/mod.rs index 73abf6938a13..566738ef394a 100644 --- a/crates/rspack_plugin_javascript/src/utils/mod.rs +++ b/crates/rspack_plugin_javascript/src/utils/mod.rs @@ -104,7 +104,7 @@ pub fn ecma_parse_error_to_rspack_error( }; let message = error.kind().msg().to_string(); let span: ErrorSpan = error.span().into(); - let traceable_error = rspack_error::TraceableRspackError::from_source_file( + let traceable_error = rspack_error::TraceableError::from_source_file( fm, span.start as usize, span.end as usize, @@ -112,7 +112,15 @@ pub fn ecma_parse_error_to_rspack_error( message, ) .with_kind(diagnostic_kind); - Error::TraceableRspackError(traceable_error) + // let traceable_error = rspack_error::TraceableRspackError::from_source_file( + // fm, + // span.start as usize, + // span.end as usize, + // format!("{file_type} parsing error"), + // message, + // ) + // .with_kind(diagnostic_kind); + Error::InternalError(traceable_error.into()) } pub fn join_jsword(arr: &[JsWord], separator: &str) -> String { diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/import_meta_scanner.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/import_meta_scanner.rs index aef72465f715..d6fe604523ff 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/import_meta_scanner.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/import_meta_scanner.rs @@ -1,5 +1,5 @@ use rspack_core::{CompilerOptions, ConstDependency, DependencyTemplate, ResourceData, SpanExt}; -use rspack_error::Diagnostic; +use rspack_error::RspackDiagnostic; use swc_core::common::Spanned; use swc_core::ecma::ast::{Expr, NewExpr, UnaryExpr, UnaryOp}; use swc_core::ecma::visit::{noop_visit_type, Visit, VisitWith}; @@ -20,7 +20,7 @@ pub struct ImportMetaScanner<'a> { pub presentational_dependencies: &'a mut Vec>, pub compiler_options: &'a CompilerOptions, pub resource_data: &'a ResourceData, - pub warning_diagnostics: &'a mut Vec, + pub warning_diagnostics: &'a mut Vec, } impl<'a> ImportMetaScanner<'a> { @@ -28,7 +28,7 @@ impl<'a> ImportMetaScanner<'a> { presentational_dependencies: &'a mut Vec>, resource_data: &'a ResourceData, compiler_options: &'a CompilerOptions, - warning_diagnostics: &'a mut Vec, + warning_diagnostics: &'a mut Vec, ) -> Self { Self { presentational_dependencies, @@ -91,7 +91,7 @@ impl Visit for ImportMetaScanner<'_> { // import.meta if expr_matcher::is_import_meta(expr) { // warn when access import.meta directly - self.warning_diagnostics.push(Diagnostic::warn( + self.warning_diagnostics.push(RspackDiagnostic::warn( String::from("import.meta warning"), String::from( "Critical dependency: Accessing import.meta directly is unsupported (only property access or destructuring is supported)"), diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs index d69e1958b4f6..cdd5184d1dae 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs @@ -23,7 +23,7 @@ use rspack_core::{ AsyncDependenciesBlock, BoxDependency, BoxDependencyTemplate, BuildInfo, BuildMeta, CompilerOptions, ModuleIdentifier, ModuleType, ResourceData, }; -use rspack_error::{Diagnostic, Result}; +use rspack_error::{Result, RspackDiagnostic}; use rustc_hash::FxHashMap as HashMap; use swc_core::common::Span; use swc_core::common::{comments::Comments, Mark, SyntaxContext}; @@ -53,7 +53,7 @@ pub struct ScanDependenciesResult { // TODO: rename this name pub rewrite_usage_span: HashMap, pub import_map: ImportMap, - pub warning_diagnostics: Vec, + pub warning_diagnostics: Vec, } #[derive(Debug, Clone, Default)] @@ -76,7 +76,7 @@ pub fn scan_dependencies( build_meta: &mut BuildMeta, module_identifier: ModuleIdentifier, ) -> Result { - let mut warning_diagnostics: Vec = vec![]; + let mut warning_diagnostics: Vec = vec![]; let mut errors = vec![]; let mut dependencies = vec![]; let mut blocks = vec![]; diff --git a/crates/rspack_plugin_json/src/lib.rs b/crates/rspack_plugin_json/src/lib.rs index 83479b630378..e26eca965cec 100644 --- a/crates/rspack_plugin_json/src/lib.rs +++ b/crates/rspack_plugin_json/src/lib.rs @@ -7,8 +7,8 @@ use rspack_core::{ ParserAndGenerator, Plugin, RuntimeGlobals, SourceType, }; use rspack_error::{ - internal_error, DiagnosticKind, Error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, - TraceableRspackError, + internal_error, DiagnosticKind, Error, IntoTWithRspackDiagnosticArray, Result, + TWithDiagnosticArray, TraceableRspackError, }; mod utils; diff --git a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs index a04a07fdcc76..76dfc4dee3d3 100644 --- a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs +++ b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs @@ -18,7 +18,7 @@ use rspack_core::{ AssetInfo, CompilationAsset, JsChunkHashArgs, Plugin, PluginContext, PluginJsChunkHashHookOutput, PluginProcessAssetsOutput, ProcessAssetsArgs, }; -use rspack_error::{internal_error, Diagnostic, Result}; +use rspack_error::{internal_error, Result, RspackDiagnostic}; use rspack_regex::RspackRegex; use rspack_util::try_any_sync; use swc_config::config_types::BoolOrDataConfig; @@ -140,7 +140,7 @@ impl Plugin for SwcJsMinimizerRspackPlugin { let compilation = args.compilation; let minify_options = &self.options; - let (tx, rx) = mpsc::channel::>(); + let (tx, rx) = mpsc::channel::>(); // collect all extracted comments info let all_extracted_comments = Mutex::new(HashMap::new()); let extract_comments_condition = minify_options.extract_comments.as_ref().map(|condition| { diff --git a/crates/rspack_plugin_warn_sensitive_module/src/lib.rs b/crates/rspack_plugin_warn_sensitive_module/src/lib.rs index 89f647c4b2dc..0e051c9ed699 100644 --- a/crates/rspack_plugin_warn_sensitive_module/src/lib.rs +++ b/crates/rspack_plugin_warn_sensitive_module/src/lib.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use rspack_core::{Compilation, Logger, Module, ModuleGraph, Plugin}; -use rspack_error::Diagnostic; +use rspack_error::RspackDiagnostic; #[derive(Debug, Default)] pub struct WarnCaseSensitiveModulesPlugin; @@ -52,7 +52,7 @@ impl Plugin for WarnCaseSensitiveModulesPlugin { fn seal(&self, compilation: &mut Compilation) -> rspack_error::Result<()> { let logger = compilation.get_logger(self.name()); let start = logger.time("check case sensitive modules"); - let mut diagnostics: Vec = vec![]; + let mut diagnostics: Vec = vec![]; let modules = compilation .module_graph .modules() @@ -87,7 +87,7 @@ impl Plugin for WarnCaseSensitiveModulesPlugin { if lower_map.values().len() > 1 { let mut case_modules = lower_map.values().map(|m| m.as_ref()).collect::>(); case_modules.sort_by_key(|m| m.identifier()); - diagnostics.push(Diagnostic::warn( + diagnostics.push(RspackDiagnostic::warn( "Sensitive Modules Warn".to_string(), self.create_sensitive_modules_warning(&case_modules, &compilation.module_graph), 0, diff --git a/crates/rspack_plugin_wasm/src/parser_and_generator.rs b/crates/rspack_plugin_wasm/src/parser_and_generator.rs index 86f8a6ec0fa4..66929b967e7d 100644 --- a/crates/rspack_plugin_wasm/src/parser_and_generator.rs +++ b/crates/rspack_plugin_wasm/src/parser_and_generator.rs @@ -9,7 +9,9 @@ use rspack_core::{ ModuleDependency, ModuleIdentifier, NormalModule, ParseContext, ParseResult, ParserAndGenerator, PathData, RuntimeGlobals, SourceType, UsedName, }; -use rspack_error::{Diagnostic, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray}; +use rspack_error::{ + IntoTWithRspackDiagnosticArray, Result, RspackDiagnostic, TWithDiagnosticArray, +}; use rspack_identifier::Identifier; use swc_core::atoms::Atom; use wasmparser::{Import, Parser, Payload}; @@ -47,7 +49,7 @@ impl ParserAndGenerator for AsyncWasmParserAndGenerator { for export in s { match export { Ok(export) => exports.push(export.name.to_string()), - Err(err) => diagnostic.push(Diagnostic::error( + Err(err) => diagnostic.push(RspackDiagnostic::error( "Wasm Export Parse Error".into(), err.to_string(), 0, @@ -66,7 +68,7 @@ impl ParserAndGenerator for AsyncWasmParserAndGenerator { ty, ))); } - Err(err) => diagnostic.push(Diagnostic::error( + Err(err) => diagnostic.push(RspackDiagnostic::error( "Wasm Import Parse Error".into(), err.to_string(), 0, @@ -78,7 +80,7 @@ impl ParserAndGenerator for AsyncWasmParserAndGenerator { _ => {} }, Err(err) => { - diagnostic.push(Diagnostic::error( + diagnostic.push(RspackDiagnostic::error( "Wasm Parse Error".into(), err.to_string(), 0,