Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 12 additions & 18 deletions crates/rspack_core/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ impl std::error::Error for ModuleBuildError {
}

impl std::fmt::Display for ModuleBuildError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Module build failed:")
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}

impl miette::Diagnostic for ModuleBuildError {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
Some(Box::new("ModuleBuildError"))
Some(Box::new("Module build failed"))
Copy link
Contributor

@h-a-n-a h-a-n-a Apr 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostic code should be PascalCase. This is intended to work as WebpackError.name in webpack.

}
fn severity(&self) -> Option<miette::Severity> {
self.0.severity()
Expand Down Expand Up @@ -83,15 +83,18 @@ impl miette::Diagnostic for ModuleBuildError {
/// This does NOT aligned with webpack as webpack does not have parse warning.
/// However, rspack may create warning during parsing stage, taking CSS as an example.
#[derive(Debug, Error)]
#[error("{title}")]
pub struct ModuleParseError {
message: String,
title: &'static str,
help: String,
#[source]
source: Box<dyn Diagnostic + Send + Sync>,
}

impl std::fmt::Display for ModuleParseError {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}

impl miette::Diagnostic for ModuleParseError {
// Passthrough the severity
fn severity(&self) -> Option<miette::Severity> {
Expand All @@ -101,8 +104,8 @@ impl miette::Diagnostic for ModuleParseError {
fn code<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
match self.severity().unwrap_or(miette::Severity::Error) {
miette::Severity::Advice => unreachable!("miette::Severity::Advice should not be used"),
miette::Severity::Warning => Some(Box::new("ModuleParseWarning")),
miette::Severity::Error => Some(Box::new("ModuleParseError")),
miette::Severity::Warning => Some(Box::new("Module parse warning")),
miette::Severity::Error => Some(Box::new("Module parse failed")),
}
}

Expand All @@ -120,9 +123,7 @@ impl miette::Diagnostic for ModuleParseError {

impl ModuleParseError {
pub fn new(source: Box<dyn Diagnostic + Send + Sync>, loaders: &[BoxLoader]) -> Self {
let message = source.to_string();
let mut help = String::new();
let mut title = "Module parse failed:";
if source.severity().unwrap_or(miette::Severity::Error) >= miette::Severity::Error {
if loaders.is_empty() {
help = format!("{help}\nYou may need an appropriate loader to handle this file type.");
Expand All @@ -136,15 +137,8 @@ impl ModuleParseError {
.join("");
help = format!("{help}\nFile was processed with these loaders:{s}\nYou may need an additional loader to handle the result of these loaders.");
}
} else {
title = "Module parse warning:"
}
Self {
message,
title,
help,
source,
}
Self { help, source }
}
}

Expand Down
15 changes: 9 additions & 6 deletions crates/rspack_error/src/graphical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,15 @@ impl GraphicalReportHandler {
.initial_indent(&initial_indent)
.subsequent_indent(&rest_indent);

writeln!(f, "{}", textwrap::fill(&diagnostic.to_string(), opts))?;
let cause = format!(
"{}{}",
diagnostic
.code()
.map(|c| format!("{}: ", c.style(severity_style)))
.unwrap_or_default(),
diagnostic
);
writeln!(f, "{}", textwrap::fill(&cause, opts))?;

if !self.with_cause_chain {
return Ok(());
Expand Down Expand Up @@ -303,11 +311,6 @@ impl GraphicalReportHandler {
if let Some(related) = diagnostic.related() {
writeln!(f)?;
for rel in related {
match rel.severity() {
Some(Severity::Error) | None => write!(f, "Error: ")?,
Some(Severity::Warning) => write!(f, "Warning: ")?,
Some(Severity::Advice) => write!(f, "Advice: ")?,
};
self.render_header(f, rel)?;
self.render_causes(f, rel)?;
let src = rel.source_code().or(parent_src);
Expand Down
7 changes: 2 additions & 5 deletions crates/rspack_plugin_circular_dependencies/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,8 @@ impl CircularDependencyRspackPlugin {
.collect();

compilation.push_diagnostic(diagnostic_factory(
"Circular Dependency".to_string(),
format!(
"Circular dependency detected:\n {}",
cycle_without_root.iter().join(" -> ")
),
"CircularDependency".to_string(),
format!("detected:\n {}", cycle_without_root.iter().join(" -> ")),
));
Ok(())
}
Expand Down
19 changes: 8 additions & 11 deletions crates/rspack_plugin_copy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,7 @@ impl CopyRspackPlugin {
diagnostics
.lock()
.expect("failed to obtain lock of `diagnostics`")
.push(Diagnostic::error(
"Run copy to fn error".into(),
e.to_string(),
));
.push(Diagnostic::error("CopyPlugin".into(), e.to_string()));
"".to_string()
}
};
Expand Down Expand Up @@ -526,7 +523,7 @@ impl CopyRspackPlugin {
.lock()
.expect("failed to obtain lock of `diagnostics`")
.push(Diagnostic::error(
"CopyRspackPlugin Error".into(),
"CopyPlugin".into(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both Diagnostic::warn and Diagnostic::error are legacy APIs. So the title is not the same as which in the TraceableError. I prefer to align this part with TraceableError.

format!("unable to locate '{glob_query}' glob"),
));
}
Expand Down Expand Up @@ -562,7 +559,7 @@ impl CopyRspackPlugin {
.lock()
.expect("failed to obtain lock of `diagnostics`")
.push(Diagnostic::error(
"CopyRspackPlugin Error".into(),
"CopyPlugin".into(),
format!("unable to locate '{glob_query}' glob"),
));
return Ok(None);
Expand Down Expand Up @@ -594,7 +591,10 @@ impl CopyRspackPlugin {
diagnostics
.lock()
.expect("failed to obtain lock of `diagnostics`")
.push(Diagnostic::error("Glob Error".into(), e.msg.to_string()));
.push(Diagnostic::error(
"CopyPlugin".into(),
format!("glob error, {}", e.msg),
));

Ok(None)
}
Expand Down Expand Up @@ -821,10 +821,7 @@ async fn handle_transform(
diagnostics
.lock()
.expect("failed to obtain lock of `diagnostics`")
.push(Diagnostic::error(
"Run copy transform fn error".into(),
e.to_string(),
));
.push(Diagnostic::error("CopyPlugin".into(), e.to_string()));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ impl CssPlugin {
.expect("should have module");

Diagnostic::warn(
"Conflicting order".into(),
"CssPlugin".into(),
format!(
"chunk {}\nConflicting order between {} and {}",
chunk.name().unwrap_or(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ impl ConsumeSharedPlugin {
.await
.map_err(|_e| {
add_diagnostic(Diagnostic::error(
"ModuleNotFoundError".into(),
"ConsumeShared".into(),
format!("resolving fallback for shared module {request}"),
))
})
Expand Down Expand Up @@ -472,7 +472,7 @@ async fn additional_tree_runtime_requirements(
#[async_trait]
impl Plugin for ConsumeSharedPlugin {
fn name(&self) -> &'static str {
"rspack.ConsumeSharedPlugin"
"CosumeShared"
}

fn apply(&self, ctx: PluginContext<&mut ApplyContext>, _options: &CompilerOptions) -> Result<()> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl ProvideSharedPlugin {
resource_data: &ResourceData,
mut add_diagnostic: impl FnMut(Diagnostic),
) {
let title = "rspack.ProvideSharedPlugin";
let title = "ProvideShared";
let error_header = "No version specified and unable to automatically determine one.";
if let Some(version) = version {
self.resolved_provide_map.write().await.insert(
Expand Down
4 changes: 2 additions & 2 deletions crates/rspack_plugin_size_limits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl SizeLimitsPlugin {
.map(|&(name, size)| format!("\n {} ({})", name, format_size(size)))
.collect::<Vec<String>>()
.join("");
let title = String::from("assets over size limit warning");
let title = String::from("SizeLimits");
let message = format!("asset size limit: The following asset(s) exceed the recommended size limit ({}). This can impact web performance.\nAssets:{}", format_size(limit), asset_list);

Self::add_diagnostic(hints, title, message, diagnostics);
Expand Down Expand Up @@ -119,7 +119,7 @@ impl SizeLimitsPlugin {
})
.collect::<Vec<_>>()
.join("");
let title = String::from("entrypoints over size limit warning");
let title = String::from("SizeLimits");
let message = format!(
"entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit ({}). This can impact web performance.\nEntrypoints:{}",
format_size(limit),
Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_plugin_sri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ async fn handle_compilation(
) {
compilation.push_diagnostic(Diagnostic::error(
"SubresourceIntegrity".to_string(),
"Subresource integrity is not applied to async chunks because the \"output.crossOriginLoading\" option is not set.".to_string(),
"SRI is not applied to async chunks because the \"output.crossOriginLoading\" option is not set.".to_string(),
));
}

Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_plugin_warn_sensitive_module/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async fn seal(&self, compilation: &mut Compilation) -> Result<()> {
let mut case_modules = set.iter().copied().collect::<Vec<_>>();
case_modules.sort_unstable();
diagnostics.push(Diagnostic::warn(
"Sensitive Modules Warn".to_string(),
"WarnCaseSensitive".to_string(),
self.create_sensitive_modules_warning(case_modules, &compilation.get_module_graph()),
));
}
Expand Down
19 changes: 7 additions & 12 deletions crates/rspack_plugin_wasm/src/parser_and_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,9 @@ impl ParserAndGenerator for AsyncWasmParserAndGenerator {
for export in s {
match export {
Ok(export) => exports.push(export.name.to_string()),
Err(err) => diagnostic.push(Diagnostic::error(
"Wasm Export Parse Error".into(),
err.to_string(),
)),
Err(err) => {
diagnostic.push(Diagnostic::error("WasmParser".into(), err.to_string()))
}
};
}
}
Expand All @@ -76,20 +75,16 @@ impl ParserAndGenerator for AsyncWasmParserAndGenerator {
ty,
)));
}
Err(err) => diagnostic.push(Diagnostic::error(
"Wasm Import Parse Error".into(),
err.to_string(),
)),
Err(err) => {
diagnostic.push(Diagnostic::error("WasmParser".into(), err.to_string()))
}
}
}
}
_ => {}
},
Err(err) => {
diagnostic.push(Diagnostic::error(
"Wasm Parse Error".into(),
err.to_string(),
));
diagnostic.push(Diagnostic::error("WasmParser".into(), err.to_string()));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,11 +333,11 @@ cacheable modules xx KiB
./d.js 22 bytes [built] [code generated]
./e.js 22 bytes [built] [code generated]

ERROR in × asset size limit: The following asset(s) exceed the recommended size limit (xx KiB). This can impact web performance.Assets:
ERROR in × SizeLimits: asset size limit: The following asset(s) exceed the recommended size limit (xx KiB). This can impact web performance.Assets:
│ main.js (xx KiB)


ERROR in × entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (xx KiB). This can impact web performance.Entrypoints:
ERROR in × SizeLimits: entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (xx KiB). This can impact web performance.Entrypoints:
│ main (xx KiB)
│ main.js

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,11 +333,11 @@ cacheable modules xx KiB
./d.js 22 bytes [built] [code generated]
./e.js 22 bytes [built] [code generated]

ERROR in × asset size limit: The following asset(s) exceed the recommended size limit (xx KiB). This can impact web performance.Assets:
ERROR in × SizeLimits: asset size limit: The following asset(s) exceed the recommended size limit (xx KiB). This can impact web performance.Assets:
│ main.js (xx KiB)


ERROR in × entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (xx KiB). This can impact web performance.Entrypoints:
ERROR in × SizeLimits: entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (xx KiB). This can impact web performance.Entrypoints:
│ main (xx KiB)
│ main.js

Expand Down
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
WARNING in (./basic.js!)
ModuleWarning: `React` is not defined
⚠ `React` is not defined

WARNING in ./lib.js (./basic.js!./lib.js)
ModuleWarning: `React` is not defined
⚠ `React` is not defined

ERROR in (./basic.js!)
× ModuleError: `React` is not defined
× `React` is not defined

ERROR in ./lib.js (./basic.js!./lib.js)
× ModuleError: `React` is not defined
× `React` is not defined

ERROR in ./some-file.js
(./with-file.js!) 1:1-4
× ModuleError: `React` is not defined
× `React` is not defined
╭────
1 │ <div></div>
· ───
╰────

ERROR in ./some-file.js
./lib.js (./with-file.js!./lib.js) 1:1-4
× ModuleError: `React` is not defined
× `React` is not defined
╭────
1 │ <div></div>
· ───
╰────

ERROR in (./with-help.js!) 1:1-4
× ModuleError: `React` is not defined
× `React` is not defined
╭────
1 │ <div></div>
· ───
╰────
help: try to import `React`

ERROR in (./with-location.js!) 1:1-4
× ModuleError: `React` is not defined
× `React` is not defined
╭────
1 │ <div></div>
· ───
╰────

ERROR in (./with-multi-byte-char.js!) 1:0-13
× ModuleError: Multi-byte character error
× Multi-byte character error
╭────
1 │ 👯‍♀️👯‍♀️👯‍♀️👯‍♀️
· ───
Expand All @@ -61,14 +61,14 @@ ERROR in (./with-multi-byte-char.js!)
│ at xxx

ERROR in (./with-multiple-line.js!) 1:0-2:4
× ModuleError: Multiple line error
× Multiple line error
╭─[1:0]
1 │ ╭─▶ ~~~~~
2 │ ╰─▶ ~~~~~
╰────

ERROR in (./with-multiple-line.js!) 1:0-2:4
× ModuleError: Multiple line error
× Multiple line error
╭─[1:0]
1 │ ╭─▶ ~~~~~
2 │ ├─▶ ~~~~~
Expand All @@ -88,7 +88,7 @@ ERROR in (./with-multiple-line.js!)
│ at xxx

ERROR in (./with-multiple-line.js!) 3:4
× ModuleError: Multiple line snippet
× Multiple line snippet
╭─[3:4]
1 │ ~~~~~
2 │ ~~~~~
Expand Down
Loading
Loading