From d8388fff88cc8179f6db9c703399ad5fe17d8bbf Mon Sep 17 00:00:00 2001 From: Hana Date: Mon, 4 Dec 2023 22:22:22 +0800 Subject: [PATCH] feat: align module error --- Cargo.lock | 11 - .../src/options/raw_module/js_loader.rs | 5 +- crates/rspack_core/src/cache/mod.rs | 15 +- .../src/cache/occasion/build_module.rs | 332 +++++++++--------- crates/rspack_core/src/cache/occasion/mod.rs | 4 +- .../rspack_core/src/compiler/compilation.rs | 6 +- crates/rspack_core/src/compiler/queue.rs | 117 +++--- crates/rspack_core/src/diagnostics.rs | 4 + crates/rspack_core/src/lib.rs | 1 + .../rspack_core/src/normal_module_factory.rs | 15 +- .../rspack_core/src/resolver/resolver_impl.rs | 8 +- crates/rspack_error/Cargo.toml | 21 +- crates/rspack_error/src/diagnostic.rs | 200 ++++++----- crates/rspack_error/src/emitter.rs | 118 ++----- crates/rspack_error/src/error.rs | 213 +++++------ crates/rspack_error/src/lib.rs | 16 +- crates/rspack_loader_sass/src/lib.rs | 19 +- crates/rspack_plugin_html/src/parser.rs | 4 +- .../rspack_plugin_javascript/src/utils/mod.rs | 12 +- crates/rspack_plugin_json/src/lib.rs | 16 +- .../src/minify.rs | 9 +- 21 files changed, 559 insertions(+), 587 deletions(-) create mode 100644 crates/rspack_core/src/diagnostics.rs diff --git a/Cargo.lock b/Cargo.lock index ddf97f291da2..4f56b21490b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2393,16 +2393,6 @@ dependencies = [ "xshell", ] -[[package]] -name = "rspack-codespan-reporting" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc53b3a0e58f509a8b55bde278d44c05879f27a66819346e0fef193c6348e9f8" -dependencies = [ - "termcolor", - "unicode-width", -] - [[package]] name = "rspack_ast" version = "0.1.0" @@ -2634,7 +2624,6 @@ dependencies = [ "futures", "insta", "miette 5.10.0", - "rspack-codespan-reporting", "rspack_binding_options", "rspack_core", "rspack_fs", 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..7454c0438959 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 @@ -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_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/cache/occasion/mod.rs b/crates/rspack_core/src/cache/occasion/mod.rs index 7a63c16294f2..62406ac09640 100644 --- a/crates/rspack_core/src/cache/occasion/mod.rs +++ b/crates/rspack_core/src/cache/occasion/mod.rs @@ -1,7 +1,7 @@ mod resolve_module; pub use resolve_module::*; -mod build_module; -pub use build_module::*; +// mod build_module; +// pub use build_module::*; mod code_generate; pub use code_generate::*; mod create_chunk_assets; diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index ab27cac3bcf1..c76b4bbb8f21 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -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..eb70455b49d9 100644 --- a/crates/rspack_core/src/compiler/queue.rs +++ b/crates/rspack_core/src/compiler/queue.rs @@ -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/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/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/normal_module_factory.rs b/crates/rspack_core/src/normal_module_factory.rs index 1728419935d1..465d7522aea1 100644 --- a/crates/rspack_core/src/normal_module_factory.rs +++ b/crates/rspack_core/src/normal_module_factory.rs @@ -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/resolver/resolver_impl.rs b/crates/rspack_core/src/resolver/resolver_impl.rs index b627309805f5..bdc969cb3690 100644 --- a/crates/rspack_core/src/resolver/resolver_impl.rs +++ b/crates/rspack_core/src/resolver/resolver_impl.rs @@ -5,7 +5,7 @@ use std::{ }; use rspack_error::{ - internal_error, DiagnosticError, Error, InternalError, Severity, TraceableRspackError, + internal_error, DiagnosticError, Error, InternalError, Severity, TraceableError, }; use rspack_loader_runner::DescriptionData; use sugar_path::SugarPath; @@ -523,7 +523,7 @@ fn map_resolver_error( }; ResolveError( runtime_message, - TraceableRspackError::from_real_file_path( + TraceableError::from_real_file_path( Path::new( importer .split_once('|') @@ -537,9 +537,9 @@ fn map_resolver_error( ) .map(|e| { if args.optional { - Error::TraceableRspackError(e.with_severity(Severity::Warn)) + Error::InternalError(e.with_severity(Severity::Warn).into()) } else { - Error::TraceableRspackError(e) + Error::InternalError(e.into()) } }) .unwrap_or_else(|_| { diff --git a/crates/rspack_error/Cargo.toml b/crates/rspack_error/Cargo.toml index 6398a218d57d..06cf9387ce08 100644 --- a/crates/rspack_error/Cargo.toml +++ b/crates/rspack_error/Cargo.toml @@ -8,17 +8,16 @@ version = "0.1.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -anyhow = { workspace = true, features = ["backtrace"] } -codespan-reporting = { version = "=0.11.2", package = "rspack-codespan-reporting" } -futures = { workspace = true } -miette = { version = "5", features = ["fancy"] } -rspack_sources = { workspace = true } -rspack_util = { path = "../rspack_util" } -serde_json = { workspace = true } -sugar_path = { workspace = true } -swc_core = { workspace = true, features = ["common"] } -termcolor = "1.2" -thiserror = "1" +anyhow = { workspace = true, features = ["backtrace"] } +futures = { workspace = true } +miette = { version = "5", features = ["fancy"] } +rspack_sources = { workspace = true } +rspack_util = { path = "../rspack_util" } +serde_json = { workspace = true } +sugar_path = { workspace = true } +swc_core = { workspace = true, features = ["common"] } +termcolor = "1" +thiserror = "1" [dev-dependencies] insta = { workspace = true } diff --git a/crates/rspack_error/src/diagnostic.rs b/crates/rspack_error/src/diagnostic.rs index c55d897f0532..08fe0d160e90 100644 --- a/crates/rspack_error/src/diagnostic.rs +++ b/crates/rspack_error/src/diagnostic.rs @@ -1,31 +1,46 @@ -use std::fmt; +use std::{ + fmt, + ops::{Deref, DerefMut}, +}; -use crate::{DiagnosticKind, Error, TraceableRspackError}; +use crate::{DiagnosticKind, Error}; #[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Hash)] -pub enum Severity { +pub enum RspackSeverity { #[default] Error, Warn, } -impl From for miette::Severity { - fn from(value: Severity) -> Self { +pub type Severity = RspackSeverity; + +impl From for miette::Severity { + fn from(value: RspackSeverity) -> Self { match value { - Severity::Error => miette::Severity::Error, - Severity::Warn => miette::Severity::Warning, + RspackSeverity::Error => miette::Severity::Error, + RspackSeverity::Warn => miette::Severity::Warning, } } } -impl fmt::Display for Severity { +impl From for RspackSeverity { + fn from(value: miette::Severity) -> Self { + match value { + miette::Severity::Error => RspackSeverity::Error, + miette::Severity::Warning => RspackSeverity::Warn, + miette::Severity::Advice => unimplemented!("Not supported miette Serverity"), + } + } +} + +impl fmt::Display for RspackSeverity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { - Severity::Error => "error", - Severity::Warn => "warning", + RspackSeverity::Error => "error", + RspackSeverity::Warn => "warning", } ) } @@ -37,104 +52,119 @@ 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 { - pub fn warn(title: String, message: String, start: usize, end: usize) -> Self { - Self { - severity: Severity::Warn, - title, - message, - source_info: None, - start, - end, - ..Default::default() - } +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 struct Diagnostic(miette::Report); + +impl Deref for Diagnostic { + type Target = miette::Report; + + fn deref(&self) -> &Self::Target { + &self.0 } +} - pub fn error(title: String, message: String, start: usize, end: usize) -> Self { - Self { - severity: Severity::Error, - message, - source_info: None, - start, - end, - title, - ..Default::default() - } +impl DerefMut for Diagnostic { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 } +} + +/// Shouldn't rely on this in [Compilation::diagnostics]. +/// Have to make sure everything is deduped in the first place. +impl std::hash::Hash for Diagnostic { + fn hash(&self, state: &mut H) { + self.0.to_string().hash(state); + self.0.code().map(|c| c.to_string()).hash(state); + self.0.help().map(|h| h.to_string()).hash(state); + self.0.url().map(|u| u.to_string()).hash(state); + self.0.severity().map(Severity::from).hash(state); + } +} + +/// Shouldn't rely on this in [Compilation::diagnostics]. +/// Have to make sure everything is deduped in the first place. +impl PartialEq for Diagnostic { + fn eq(&self, other: &Self) -> bool { + self.0.to_string() == other.0.to_string() + && self.0.code().map(|c| c.to_string()) == other.0.code().map(|c| c.to_string()) + && self.0.help().map(|h| h.to_string()) == other.0.help().map(|h| h.to_string()) + && self.0.url().map(|u| u.to_string()) == other.0.url().map(|u| u.to_string()) + && self.0.severity() == other.0.severity() + } +} - pub fn title(&self) -> &str { - &self.title +impl Eq for Diagnostic {} + +impl Diagnostic { + pub fn title(&self) -> String { + self.0.code().map(|v| v.to_string()).unwrap_or_default() } - pub fn message(&self) -> &str { - &self.message + pub fn message(&self) -> String { + self.0.to_string() } pub fn severity(&self) -> Severity { - self.severity + self.0.severity().unwrap_or_default().into() } - pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { - self.kind = kind; - self + pub fn warn(title: String, message: String, start: usize, end: usize) -> Self { + unreachable!("refactor") } - pub fn with_source_info(mut self, source: DiagnosticSourceInfo) -> Self { - self.source_info = Some(source); - self + pub fn error(title: String, message: String, start: usize, end: usize) -> Self { + unreachable!("refactor") } - pub fn with_notes(mut self, notes: Vec) -> Self { - self.notes = notes; - self + + pub fn kind(&self) -> DiagnosticKind { + unreachable!("refactor") + } + + pub fn notes(&self) -> Vec { + unreachable!("refactor") + } + + pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { + unreachable!("refactor") + } + + pub fn add_notes(&mut self, notes: Vec) { + unreachable!("refactor") } } 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::TraceableRspackError(TraceableRspackError { - start, - end, - error_message, - title, - kind, - severity, - file_path, - file_src, - }) => Diagnostic { - message: error_message, - source_info: Some(DiagnosticSourceInfo { - source: file_src, - path: file_path, - }), - start, - end, - title, - kind, - severity, - ..Default::default() - }, + Error::InternalError(err) => Diagnostic(err.0), Error::BatchErrors(diagnostics) => { return diagnostics .into_iter() diff --git a/crates/rspack_error/src/emitter.rs b/crates/rspack_error/src/emitter.rs index 209c8eab31a9..d84c9866d46c 100644 --- a/crates/rspack_error/src/emitter.rs +++ b/crates/rspack_error/src/emitter.rs @@ -1,15 +1,16 @@ -use std::io::Write; -use std::path::Path; +use std::io::{IsTerminal, Write}; 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 sugar_path::SugarPath; +use miette::{GraphicalReportHandler, GraphicalTheme, IntoDiagnostic}; use termcolor::{Buffer, ColorSpec, StandardStreamLock, WriteColor}; +use termcolor::{ColorChoice, StandardStream}; -use crate::Diagnostic as RspackDiagnostic; +use crate::Diagnostic; + +/// 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) {} @@ -28,9 +29,9 @@ pub trait DiagnosticDisplay { type Output; fn emit_batch_diagnostic( &mut self, - diagnostics: impl Iterator, + diagnostics: impl Iterator, ) -> Self::Output; - fn emit_diagnostic(&mut self, diagnostic: &RspackDiagnostic) -> Self::Output; + fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) -> Self::Output; } #[derive(Default)] @@ -41,19 +42,17 @@ impl DiagnosticDisplay for StdioDiagnosticDisplay { fn emit_batch_diagnostic( &mut self, - diagnostics: impl Iterator, + diagnostics: impl Iterator, ) -> Self::Output { let writer = StandardStream::stderr(ColorChoice::Always); let mut lock_writer = writer.lock(); emit_batch_diagnostic(diagnostics, &mut lock_writer) } - fn emit_diagnostic(&mut self, diagnostic: &RspackDiagnostic) -> Self::Output { + fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) -> Self::Output { let writer = StandardStream::stderr(ColorChoice::Always); let mut lock_writer = writer.lock(); - let mut files = SimpleFiles::new(); - let pwd = std::env::current_dir()?; - emit_diagnostic(diagnostic, &mut lock_writer, &pwd, &mut files) + emit_diagnostic(diagnostic, &mut lock_writer) } } @@ -102,7 +101,7 @@ impl DiagnosticDisplay for StringDiagnosticDisplay { fn emit_batch_diagnostic( &mut self, - diagnostics: impl Iterator, + diagnostics: impl Iterator, ) -> Self::Output { emit_batch_diagnostic(diagnostics, self)?; if self.sorted { @@ -111,10 +110,8 @@ impl DiagnosticDisplay for StringDiagnosticDisplay { Ok(self.diagnostic_vector.drain(..).collect()) } - fn emit_diagnostic(&mut self, diagnostic: &RspackDiagnostic) -> Self::Output { - let mut files = SimpleFiles::new(); - let pwd = std::env::current_dir()?; - emit_diagnostic(diagnostic, self, &pwd, &mut files)?; + fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) -> Self::Output { + emit_diagnostic(diagnostic, self)?; self.flush_diagnostic(); Ok( self @@ -133,35 +130,28 @@ impl DiagnosticDisplay for ColoredStringDiagnosticDisplay { fn emit_batch_diagnostic( &mut self, - diagnostics: impl Iterator, + diagnostics: impl Iterator, ) -> Self::Output { - let mut files = SimpleFiles::new(); - let pwd = std::env::current_dir()?; let mut buf = Buffer::ansi(); for d in diagnostics { - emit_diagnostic(d, &mut buf, &pwd, &mut files)?; + emit_diagnostic(d, &mut buf)?; } Ok(String::from_utf8_lossy(buf.as_slice()).to_string()) } - fn emit_diagnostic(&mut self, diagnostic: &RspackDiagnostic) -> Self::Output { - let mut files = SimpleFiles::new(); - let pwd = std::env::current_dir()?; + fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) -> Self::Output { let mut buf = Buffer::ansi(); - emit_diagnostic(diagnostic, &mut buf, &pwd, &mut files)?; + emit_diagnostic(diagnostic, &mut buf)?; Ok(String::from_utf8_lossy(buf.as_slice()).to_string()) } } fn emit_batch_diagnostic( - diagnostics: impl Iterator, + diagnostics: impl Iterator, writer: &mut T, ) -> crate::Result<()> { - let mut files = SimpleFiles::new(); - let pwd = std::env::current_dir()?; - for diagnostic in diagnostics { - emit_diagnostic(diagnostic, writer, &pwd, &mut files)?; + emit_diagnostic(diagnostic, writer)?; // `codespan_reporting` will not write the diagnostic message in a whole, // we need to insert some helper flag for sorting writer.flush_diagnostic(); @@ -170,53 +160,23 @@ fn emit_batch_diagnostic( } fn emit_diagnostic( - diagnostic: &RspackDiagnostic, + diagnostic: &Diagnostic, writer: &mut T, - pwd: impl AsRef, - files: &mut SimpleFiles, ) -> crate::Result<()> { - let (labels, message) = match &diagnostic.source_info { - Some(info) => { - let file_path = Path::new(&info.path); - let relative_path = file_path.relative(&pwd); - let relative_path = relative_path.as_os_str().to_string_lossy().to_string(); - let file_id = files.add(relative_path, info.source.clone()); - ( - vec![Label::primary(file_id, diagnostic.start..diagnostic.end) - .with_message(&diagnostic.message)], - diagnostic.title.clone(), - ) - } - None => (vec![], diagnostic.message.clone()), - }; - - let diagnostic = Diagnostic::new(diagnostic.severity.into()) - .with_message(message) - // Because we don't have error code now, and I don't think we have - // enough energy to matain error code either in the future, so I use - // this field to represent diagnostic kind, looks pretty neat. - .with_code(diagnostic.kind.to_string()) - .with_notes(diagnostic.notes.clone()) - .with_labels(labels); - - let config = Config { - before_label_lines: 4, - after_label_lines: 4, - ..Config::default() - }; - - term::emit(writer, &config, files, &diagnostic).expect("TODO:"); + let h = GraphicalReportHandler::new().with_theme(if !is_terminal() { + GraphicalTheme::ascii() + } else if writer.supports_color() { + GraphicalTheme::unicode() + } else { + GraphicalTheme::unicode_nocolor() + }); + let mut buf = String::new(); + h.render_report(&mut buf, diagnostic.as_ref()) + .into_diagnostic()?; + writer.write_all(buf.as_bytes()).into_diagnostic()?; // reset to original color after emitting a diagnostic, this avoids interference stdio of other procedure. - writer.reset().map_err(|e| e.into()) -} - -impl From for Severity { - fn from(severity: crate::Severity) -> Self { - match severity { - crate::Severity::Error => Self::Error, - crate::Severity::Warn => Self::Warning, - } - } + writer.reset().into_diagnostic()?; + Ok(()) } #[derive(Debug, Clone)] @@ -240,7 +200,7 @@ impl DiagnosticDisplay for DiagnosticDisplayer { fn emit_batch_diagnostic( &mut self, - diagnostics: impl Iterator, + diagnostics: impl Iterator, ) -> Self::Output { match self { Self::Colored(d) => d.emit_batch_diagnostic(diagnostics), @@ -248,7 +208,7 @@ impl DiagnosticDisplay for DiagnosticDisplayer { } } - fn emit_diagnostic(&mut self, diagnostic: &RspackDiagnostic) -> Self::Output { + fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) -> Self::Output { match self { Self::Colored(d) => d.emit_diagnostic(diagnostic), Self::Plain(d) => d.emit_diagnostic(diagnostic), diff --git a/crates/rspack_error/src/error.rs b/crates/rspack_error/src/error.rs index e1ea315ac5eb..351c7bfd1a6c 100644 --- a/crates/rspack_error/src/error.rs +++ b/crates/rspack_error/src/error.rs @@ -1,14 +1,28 @@ -use std::{fmt, io, path::Path}; - -use miette::{Diagnostic, IntoDiagnostic, MietteDiagnostic, NamedSource, SourceSpan}; +use std::{ + fmt, io, + path::{Path, PathBuf}, +}; + +use miette::{ + Diagnostic, IntoDiagnostic, LabeledSpan, MietteDiagnostic, NamedSource, SourceCode, SourceSpan, +}; use rspack_util::swc::normalize_custom_filename; +use sugar_path::SugarPath; use swc_core::common::SourceFile; use thiserror::Error; -use crate::Severity; +use crate::RspackSeverity; + +/// # Panic +/// +/// Panics if `current_dir` is not accessible. +/// See [std::env::current_dir] for details. +fn relative_to_pwd(file: impl AsRef) -> PathBuf { + file.as_ref().relative(std::env::current_dir().unwrap()) +} #[derive(Debug)] -pub struct InternalError(miette::Report); +pub struct InternalError(pub(crate) miette::Report); impl From for InternalError { fn from(value: T) -> Self { @@ -17,7 +31,7 @@ impl From for InternalError { } impl InternalError { - pub fn new(error_message: String, severity: Severity) -> Self { + pub fn new(error_message: String, severity: RspackSeverity) -> Self { Self(miette::Report::new( MietteDiagnostic::new(error_message.clone()).with_severity(severity.into()), )) @@ -37,12 +51,12 @@ impl InternalError { } } - pub fn severity(&self) -> Severity { + pub fn severity(&self) -> RspackSeverity { let severity = self.cast_to_miette().severity.as_ref(); match severity.expect("severity should available") { miette::Severity::Advice => unreachable!(), - miette::Severity::Warning => Severity::Warn, - miette::Severity::Error => Severity::Error, + miette::Severity::Warning => RspackSeverity::Warn, + miette::Severity::Error => RspackSeverity::Error, } } } @@ -53,21 +67,58 @@ impl fmt::Display for InternalError { } } -#[derive(Debug, Error, Diagnostic)] -#[diagnostic(code(TraceableError))] -#[error("error[{kind}]: {title}")] +/// ## Warning +/// For a [TraceableError], the path is required. +/// Because if the source code is missing when you construct a [TraceableError], we could read it from file system later +/// when convert it into [crate::Diagnostic], but the reverse will not working. +#[derive(Debug, Error)] +#[error("{severity:?}[{kind}]: {title}")] pub struct TraceableError { title: String, kind: DiagnosticKind, message: String, - // file_path: String, - #[source_code] + severity: miette::Severity, src: NamedSource, - #[label("{message}")] label: SourceSpan, } +impl miette::Diagnostic for TraceableError { + fn severity(&self) -> Option { + Some(self.severity) + } + fn labels(&self) -> Option + '_>> { + use miette::macro_helpers::{OptionalWrapper, ToOption}; + let Self { message, .. } = self; + std::option::Option::Some(Box::new( + vec![OptionalWrapper::::new() + .to_option(&self.label) + .map(|label| { + miette::LabeledSpan::new_with_span( + Some(format!("{message}", message = message)), + label.clone(), + ) + })] + .into_iter() + .filter(Option::is_some) + .map(Option::unwrap), + )) + } + fn source_code(&self) -> Option<&dyn SourceCode> { + Some(&self.src) + } +} + impl TraceableError { + pub fn with_severity(mut self, severity: impl Into) -> Self { + self.severity = severity.into(); + self + } + + pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { + self.kind = kind; + self + } + pub fn from_source_file( source_file: &SourceFile, start: usize, @@ -76,12 +127,17 @@ impl TraceableError { message: String, ) -> Self { let file_path = normalize_custom_filename(&source_file.name.to_string()).to_string(); + let file_path = relative_to_pwd(PathBuf::from(file_path)); let file_src = source_file.src.to_string(); Self { title, kind: Default::default(), message, - src: NamedSource::new(file_path, file_src), + severity: Default::default(), + src: NamedSource::new( + file_path.as_os_str().to_string_lossy().to_string(), + file_src, + ), label: SourceSpan::new(start.into(), (end - start).into()), } } @@ -94,11 +150,16 @@ impl TraceableError { title: String, message: String, ) -> Self { + let file_path = relative_to_pwd(PathBuf::from(file_path)); Self { title, kind: Default::default(), message, - src: NamedSource::new(file_path, file_src), + severity: Default::default(), + src: NamedSource::new( + file_path.as_os_str().to_string_lossy().to_string(), + file_src, + ), label: SourceSpan::new(start.into(), (end - start).into()), } } @@ -122,107 +183,9 @@ impl TraceableError { } } -#[derive(Debug)] -/// ## Warning -/// For a [TraceableRspackError], the path is required. -/// Because if the source code is missing when you construct a [TraceableRspackError], we could read it from file system later -/// when convert it into [crate::Diagnostic], but the reverse will not working. -pub struct TraceableRspackError { - /// path of a file (real file or virtual file) - pub(crate) file_path: String, - /// source content of a file (real file or virtual file) - pub(crate) file_src: String, - pub(crate) start: usize, - pub(crate) end: usize, - pub(crate) error_message: String, - pub(crate) title: String, - pub(crate) kind: DiagnosticKind, - pub(crate) severity: Severity, -} - -impl TraceableRspackError { - pub fn from_source_file( - source_file: &SourceFile, - start: usize, - end: usize, - title: String, - error_message: String, - ) -> Self { - let file_path = normalize_custom_filename(&source_file.name.to_string()).to_string(); - let file_src = source_file.src.to_string(); - Self { - file_path, - file_src, - start, - end, - error_message, - title, - kind: DiagnosticKind::Internal, - severity: Severity::Error, - } - } - - pub fn from_file( - file_path: String, - file_src: String, - start: usize, - end: usize, - title: String, - error_message: String, - ) -> Self { - Self { - file_path, - file_src, - start, - end, - error_message, - title, - kind: DiagnosticKind::Internal, - severity: Severity::Error, - } - } - - pub fn from_real_file_path( - path: &Path, - start: usize, - end: usize, - title: String, - error_message: String, - ) -> Result { - let file_src = std::fs::read_to_string(path)?; - Ok(Self::from_file( - path.to_string_lossy().into_owned(), - file_src, - start, - end, - title, - error_message, - )) - } - - pub fn with_kind(mut self, kind: DiagnosticKind) -> Self { - self.kind = kind; - self - } - - pub fn with_severity(mut self, severity: Severity) -> Self { - self.severity = severity; - self - } -} - -impl fmt::Display for TraceableRspackError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f, "{}[{}]: {}", self.severity, self.kind, self.title)?; - writeln!(f, "{}", self.error_message)?; - writeln!(f, "in {}", self.file_path) - } -} - #[derive(Debug)] pub enum Error { InternalError(InternalError), - TraceableRspackError(TraceableRspackError), BatchErrors(Vec), } @@ -245,7 +208,6 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::InternalError(e) => write!(f, "{e}"), - Error::TraceableRspackError(v) => write!(f, "{v}"), Error::BatchErrors(errs) => write!( f, "{}", @@ -261,7 +223,7 @@ impl fmt::Display for Error { impl From for Error { fn from(value: serde_json::Error) -> Self { - Error::InternalError(InternalError::new(value.to_string(), Severity::Error)) + Error::InternalError(InternalError::new(value.to_string(), RspackSeverity::Error)) } } @@ -283,23 +245,6 @@ impl From for Error { } } -impl Error { - pub fn kind(&self) -> DiagnosticKind { - match self { - Error::InternalError(_) => DiagnosticKind::Internal, - Error::TraceableRspackError(TraceableRspackError { kind, .. }) => *kind, - Error::BatchErrors(_) => DiagnosticKind::Internal, - } - } - pub fn severity(&self) -> Severity { - match self { - Error::InternalError(_) => Severity::Error, - Error::TraceableRspackError(TraceableRspackError { severity, .. }) => *severity, - Error::BatchErrors(_) => Severity::Error, - } - } -} - #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub enum DiagnosticKind { JavaScript, diff --git a/crates/rspack_error/src/lib.rs b/crates/rspack_error/src/lib.rs index 3f61fdf1a0eb..69e573d88429 100644 --- a/crates/rspack_error/src/lib.rs +++ b/crates/rspack_error/src/lib.rs @@ -42,14 +42,14 @@ impl TWithDiagnosticArray { } } -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 { diff --git a/crates/rspack_loader_sass/src/lib.rs b/crates/rspack_loader_sass/src/lib.rs index af8a80327f9d..561fc393ff0d 100644 --- a/crates/rspack_loader_sass/src/lib.rs +++ b/crates/rspack_loader_sass/src/lib.rs @@ -16,7 +16,7 @@ use rspack_core::{ }; use rspack_error::{ internal_error, Diagnostic, DiagnosticKind, Error, InternalError, Result, Severity, - TraceableRspackError, + TraceableError, }; use rspack_loader_runner::{Identifiable, Identifier, Loader, LoaderContext}; use sass_embedded::{ @@ -524,7 +524,7 @@ fn sass_exception_to_error(e: Box) -> Error { && let Some(message) = e.sass_message() && let Some(e) = make_traceable_error("Sass Error", message, span) { - Error::TraceableRspackError(e.with_kind(DiagnosticKind::Scss)) + Error::InternalError(e.with_kind(DiagnosticKind::Scss).into()) } else { internal_error!(e.message().to_string()) } @@ -542,7 +542,12 @@ fn sass_log_to_diagnostics( if let Some(span) = span && let Some(e) = make_traceable_error(title, message, span) { - Error::TraceableRspackError(e.with_kind(DiagnosticKind::Scss).with_severity(severity)).into() + Error::InternalError( + e.with_kind(DiagnosticKind::Scss) + .with_severity(severity) + .into(), + ) + .into() } else { let f = match severity { Severity::Error => Diagnostic::error, @@ -552,11 +557,7 @@ fn sass_log_to_diagnostics( } } -fn make_traceable_error( - title: &str, - message: &str, - span: &SourceSpan, -) -> Option { +fn make_traceable_error(title: &str, message: &str, span: &SourceSpan) -> Option { span .url .as_ref() @@ -575,7 +576,7 @@ fn make_traceable_error( .map(|(path, source)| { let start = utf16::to_byte_idx(&source, span.start.offset); let end = utf16::to_byte_idx(&source, span.end.offset); - TraceableRspackError::from_file( + TraceableError::from_file( path, source, start, diff --git a/crates/rspack_plugin_html/src/parser.rs b/crates/rspack_plugin_html/src/parser.rs index 6eaa410e361f..10ef4c03b7d2 100644 --- a/crates/rspack_plugin_html/src/parser.rs +++ b/crates/rspack_plugin_html/src/parser.rs @@ -66,7 +66,7 @@ pub fn html_parse_error_to_traceable_error(error: Error, fm: &SourceFile) -> rsp let message = error.message(); let error = error.into_inner(); let span: ErrorSpan = error.0.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, @@ -75,5 +75,5 @@ pub fn html_parse_error_to_traceable_error(error: Error, fm: &SourceFile) -> rsp ) .with_kind(DiagnosticKind::Html); //Use this `Error` conversion could avoid eagerly clone source file. - rspack_error::Error::TraceableRspackError(traceable_error) + rspack_error::Error::InternalError(traceable_error.into()) } diff --git a/crates/rspack_plugin_javascript/src/utils/mod.rs b/crates/rspack_plugin_javascript/src/utils/mod.rs index 73abf6938a13..6e41aa2b2db0 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::TraceableError::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_json/src/lib.rs b/crates/rspack_plugin_json/src/lib.rs index 83479b630378..22ef255831b5 100644 --- a/crates/rspack_plugin_json/src/lib.rs +++ b/crates/rspack_plugin_json/src/lib.rs @@ -8,7 +8,7 @@ use rspack_core::{ }; use rspack_error::{ internal_error, DiagnosticKind, Error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray, - TraceableRspackError, + TraceableError, }; mod utils; @@ -58,8 +58,8 @@ impl ParserAndGenerator for JsonParserAndGenerator { } else { start_offset }; - Error::TraceableRspackError( - TraceableRspackError::from_file( + Error::InternalError( + TraceableError::from_file( resource_data.resource_path.to_string_lossy().to_string(), source.into_owned(), // one character offset @@ -68,7 +68,8 @@ impl ParserAndGenerator for JsonParserAndGenerator { "Json parsing error".to_string(), format!("Unexpected character {ch}"), ) - .with_kind(DiagnosticKind::Json), + .with_kind(DiagnosticKind::Json) + .into(), ) } ExceededDepthLimit | WrongType(_) | FailedUtf8Parsing => { @@ -77,8 +78,8 @@ impl ParserAndGenerator for JsonParserAndGenerator { UnexpectedEndOfJson => { // End offset of json file let offset = source.len(); - Error::TraceableRspackError( - TraceableRspackError::from_file( + Error::InternalError( + TraceableError::from_file( resource_data.resource_path.to_string_lossy().to_string(), source.into_owned(), offset, @@ -86,7 +87,8 @@ impl ParserAndGenerator for JsonParserAndGenerator { "Json parsing error".to_string(), format!("{e}"), ) - .with_kind(DiagnosticKind::Json), + .with_kind(DiagnosticKind::Json) + .into(), ) } } diff --git a/crates/rspack_plugin_swc_js_minimizer/src/minify.rs b/crates/rspack_plugin_swc_js_minimizer/src/minify.rs index aec0a91f66af..55b14896c639 100644 --- a/crates/rspack_plugin_swc_js_minimizer/src/minify.rs +++ b/crates/rspack_plugin_swc_js_minimizer/src/minify.rs @@ -7,7 +7,7 @@ use rspack_core::{ rspack_sources::{RawSource, SourceExt}, ModuleType, }; -use rspack_error::{internal_error, DiagnosticKind, Error, Result, TraceableRspackError}; +use rspack_error::{internal_error, DiagnosticKind, Error, Result, TraceableError}; use rspack_plugin_javascript::ast::parse_js; use rspack_plugin_javascript::ast::{print, SourceMapConfig}; use rspack_plugin_javascript::{ @@ -330,15 +330,16 @@ impl Emitter for RspackErrorEmitter { if let Some(source_file_and_byte_pos) = source_file_and_byte_pos { self .tx - .send(Error::TraceableRspackError( - TraceableRspackError::from_source_file( + .send(Error::InternalError( + TraceableError::from_source_file( &source_file_and_byte_pos.sf, source_file_and_byte_pos.pos.0 as usize, source_file_and_byte_pos.pos.0 as usize, self.title.to_string(), db.message(), ) - .with_kind(self.kind), + .with_kind(self.kind) + .into(), )) .expect("Sender should drop after emit called"); } else {