Skip to main content

rspack_error/
diagnostic.rs

1use rspack_cacheable::{
2  cacheable,
3  with::{AsOption, AsPreset},
4};
5use rspack_collections::Identifier;
6use rspack_location::DependencyLocation;
7use rspack_paths::Utf8PathBuf;
8
9use crate::{Result, displayer::Renderer, error::Error};
10
11#[cacheable]
12#[derive(Debug, Clone, Default)]
13pub struct Diagnostic {
14  pub error: Error,
15
16  // The following fields are only used to restore Diagnostic for Rspack.
17  // If the current Diagnostic originates from Rust, these fields will be None.
18  pub module_identifier: Option<Identifier>,
19  pub loc: Option<DependencyLocation>,
20  #[cacheable(with=AsOption<AsPreset>)]
21  pub file: Option<Utf8PathBuf>,
22  pub chunk: Option<u32>,
23}
24
25impl std::ops::Deref for Diagnostic {
26  type Target = Error;
27  fn deref(&self) -> &Self::Target {
28    &self.error
29  }
30}
31
32impl std::ops::DerefMut for Diagnostic {
33  fn deref_mut(&mut self) -> &mut Self::Target {
34    &mut self.error
35  }
36}
37
38impl From<Error> for Diagnostic {
39  fn from(value: Error) -> Self {
40    Self {
41      error: value,
42      ..Default::default()
43    }
44  }
45}
46
47impl Diagnostic {
48  pub fn warn(code: String, message: String) -> Self {
49    let mut error = Error::warning(message);
50    error.code = Some(code);
51    Self {
52      error,
53      ..Default::default()
54    }
55  }
56
57  pub fn error(code: String, message: String) -> Self {
58    let mut error = Error::error(message);
59    error.code = Some(code);
60    Self {
61      error,
62      ..Default::default()
63    }
64  }
65
66  pub fn render_report(&self, colored: bool) -> Result<String> {
67    let renderer = Renderer::new(colored);
68    renderer.render(self)
69  }
70}