aboutsummaryrefslogtreecommitdiff
path: root/src/eyreish/macros.rs
blob: 938ac3212c5623d1c2196a9a38d42f866c693241 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/// Return early with an error.
///
/// This macro is equivalent to `return Err(From::from($err))`.
///
/// # Example
///
/// ```
/// # use miette::{bail, Result};
/// #
/// # fn has_permission(user: usize, resource: usize) -> bool {
/// #     true
/// # }
/// #
/// # fn main() -> Result<()> {
/// #     let user = 0;
/// #     let resource = 0;
/// #
/// if !has_permission(user, resource) {
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#"     bail!("permission denied for accessing {resource}");"#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#"     bail!("permission denied for accessing {}", resource);"#
)]
/// }
/// #     Ok(())
/// # }
/// ```
///
/// ```
/// # use miette::{bail, Result};
/// # use thiserror::Error;
/// #
/// # const MAX_DEPTH: usize = 1;
/// #
/// #[derive(Error, Debug)]
/// enum ScienceError {
///     #[error("recursion limit exceeded")]
///     RecursionLimitExceeded,
///     # #[error("...")]
///     # More = (stringify! {
///     ...
///     # }, 1).1,
/// }
///
/// # fn main() -> Result<()> {
/// #     let depth = 0;
/// #     let err: &'static dyn std::error::Error = &ScienceError::RecursionLimitExceeded;
/// #
/// if depth > MAX_DEPTH {
///     bail!(ScienceError::RecursionLimitExceeded);
/// }
/// #     Ok(())
/// # }
/// ```
///
/// ```
/// use miette::{bail, Result, Severity};
///
/// fn divide(x: f64, y: f64) -> Result<f64> {
///     if y.abs() < 1e-3 {
///         bail!(
///             severity = Severity::Warning,
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#"             "dividing by value ({y}) close to 0""#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#"             "dividing by value ({}) close to 0", y"#
)]
///         );
///     }
///     Ok(x / y)
/// }
/// ```
#[macro_export]
macro_rules! bail {
    ($($key:ident = $value:expr,)* $fmt:literal $($arg:tt)*) => {
        return $crate::private::Err(
            $crate::miette!($($key = $value,)* $fmt $($arg)*)
        );
    };
    ($err:expr $(,)?) => {
        return $crate::private::Err($crate::miette!($err));
    };
}

/// Return early with an error if a condition is not satisfied.
///
/// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`.
///
/// Analogously to `assert!`, `ensure!` takes a condition and exits the function
/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
/// rather than panicking.
///
/// # Example
///
/// ```
/// # use miette::{ensure, Result};
/// #
/// # fn main() -> Result<()> {
/// #     let user = 0;
/// #
/// ensure!(user == 0, "only user 0 is allowed");
/// #     Ok(())
/// # }
/// ```
///
/// ```
/// # use miette::{ensure, Result};
/// # use thiserror::Error;
/// #
/// # const MAX_DEPTH: usize = 1;
/// #
/// #[derive(Error, Debug)]
/// enum ScienceError {
///     #[error("recursion limit exceeded")]
///     RecursionLimitExceeded,
///     # #[error("...")]
///     # More = (stringify! {
///     ...
///     # }, 1).1,
/// }
///
/// # fn main() -> Result<()> {
/// #     let depth = 0;
/// #
/// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
/// #     Ok(())
/// # }
/// ```
///
/// ```
/// use miette::{ensure, Result, Severity};
///
/// fn divide(x: f64, y: f64) -> Result<f64> {
///     ensure!(
///         y.abs() >= 1e-3,
///         severity = Severity::Warning,
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#"             "dividing by value ({y}) close to 0""#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#"             "dividing by value ({}) close to 0", y"#
)]
///     );
///     Ok(x / y)
/// }
/// ```
#[macro_export]
macro_rules! ensure {
    ($cond:expr, $($key:ident = $value:expr,)* $fmt:literal $($arg:tt)*) => {
        if !$cond {
            return $crate::private::Err(
                $crate::miette!($($key = $value,)* $fmt $($arg)*)
            );
        }
    };
    ($cond:expr, $err:expr $(,)?) => {
        if !$cond {
            return $crate::private::Err($crate::miette!($err));
        }
    };
}

/// Construct an ad-hoc [`Report`].
///
/// # Examples
///
/// With string literal and interpolation:
/// ```
/// # use miette::miette;
/// let x = 1;
/// let y = 2;
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#"let report = miette!("{x} + {} = {z}", y, z = x + y);"#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#"let report = miette!("{} + {} = {z}", x, y, z = x + y);"#
)]
///
/// assert_eq!(report.to_string().as_str(), "1 + 2 = 3");
///
/// let z = x + y;
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#"let report = miette!("{x} + {y} = {z}");"#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#"let report = miette!("{} + {} = {}", x, y, z);"#
)]
/// assert_eq!(report.to_string().as_str(), "1 + 2 = 3");
/// ```
///
/// With [`diagnostic!`]-like arguments:
/// ```
/// use miette::{miette, LabeledSpan, Severity};
///
/// let source = "(2 + 2".to_string();
/// let report = miette!(
///     // 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",
///     // 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 {
    ($($key:ident = $value:expr,)* $fmt:literal $($arg:tt)*) => {
        $crate::Report::from(
            $crate::diagnostic!($($key = $value,)* $fmt $($arg)*)
        )
    };
    ($err:expr $(,)?) => ({
        use $crate::private::kind::*;
        let error = $err;
        (&error).miette_kind().new(error)
    });
}

/// 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",
///     // 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;
///
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#" let diag = diagnostic!("{x} + {} = {z}", y, z = x + y);"#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#" let diag = diagnostic!("{} + {} = {z}", x, y, z = x + y);"#
)]
/// assert_eq!(diag.message, "1 + 2 = 3");
///
/// let z = x + y;
#[cfg_attr(
    not(feature = "no-format-args-capture"),
    doc = r#"let diag = diagnostic!("{x} + {y} = {z}");"#
)]
#[cfg_attr(
    feature = "no-format-args-capture",
    doc = r#"let diag = diagnostic!("{} + {} = {}", x, y, z);"#
)]
/// assert_eq!(diag.message, "1 + 2 = 3");
/// ```
#[macro_export]
macro_rules! diagnostic {
    ($fmt:literal $($arg:tt)*) => {{
        $crate::MietteDiagnostic::new(format!($fmt $($arg)*))
    }};
    ($($key:ident = $value:expr,)+ $fmt:literal $($arg:tt)*) => {{
        let mut diag = $crate::MietteDiagnostic::new(format!($fmt $($arg)*));
        $(diag.$key = Some($value.into());)*
        diag
    }};
}