thisctx 0.4.0

Easily create error with contexts
Documentation
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! A small crate works with [thiserror](https://crates.io/crates/thiserror) to
//! create errors with contexts, heavily inspired by
//! [snafu](https://crates.io/crates/snafu).
//!
//! # ✍️ Examples
//!
//! ```
//! # use std::path::{Path, PathBuf};
//! # use thisctx::WithContext;
//! # use thiserror::Error;
//! #[derive(Debug, Error, WithContext)]
//! pub enum Error {
//!     #[error("I/O failed at '{1}'")]
//!     Io(#[source] std::io::Error, PathBuf),
//!     #[error(transparent)]
//!     ParseInt(std::num::ParseIntError),
//! }
//!
//! fn read_file(path: &Path) -> Result<String, Error> {
//!     std::fs::read_to_string(path).context(Io(path))
//! }
//! ```
//!
//! # ⚙️ Attributes
//!
//! You can use the `#[thisctx]` attribute with the following options to customize
//! the expanded code:
//!
//! | Option       | Type            | Inherited | Container | Variant | Field |
//! | ------------ | --------------- | --------- | --------- | ------- | ----- |
//! | `attr`       | `TokenStream[]` | ✔         | ✔         | ✔       | ✔     |
//! | `generic`    | `bool`          | ✔         | ✔         | ✔       | ✔     |
//! | `into`       | `Type[]`        | ✔         | ✔         | ✔       |       |
//! | `module`     | `bool \| Ident` |           | ✔         |         |       |
//! | `skip`       | `Ident`         | ✔         | ✔         | ✔       |       |
//! | `suffix`     | `bool \| Ident` | ✔         | ✔         | ✔       |       |
//! | `unit`       | `bool`          | ✔         | ✔         | ✔       |       |
//! | `visibility` | `Visibility`    | ✔         | ✔         | ✔       | ✔     |
//!
//! The `#[source]` and `#[error]` attributes defined in `thiserror` will also be
//! checked to determine the source error type.
//!
//! ## Option arguments
//!
//! `#[thisctx]` supports two syntaxes for passing arguments to an option:
//!
//! - Put tokens directly in the parentheses, e.g. `#[thisctx(visibility(pub))]`
//! - Use a string literal, e.g. `#[thisctx(visibility = "pub")]`, this is useful in
//!   older versions of `rustc` that don't support arbitrary tokens in non-macro
//!   attributes.
//!
//! An option of type `T[]` can occur multiple times in the same node, while other
//! types will lead an error.
//!
//! ## Boolean options
//!
//! You can omit the `true` value in boolean options, e.g. `#[thisctx(skip)]` is
//! equal to `#[thisctx(skip(true))]`.
//!
//! Reversed boolean options starts with `no_` can also be used as a shortcut to
//! pass `false`, e.g. `#[thisctx(no_skip)]` is equal to `#[thisctx(skip(false))]`.
//!
//! ## Inherited options
//!
//! An inherited option uses the value of its parent node if no value is provided,
//! for example:
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(skip)]
//! enum Error {
//!     // This variant will be ignored since `skip=true` is inherited.
//!     Io(#[source] std::io::Error),
//!     // This variant will be processed.
//!     #[thisctx(no_skip)]
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! ```
//!
//! An option of type `T[]` will concatenate arguments from its ancestors instead of
//! overriding them.
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(attr(derive(Debug)))]
//! enum Error {
//!     #[thisctx(attr(derive(Clone, Copy)))]
//!     Io(#[source] std::io::Error),
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! ```
//!
//! Expanded example:
//!
//! ```
//! // The order of attributes (and other options) is guaranteed by the order of
//! // inheritance.
//! // Attributes from the child node.
//! #[derive(Clone, Copy)]
//! // Attributes from the parent node.
//! #[derive(Debug)]
//! struct Io;
//!
//! #[derive(Debug)]
//! struct ParseInt;
//! ```
//!
//! ## `source`
//!
//! If a field has the `#[source]` attribute or is named `source`, the type of this
//! field will be assigned to `IntoError::Source` and won't appear in the generated
//! context types.
//!
//! ```
//! # use std::path::PathBuf;
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! struct Error(#[source] std::io::Error, PathBuf);
//! ```
//!
//! Expanded example:
//!
//! ```
//! # use std::path::PathBuf;
//! # use thisctx::{IntoError, WithContext};
//! # struct Error(std::io::Error, PathBuf);
//! struct ErrorContext<T1 = PathBuf>(T1);
//!
//! impl<T1> IntoError<Error> for ErrorContext<T1>
//! where
//!     T1: Into<PathBuf>,
//! {
//!     type Source = std::io::Error;
//!
//!     fn into_error(self, source: Self::Source) -> Error {
//!         Error(source, self.0.into())
//!     }
//! }
//! ```
//!
//! ## `error`
//!
//! If a variant is transparent (which has `#[error(transparent)]`), the first field
//! (which should also be the only field) will be considered as the source field.
//!
//! ## `thisctx.attr`
//!
//! An option used to add extra attributes to a generated node.
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(attr(derive(Debug)))]
//! struct Error {
//!     reason: String,
//! }
//! ```
//!
//! Expanded example:
//!
//! ```
//! #[derive(Debug)]
//! struct ErrorContext<T1 = String> {
//!     reason: T1,
//! }
//! ```
//!
//! `thisctx` allows you to add some common attributes without `attr(...)`,
//! including:
//!
//! - `cfg`
//! - `cfg_attr`
//! - `derive`
//! - `doc`
//!
//! This means the above example can also be written as:
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(derive(Debug))]
//! struct Error {
//!     reason: String,
//! }
//! ```
//!
//! ## `thisctx.generic`
//!
//! An option to disable generics of a generated node.
//!
//! ```
//! # use std::path::PathBuf;
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! struct Error {
//!     reason: String,
//!     #[thisctx(no_generic)]
//!     path: PathBuf,
//! }
//! ```
//!
//! Expanded example:
//!
//! ```
//! # use std::path::PathBuf;
//! struct ErrorContext<T1 = String> {
//!     reason: T1,
//!     path: PathBuf,
//! }
//! ```
//!
//! The generics provide a convenient way to construct context types, for example:
//!
//! ```
//! # use std::path::PathBuf;
//! # use thisctx::{IntoError, WithContext};
//! # #[derive(WithContext)]
//! # struct Error {
//! #     reason: String,
//! #     #[thisctx(no_generic)]
//! #     path: PathBuf,
//! # }
//! let _: Error = ErrorContext {
//!     // You can use &str directly because String implements From<&str>,
//!     reason: "anyhow",
//!     // whereas without generics you have to convert the data to PathBuf manually.
//!     path: "/some/path".into(),
//! }.build();
//! ```
//!
//! ## `thisctx.into`
//!
//! An option for converting generated types to a remote error type.
//!
//! ```
//! # use thisctx::{IntoError, WithContext};
//! // Probably an error defined in another crate.
//! enum RemoteError {
//!     Custom(String),
//! }
//!
//! // From<T> is required by #[thisctx(into)]
//! impl From<MyError> for RemoteError {
//!     fn from(e: MyError) -> Self {
//!         Self::Custom(e.0)
//!     }
//! }
//!
//! #[derive(WithContext)]
//! #[thisctx(into(RemoteError))]
//! struct MyError(String);
//!
//! let _: MyError = MyErrorContext("anyhow").build();
//! // It's possible to construct a remote error from the local context type.
//! let _: RemoteError = MyErrorContext("anyhow").build();
//! ```
//!
//! ## `thisctx.module`
//!
//! This option allows you put all generated context types into a single module.
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(module(context))]
//! pub enum Error {
//!     Io(#[source] std::io::Error),
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! # fn main() {}
//! ```
//!
//! Expanded example:
//!
//! ```
//! pub mod context {
//!     pub struct Io;
//!     pub struct ParseInt;
//! }
//! ```
//!
//! > You can also set this option to `true` to use the snake case of the container
//! > name as the module name, e.g. `#[thisctx(module)]` on `enum MyError` is equal
//! > to `#[thisctx(module(my_error))]`.
//!
//! ## `thisctx.skip`
//!
//! This option is used to skip generating context types for the specified variant.
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! enum Error {
//!     #[thisctx(skip)]
//!     Io(#[source] std::io::Error),
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! ```
//!
//! Expanded example:
//!
//! ```
//! struct ParseInt;
//! ```
//!
//! ## `thisctx.suffix`
//!
//! An option to add a suffix to the names of the generated context types.
//!
//! By default, only `struct`s will be added the builtin suffix `Context` since the
//! generated type without a suffix will confict with the error type.
//!
//! ```
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(suffix(Error))]
//! enum Error {
//!     Io(#[source] std::io::Error),
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! ```
//!
//! Expanded example:
//!
//! ```
//! struct IoError;
//! struct ParseIntError;
//! ```
//!
//! > The value `true` means to use the default suffix `Context` and the value
//! > `false` will remove the suffix from the generated type.
//!
//! ## `thisctx.unit`
//!
//! In Rust, the parentheses are required to construct a tuple struct even if it's
//! empty. `thisctx` will convert an empty struct to a unit struct by default. This
//! allows you use the struct name to create a new context without having to add
//! parentheses each time and can be disabled by passing `#[thisctx(no_unit)]`.
//!
//! ```rust
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! enum Error {
//!     #[thisctx(no_unit)]
//!     Io(#[source] std::io::Error),
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! ```
//!
//! Expanded example:
//!
//! ```rust
//! struct IoError();
//! struct ParseIntError;
//! ```
//!
//! ## `thisctx.visibility`
//!
//! This option is used to change the visibility of the generated types and fields
//! and can be written in shorthand as `#[pub(...)]`.
//!
//! ```rust
//! # use thisctx::WithContext;
//! #[derive(WithContext)]
//! #[thisctx(pub(crate))]
//! pub enum Error {
//!     Io(#[source] std::io::Error),
//!     ParseInt(#[source] std::num::ParseIntError),
//! }
//! ```
//!
//! Expanded example:
//!
//! ```rust
//! pub(crate) struct IoError;
//! pub(crate) struct ParseIntError;
//! ```
//!
//! # 📝 Todo
//!
//! - [x] ~~Switch to Rust 2021.~~
//! - [x] MSRV v1.33
//! - [x] Use derive macro instead.
//! - [x] Add attributes to context types.
//! - [x] Support transparent error.
//! - [x] Support generics.
//! - [x] Simplify the derive implementation.
//! - [x] More documentation.
//! - [ ] More tests.
//!
//! # 🚩 Minimal suppoted Rust version
//!
//! All tests under `tests/*` passed with `rustc v1.33`, previous versions may not
//! compile.
#![no_std]

pub use thisctx_impl::WithContext;

#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct NoneSource;

pub trait IntoError<E>: Sized {
    type Source;

    fn into_error(self, source: Self::Source) -> E;

    #[inline]
    fn build(self) -> E
    where
        Self: IntoError<E, Source = NoneSource>,
    {
        self.into_error(NoneSource)
    }

    // TODO: use never type instead?
    #[inline]
    fn fail<T>(self) -> Result<T, E>
    where
        Self: IntoError<E, Source = NoneSource>,
    {
        Err(self.build())
    }
}

pub trait WithContext: Sized {
    type Ok;
    type Err;

    fn context_with<E, C>(self, f: impl FnOnce() -> C) -> Result<Self::Ok, E>
    where
        C: IntoError<E>,
        Self::Err: Into<C::Source>;

    #[inline]
    fn context<E, C>(self, context: C) -> Result<Self::Ok, E>
    where
        C: IntoError<E>,
        Self::Err: Into<C::Source>,
    {
        self.context_with(|| context)
    }
}

impl<T, Err> WithContext for Result<T, Err> {
    type Ok = T;
    type Err = Err;

    #[inline]
    fn context_with<E, C>(self, f: impl FnOnce() -> C) -> Result<T, E>
    where
        C: IntoError<E>,
        Err: Into<C::Source>,
    {
        self.map_err(|e| f().into_error(e.into()))
    }
}

impl<T> WithContext for Option<T> {
    type Ok = T;
    type Err = NoneSource;

    #[inline]
    fn context_with<E, C>(self, f: impl FnOnce() -> C) -> Result<T, E>
    where
        C: IntoError<E>,
        NoneSource: Into<C::Source>,
    {
        self.ok_or_else(|| f().into_error(NoneSource.into()))
    }
}