Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dynamic diagnostic #262

Merged
merged 30 commits into from
May 13, 2023
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
09d7d15
Remove dot
gavrilikhin-d May 5, 2023
e6d2eed
Add skeleton
gavrilikhin-d May 5, 2023
ab20069
DynamicDiagnostic -> MietteDiagnostic
gavrilikhin-d May 6, 2023
01b34a4
Make `Severity::Error` to be default severity
gavrilikhin-d May 6, 2023
61d43f8
Add severity field
gavrilikhin-d May 6, 2023
53b21ea
Add help field
gavrilikhin-d May 6, 2023
a1f602c
Add url field
gavrilikhin-d May 6, 2023
c6e977b
Add labels field
gavrilikhin-d May 6, 2023
a3ee52a
Add convenience function to `LabeledSpan`
gavrilikhin-d May 6, 2023
8aaba99
Use convenience functions in examples
gavrilikhin-d May 6, 2023
021eb01
Adjust `miette!` a little bit
gavrilikhin-d May 6, 2023
b9a892f
Use `Option<Severity>`
gavrilikhin-d May 6, 2023
c2d793e
labels: `Option<Vec<_>>`
gavrilikhin-d May 6, 2023
bcf18f8
Fully implement support for `MietteDiagnostic`-like arguments in `mie…
gavrilikhin-d May 6, 2023
287ffc5
Add `miette_diagnostic!`
gavrilikhin-d May 6, 2023
4f0bc3e
Add `ensure!` support
gavrilikhin-d May 6, 2023
52e2dcb
Add `bail!` support
gavrilikhin-d May 6, 2023
7c4dd12
Add docs
gavrilikhin-d May 6, 2023
0e5512a
Add dot
gavrilikhin-d May 7, 2023
e35a63a
description -> message
gavrilikhin-d May 7, 2023
4148552
`miette_diagnostic!` -> `diagnostic!`
gavrilikhin-d May 7, 2023
b658720
Add `and_label(s)`
gavrilikhin-d May 7, 2023
cb5a1d3
Implement interpolation
gavrilikhin-d May 7, 2023
55f41a6
Remove literal case from ensure
gavrilikhin-d May 7, 2023
3e62212
Fix macro
gavrilikhin-d May 12, 2023
5e67953
Use `mut self` in builder functions
gavrilikhin-d May 12, 2023
5c94dd0
Sync README.md
gavrilikhin-d May 12, 2023
253a0f8
Update .tpl
gavrilikhin-d May 12, 2023
4520d66
Fix clippy
gavrilikhin-d May 13, 2023
7fb4cb2
Add and use `no-format-args-capture` flag
gavrilikhin-d May 13, 2023
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
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

## Introduction

Thank you so much for your interest in contributing!. All types of contributions are encouraged and valued. See the [table of contents](#toc) for different ways to help and details about how this project handles them!📝
Thank you so much for your interest in contributing! All types of contributions are encouraged and valued. See the [table of contents](#toc) for different ways to help and details about how this project handles them!📝

Please make sure to read the relevant section before making your contribution! It will make it a lot easier for us maintainers to make the most of it and smooth out the experience for all involved. 💚

Expand Down
146 changes: 118 additions & 28 deletions src/eyreish/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
/// # let resource = 0;
/// #
/// if !has_permission(user, resource) {
/// bail!("permission denied for accessing {}", resource);
/// bail!("permission denied for accessing {resource}");
/// }
/// # Ok(())
/// # }
Expand Down Expand Up @@ -48,16 +48,32 @@
/// # Ok(())
/// # }
/// ```
///
/// ```
/// use miette::{bail, Result, Severity};
///
/// fn divide(x: f64, y: f64) -> Result<f64> {
/// if y.abs() < 1e-3 {
/// bail!(
/// severity = Severity::Warning;
/// "dividing by value ({y}) close to 0"
/// );
/// }
/// Ok(x / y)
/// }
/// ```
#[macro_export]
macro_rules! bail {
($msg:literal $(,)?) => {
return $crate::private::Err($crate::miette!($msg));
};
($err:expr $(,)?) => {
return $crate::private::Err($crate::miette!($err));
};
($fmt:expr, $($arg:tt)*) => {
return $crate::private::Err($crate::miette!($fmt, $($arg)*));
($($key:ident = $value:expr),+; $($fmt:tt)+) => {
return $crate::private::Err(
$crate::miette!($($key = $value),+; $($fmt)+)
);
};
($($fmt:tt)+) => {
return $crate::private::Err($crate::miette!($($fmt)+));
};
}

Expand Down Expand Up @@ -105,6 +121,19 @@ macro_rules! bail {
/// # Ok(())
/// # }
/// ```
///
/// ```
/// use miette::{ensure, Result, Severity};
///
/// fn divide(x: f64, y: f64) -> Result<f64> {
/// ensure!(
/// y.abs() >= 1e-3,
/// severity = Severity::Warning;
/// "dividing by value ({y}) close to 0"
/// );
/// Ok(x / y)
/// }
/// ```
#[macro_export]
macro_rules! ensure {
($cond:expr, $msg:literal $(,)?) => {
Expand All @@ -117,52 +146,113 @@ macro_rules! ensure {
return $crate::private::Err($crate::miette!($err));
}
};
($cond:expr, $($key:ident = $value:expr),+; $($fmt:tt)+) => {
if !$cond {
return $crate::private::Err(
$crate::miette!($($key = $value),+; $($fmt)+)
);
}
};
($cond:expr, $fmt:expr, $($arg:tt)*) => {
if !$cond {
return $crate::private::Err($crate::miette!($fmt, $($arg)*));
}
};
}

/// 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
///
/// # Example
/// With string literal and interpolation:
/// ```
/// # use miette::miette;
/// let x = 1;
/// let y = 2;
/// let report = miette!("{x} + {} = {z}", y, z = x + y);
/// assert_eq!(report.to_string().as_str(), "1 + 2 = 3");
///
/// let report = miette!("{x} + {y} = {x + y}");
/// assert_eq!(report.to_string().as_str(), "1 + 2 = 3");
/// ```
/// # type V = ();
/// #
/// use miette::{miette, Result};
///
/// fn lookup(key: &str) -> Result<V> {
/// if key.len() != 16 {
/// return Err(miette!("key length must be 16 characters, got {:?}", key));
/// }
/// With [`diagnostic!`]-like arguments:
/// ```
/// use miette::{miette, LabeledSpan, Severity};
///
/// // ...
/// # Ok(())
/// }
/// let source = "(2 + 2".to_string();
/// let report = miette!(
gavrilikhin-d marked this conversation as resolved.
Show resolved Hide resolved
/// // 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"; // <- semicolon separates fields from message
///
/// // Rest of the arguments are passed to `format!`
/// // to form diagnostic message
/// "expected closing ')'"
/// )
/// .with_source_code(source);
/// ```
///
/// ## `anyhow`/`eyre` Users
///
/// You can just replace `use`s of the `anyhow!`/`eyre!` macros with `miette!`.
#[macro_export]
macro_rules! miette {
($msg:literal $(,)?) => {
// Handle $:literal as a special case to make cargo-expanded code more
// concise in the common case.
$crate::private::new_adhoc($msg)
};
($err:expr $(,)?) => ({
use $crate::private::kind::*;
let error = $err;
(&error).miette_kind().new(error)
});
($fmt:expr, $($arg:tt)*) => {
$crate::private::new_adhoc(format!($fmt, $($arg)*))
($($key:ident = $value:expr),+; $($fmt:tt)+) => {
$crate::Report::from(
$crate::diagnostic!($($key = $value),+; $($fmt)+)
)
};
($($fmt:tt)+) => {
gavrilikhin-d marked this conversation as resolved.
Show resolved Hide resolved
$crate::private::new_adhoc(format!($($fmt)+))
};
}

/// Construct a [`MietteDiagnostic`] in more user-friendly way.
///
/// # Examples
/// ```
/// use miette::{diagnostic, LabeledSpan, Severity};
///
/// let source = "(2 + 2".to_string();
/// let diag = diagnostic!(
/// // 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"; // <- semicolon separates fields from message
///
/// // Rest of the arguments are passed to `format!`
/// // to form diagnostic message
/// "expected closing ')'",
/// );
/// ```
/// Diagnostic without any fields:
/// ```
/// # use miette::diagnostic;
/// let x = 1;
/// let y = 2;
///
/// let diag = diagnostic!("{x} + {} = {z}", y, z = x + y);
/// assert_eq!(diag.message, "1 + 2 = 3");
/// ```
#[macro_export]
macro_rules! diagnostic {
($($key:ident = $value:expr),+; $($fmt:tt)+) => {{
let mut diag = $crate::MietteDiagnostic::new(format!($($fmt)+));
$(diag.$key = Some($value.into());)*
diag
}};
($($fmt:tt)+) => {{
$crate::MietteDiagnostic::new(format!($($fmt)+))
}};
}
27 changes: 26 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
//! - [... multiple related errors](#-multiple-related-errors)
//! - [... delayed source code](#-delayed-source-code)
//! - [... handler options](#-handler-options)
//! - [... dynamic diagnostics](#-dynamic-diagnostics)
//! - [Acknowledgements](#acknowledgements)
//! - [License](#license)
//!
Expand Down Expand Up @@ -249,7 +250,7 @@
//! To construct your own simple adhoc error use the [miette!] macro:
//! ```rust
//! // my_app/lib/my_internal_file.rs
//! use miette::{IntoDiagnostic, Result, WrapErr, miette};
//! use miette::{miette, IntoDiagnostic, Result, WrapErr};
gavrilikhin-d marked this conversation as resolved.
Show resolved Hide resolved
//! use semver::Version;
//!
//! pub fn some_tool() -> Result<Version> {
Expand Down Expand Up @@ -590,6 +591,28 @@
//! See the docs for [`MietteHandlerOpts`] for more details on what you can
//! customize!
//!
//! ### ... dynamic diagnostics
//!
//! If you...
//! - ...don't know all the possible errors upfront
//! - ...need to serialize/deserialize errors
//! then you may want to use [`miette!`], [`diagnostic!`] macros or
//! [`MietteDiagnostic`] directly to create diagnostic on the fly.
//!
//! ```rs
//! # use miette::{miette, LabeledSpan, Report};
//!
//! let source = "2 + 2 * 2 = 8".to_string();
//! let report = miette!(
//! "Wrong answer",
//! labels = vec[
//! LabeledSpan::at(12..13, "this should be 6"),
//! ],
//! help = "'*' has greater precedence than '+'"
//! ).with_source_code(source);
//! println!("{:?}", report)
//! ```
//!
//! ## Acknowledgements
//!
//! `miette` was not developed in a void. It owes enormous credit to various
Expand Down Expand Up @@ -624,6 +647,7 @@ pub use eyreish::*;
#[cfg(feature = "fancy-no-backtrace")]
pub use handler::*;
pub use handlers::*;
pub use miette_diagnostic::*;
pub use named_source::*;
#[cfg(feature = "fancy")]
pub use panic::*;
Expand All @@ -638,6 +662,7 @@ mod handler;
mod handlers;
#[doc(hidden)]
pub mod macro_helpers;
mod miette_diagnostic;
mod named_source;
#[cfg(feature = "fancy")]
mod panic;
Expand Down
Loading