mirror of
https://github.com/hanzoai/swc.git
synced 2026-10-30 19:42:53 +00:00
# Description
SWC api `try_with_handler` only return anyhow!(msg) Err, it'a will lose many message about error stack, level ...,
To express more error message in swc, we can return `Vec<Diagnostic>` in `try_with_handler`;
try_with_handler_diagnostic return a `Result<Ret, Vec<Diagnostic>>`. Later user can using `diagnostic.code` to distinguish what kind error is.
- Added `miette` as a dependency for improved error handling and reporting.
- Updated diagnostic handling to utilize `miette` for pretty printing errors.
- Introduced a new `ThreadSafetyDiagnostics` to manage and store diagnostics.
- Refactored emitters to support the new diagnostic structure and ensure compatibility with `miette`.
- Enhanced error handling in various components to provide clearer and more informative error messages.
# BREAKING CHANGE:
The api `try_with_handler` would not return anyhow!(msg).
It's will return WrapperDiagnostics as it's Err. Then you can take
diagnostics from WrapperDiagnostics or get pretty string from it.
```diff
- pub fn try_with_handler<F, Ret>(cm: Lrc<SourceMap>, config: HandlerOpts, op:F) -> Result<Ret, anyhow::error>;
+ pub fn try_with_handler<F, Ret>(cm: Lrc<SourceMap>, config: HandlerOpts, op:F) -> Result<Ret, WrapperDiagnostics>;
```
```rust
/// A wrapper around a value that also contains a list of diagnostics.
/// It helps swc error system migrate to the new error reporting system.
pub struct WrapperDiagnostics {
diagnostics: Vec<SwcDignostic>,
....
}
impl WrapperDiagnostics {
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
pub fn to_pretty_error(&self) -> anyhow::Error {
let error_msg = self.to_pretty_string();
anyhow::anyhow!(error_msg)
}
pub fn to_pretty_string(&self) -> String {
....
}
}
```
### formatting
In SWC, the `Syntax Error` message formatting dependents anyhow.
```rust
// input: Foo {}
// https://play.swc.rs/?version=1.11.13&code=H4sIAAAAAAAAA3PLz1eorgUAR6TWygYAAAA%3D&config=H4sIAAAAAAAAA1WPSw7DIAwF9zkF8rrbdtE79BAWdSIifrKJVBTl7iUE0maH3xsz8jooBbNoeKq1PMsQkYX4nEsi2Sf8lARIOxTNJia49XaWvRrRCtVoOxpIyBOluiX3hoMNQajjLXPGmzH%2FC3VwkUnkCu4o%2BsnSVTc0JbjwXmrZDkk50qF%2FwA%2FqsvNjMPLqm4kXGrYvhlQioBQBAAA%3D
x Expected ';', '}' or <eof>
,-[input.js:1:1]
1 | Foo {}
: ^|^ ^
: `-- This is the expression part of an expression statement
`----
Caused by:
0: failed to process js file
1: Syntax Error
```
So if we return `Vec<Diagnostic>` instead of `anyhow:Error`, The output
formatting would have a litter breaking change.
```diff
x Expected ';', '}' or <eof>
,-[input.js:1:1]
1 | Foo {}
: ^|^ ^
: `-- This is the expression part of an expression statement
`----
- Caused by:
- 0: failed to process js file
- 1: Syntax Error
+ x Syntax Error
```
# Related issue:
- Closes https://github.com/swc-project/swc/issues/10192
---------
Co-authored-by: Donny/강동윤 <[email protected]>
80 lines
2.0 KiB
Rust
80 lines
2.0 KiB
Rust
use std::{
|
|
fmt,
|
|
io::{self, Write},
|
|
sync::{Arc, RwLock},
|
|
};
|
|
|
|
use swc_common::{
|
|
errors::{Emitter, Handler, HandlerFlags},
|
|
sync::Lrc,
|
|
SourceMap,
|
|
};
|
|
use swc_error_reporters::{GraphicalReportHandler, GraphicalTheme, ToPrettyDiagnostic};
|
|
|
|
use super::StdErr;
|
|
use crate::errors::{multi_emitter, stderr::stderr_emitter};
|
|
|
|
/// Creates a new handler for testing.
|
|
pub(crate) fn new_handler(cm: Lrc<SourceMap>, treat_err_as_bug: bool) -> (Handler, BufferedError) {
|
|
let buffer: BufferedError = Default::default();
|
|
|
|
let buffered_emitter = BufferedEmitter {
|
|
cm: cm.clone(),
|
|
report: GraphicalReportHandler::default().with_theme(GraphicalTheme::none()),
|
|
buffer: buffer.clone(),
|
|
};
|
|
|
|
let emitter = multi_emitter(Box::new(buffered_emitter), stderr_emitter(cm));
|
|
let handler = Handler::with_emitter_and_flags(
|
|
emitter,
|
|
HandlerFlags {
|
|
treat_err_as_bug,
|
|
..Default::default()
|
|
},
|
|
);
|
|
|
|
(handler, buffer)
|
|
}
|
|
|
|
pub struct BufferedEmitter {
|
|
cm: Lrc<SourceMap>,
|
|
report: GraphicalReportHandler,
|
|
buffer: BufferedError,
|
|
}
|
|
|
|
impl Emitter for BufferedEmitter {
|
|
fn emit(&mut self, db: &mut swc_common::errors::DiagnosticBuilder<'_>) {
|
|
let d = &**db;
|
|
let pretty_string = d.to_pretty_string(&self.cm, false, &self.report);
|
|
let _ = self.buffer.write(pretty_string.as_bytes()).unwrap();
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
pub(crate) struct BufferedError(Arc<RwLock<Vec<u8>>>);
|
|
|
|
impl Write for BufferedError {
|
|
fn write(&mut self, d: &[u8]) -> io::Result<usize> {
|
|
self.0.write().unwrap().write(d)
|
|
}
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
Ok(())
|
|
}
|
|
}
|
|
impl From<BufferedError> for StdErr {
|
|
fn from(buf: BufferedError) -> Self {
|
|
let s = buf.0.read().unwrap();
|
|
let s: String = String::from_utf8_lossy(&s).into();
|
|
|
|
s.into()
|
|
}
|
|
}
|
|
|
|
impl fmt::Write for BufferedError {
|
|
fn write_str(&mut self, s: &str) -> fmt::Result {
|
|
self.write(s.as_bytes()).map_err(|_| fmt::Error)?;
|
|
Ok(())
|
|
}
|
|
}
|