Skip to content

Commit

Permalink
refactor: error and diagnostics
Browse files Browse the repository at this point in the history
  • Loading branch information
h-a-n-a committed Dec 8, 2023
1 parent 4f3bf02 commit 8deb971
Show file tree
Hide file tree
Showing 9 changed files with 137 additions and 39 deletions.
81 changes: 76 additions & 5 deletions Cargo.lock

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

12 changes: 6 additions & 6 deletions crates/rspack_core/src/tree_shaking/optimizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,10 +1067,10 @@ impl<'a> CodeSizeOptimizer<'a> {
})
.collect::<Vec<_>>();
error_message += &join_string_component(module_identifier_list);
errors.push(Error::InternalError(InternalError {
errors.push(Error::InternalError(InternalError::new(
error_message,
severity: Severity::Warn,
}));
Severity::Warn,
)));
ret[0].1.clone()
}
};
Expand Down Expand Up @@ -1101,10 +1101,10 @@ impl<'a> CodeSizeOptimizer<'a> {
.normal_module_source_path_by_identifier(&star_symbol.src());
if let Some(module_path) = module_path {
let error_message = format!("Can't get analyze result of {module_path}");
errors.push(Error::InternalError(InternalError {
errors.push(Error::InternalError(InternalError::new(
error_message,
severity: Severity::Warn,
}));
Severity::Warn,
)));
}
}
return;
Expand Down
2 changes: 2 additions & 0 deletions crates/rspack_error/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ version = "0.1.0"
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"

[dev-dependencies]
insta = { workspace = true }
Expand Down
13 changes: 11 additions & 2 deletions crates/rspack_error/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ pub enum Severity {
Warn,
}

impl From<Severity> for miette::Severity {
fn from(value: Severity) -> Self {
match value {
Severity::Error => miette::Severity::Error,
Severity::Warn => miette::Severity::Warning,
}
}
}

impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
Expand Down Expand Up @@ -87,11 +96,11 @@ impl From<Error> for Vec<Diagnostic> {
let severity = err.severity();
let diagnostic = match err {
Error::InternalError(err) => Diagnostic {
message: err.error_message,
message: err.error_message().to_string(),
source_info: None,
start: 0,
end: 0,
severity: err.severity,
severity: err.severity(),
..Default::default()
},
Error::Napi {
Expand Down
39 changes: 27 additions & 12 deletions crates/rspack_error/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,48 @@
use std::{fmt, io, path::Path};

use miette::MietteDiagnostic;
use rspack_util::swc::normalize_custom_filename;
use swc_core::common::SourceFile;

use crate::{internal_error, Severity};

#[derive(Debug, Default)]
pub struct InternalError {
pub error_message: String,
pub severity: Severity,
}
#[derive(Debug)]
pub struct InternalError(miette::Report);

impl InternalError {
pub fn new(error_message: String, severity: Severity) -> Self {
Self {
error_message,
severity,
Self(miette::Report::new(
MietteDiagnostic::new(error_message.clone()).with_severity(severity.into()),
))
}

fn cast_to_miette(&self) -> &MietteDiagnostic {
match self.0.downcast_ref::<MietteDiagnostic>() {
Some(e) => e,
None => unreachable!(),
}
}

pub fn with_severity(mut self, severity: Severity) -> Self {
self.severity = severity;
self
pub fn error_message(&self) -> &str {
match self.0.downcast_ref::<MietteDiagnostic>() {
Some(e) => &e.message,
None => unreachable!(),
}
}

pub fn severity(&self) -> Severity {
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,
}
}
}

impl fmt::Display for InternalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}[internal]: {}", self.severity, self.error_message)
writeln!(f, "{}[internal]: {}", self.severity(), self.error_message())
}
}

Expand Down
4 changes: 4 additions & 0 deletions crates/rspack_error/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ pub mod emitter;

mod macros;

pub use miette;
pub use thiserror;

pub type Result<T> = std::result::Result<T, Error>;

/// A helper struct for change logic from
Expand Down Expand Up @@ -81,6 +84,7 @@ impl<T: Sized + std::fmt::Debug> IntoTWithDiagnosticArray for T {
pub mod __private {
pub use core::result::Result::Err;

pub use crate::diagnostic::Severity;
pub use crate::error::{Error, InternalError};
pub use crate::internal_error;
}
9 changes: 3 additions & 6 deletions crates/rspack_error/src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
#[macro_export]
macro_rules! internal_error {
(@base $expr:expr) => {
$crate::__private::Error::InternalError({
$crate::__private::InternalError {
error_message: $expr,
..Default::default()
}
})
$crate::__private::Error::InternalError(
$crate::__private::InternalError::new($expr, $crate::__private::Severity::Error)
)
};
($str:literal $(,)?) => {{
let err = format!($str);
Expand Down
8 changes: 4 additions & 4 deletions crates/rspack_loader_sass/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,16 +473,16 @@ impl Loader<LoaderRunnerContext> for SassLoader {
let sass_options = self.get_sass_options(loader_context, content.try_into_string()?, logger);
let result = Sass::new(&self.options.__exe_path)
.map_err(|e| {
rspack_error::Error::InternalError(InternalError {
severity: Severity::Error,
error_message: format!(
rspack_error::Error::InternalError(InternalError::new(
format!(
"{}: The dart-sass-embedded path is {}, your OS is {}, your Arch is {}",
e.message(),
&self.options.__exe_path.display(),
get_os(),
get_arch(),
),
})
Severity::Error,
))
})?
.render(sass_options)
.map_err(sass_exception_to_error)?;
Expand Down
8 changes: 4 additions & 4 deletions crates/rspack_plugin_ensure_chunk_conditions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ impl Plugin for EnsureChunkConditionsPlugin {
}
}
if chunk_group.is_initial() {
return Err(Error::InternalError(rspack_error::InternalError {
error_message: format!("Cannot fulfil chunk condition of {}", module_id),
severity: Default::default(),
}));
return Err(Error::InternalError(rspack_error::InternalError::new(
format!("Cannot fulfil chunk condition of {}", module_id),
Default::default(),
)));
}
let parent_chunks = chunk_group.parents_iterable();

Expand Down

0 comments on commit 8deb971

Please sign in to comment.