Fully implement support for `MietteDiagnostic`-like arguments in `miette!`

This commit is contained in:
Gavrilikhin Daniil 2023-05-06 22:35:53 +08:00
parent c2d793e578
commit bcf18f8151
1 changed files with 23 additions and 14 deletions

View File

@ -124,13 +124,11 @@ macro_rules! ensure {
}; };
} }
/// Construct an ad-hoc error from a string. /// Construct an ad-hoc [`Report`].
///
/// This evaluates to an `Error`. It can take either just a string, or a format
/// string with arguments. It also can take any custom type which implements
/// `Debug` and `Display`.
/// ///
/// # Examples /// # Examples
///
/// With string literal and interpolation:
/// ``` /// ```
/// # type V = (); /// # type V = ();
/// # /// #
@ -145,10 +143,22 @@ macro_rules! ensure {
/// # Ok(()) /// # Ok(())
/// } /// }
/// ``` /// ```
/// ```
/// use miette::miette;
/// ///
/// let err = miette!("expected '('", code = "expected::lparen"); /// With [`MietteDiagnostic`]-like arguments:
/// ```
/// use miette::{miette, LabeledSpan, Severity};
///
/// let source = "(2 + 2".to_string();
/// let report = miette!(
/// "expected closing ')'",
/// // Those fields are optional
/// severity = Severity::Error,
/// code = "expected::rparen",
/// help = "always close your parens",
/// labels = vec![LabeledSpan::at_offset(6, "here")],
/// url = "https://example.com"
/// )
/// .with_source_code(source);
/// ``` /// ```
/// ///
/// ## `anyhow`/`eyre` Users /// ## `anyhow`/`eyre` Users
@ -166,12 +176,11 @@ macro_rules! miette {
let error = $err; let error = $err;
(&error).miette_kind().new(error) (&error).miette_kind().new(error)
}); });
($msg:literal, $(code = $code:literal)? ) => { ($fmt:expr $(, $key:ident = $value:expr)* $(,)?) => {{
$crate::Report::from( let mut diag = $crate::MietteDiagnostic::new(format!("{}", $fmt));
$crate::MietteDiagnostic::new($msg) $(diag.$key = Some($value.into());)*
$(.with_code($code))? $crate::Report::from(diag)
) }};
};
($fmt:expr, $($arg:tt)*) => { ($fmt:expr, $($arg:tt)*) => {
$crate::private::new_adhoc(format!($fmt, $($arg)*)) $crate::private::new_adhoc(format!($fmt, $($arg)*))
}; };