mynt 0.1.1

a refreshing error handling crate for proc macros
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#![doc = include_str!("../README.md")]
//!
//! # API
//!
//! The following are the utilities mynt provides to make error handling easier with proc-macros:
//!
//! ## Entry points
//!
//! Macros need to be wrapped in an entry point to use mynt's features (needed for quit + fallback support).
//!
//! - [`mynt!{}`](mynt): allows wrapping an inline/existing proc macros in lib.rs
//! - [`mynt_macro!(name => name_impl);`](mynt_macro): declares a function-like proc macro
//! - [`mynt_macro_attribute!(name => name_impl);`](mynt_macro_attribute): declares an attribute proc macro
//! - [`mynt_macro_derive!(name for Trait(attributes(attr))? => name_impl);`](mynt_macro_derive):
//! declares a derive proc macro
//!
//! ## Helpers
//!
//! Helpers make emitting diagnostics easy.
//! They can be called in two ways:
//! - `helper!(item);` for emitting a diagnostic from an item that implements [`Emittable`] (like strings or error types).
//! - `helper!(spans => message);` for emitting a diagnostic with a custom span and message.
//!
//! You can also call `helper!("message");` to use the call site span.
//!
//! - [`emit!()`]: Emit a diagnostic for a given [`Level`]
//! - [`help!()`]: Emit a help message (written to stderr on stable)
//! - [`note!()`]: Emit a note (written to stderr on stable)
//! - [`warn!()`]: Emit a warning (written to stderr on stable)
//! - [`error!()`]: Emit an error
//! - [`bail!()`]: Emit an error and return with the default value
//! - [`fatal!()`]: Emit an error and [`quit`]
//!
//! ### Assertions
//!
//! mynt provides equivalents to `assert_*!` macros that instead
//! call [`fatal!`] instead of [`panic!`] for cleaner error output.
//!
//! - [`mynt_assert!()`]: Ensures an expression is `true`
//! - [`mynt_assert_eq!()`]: Ensures two expressions are equal
//! - [`mynt_assert_ne!()`]: Ensures two expressions are not equal
//!
//! ### Low-level API
//!
//! mynt exposes some of its internals just in case.
//!
//! - [`Diagnostic`]: Manually write diagnostics
//! - [`Level`]: The level of diagnostic (Error/Warning/Note/Help)
//! - [`quit()`]: Quit the proc-macro and let mynt clean-up
//!
//! # Feature Flags
//!
//! - `default`: `proc-macro2`, `syn`
//! - `darling`: support for darling error conversion
//! - `nightly`: support for nightly Rust's `proc_macro_diagnostic` feature
//! - `proc-macro2`: support for proc-macro2 span conversion
//! - `syn`: support for syn error conversion
//! - `venial`: support for venial error conversion
//! - `yansi`: support for fallback (stable Rust) terminal coloring via yansi
//!
//! # Example
//!
//! This example (`/examples/attribute/src/lib.rs`) demonstrates the outer macro pattern,
//! a technique where we want to share information between invocations of macros
//! (like when we want to get information about items in a database schema),
//! which is not currently possible with macros (without risking determinism).
//!
//! Instead, we can wrap macros in an *outer* macro, which can then find those macros,
//! collect data from them, and then proceed with their implementations.
//!
//! This pattern shows how mynt can shine, by allowing inner macros to produce output,
//! even if other inner macros run into errors.
//!
//! ```
#![doc = include_str!("../example.rs")]
//! ```
//!
//! Check out `/examples` on the repository to see how this macro is used and other examples.

#![cfg_attr(feature = "nightly", feature(proc_macro_diagnostic))]

extern crate proc_macro;

#[cfg(not(feature = "nightly"))]
pub mod fallback;

/// Type alias to the available diagnostic struct.
#[cfg(feature = "nightly")]
pub type Diagnostic = proc_macro::Diagnostic;

/// Type alias to the available diagnostic struct.
#[cfg(not(feature = "nightly"))]
pub type Diagnostic = fallback::Diagnostic;

/// Type alias to the available diagnostic level enum.
#[cfg(feature = "nightly")]
pub type Level = proc_macro::Level;

/// Type alias to the available diagnostic level enum.
#[cfg(not(feature = "nightly"))]
pub type Level = fallback::Level;

/// Helper trait implemented by types that can be converted to a multispan.
pub trait ToSpans {
    fn to_spans(self) -> Vec<proc_macro::Span>;
}

impl ToSpans for proc_macro::Span {
    fn to_spans(self) -> Vec<proc_macro::Span> {
        vec![self]
    }
}

#[cfg(feature = "proc-macro2")]
impl ToSpans for proc_macro2::Span {
    fn to_spans(self) -> Vec<proc_macro::Span> {
        vec![self.unwrap()]
    }
}

/// Trait implemented by types that can be emitted through diagnostics.
pub trait Emittable {
    /// Emits a [`Diagnostic`].
    fn emit(level: Level, this: Self);
}

impl Emittable for &str {
    fn emit(level: Level, this: Self) {
        Diagnostic::spanned(proc_macro::Span::call_site(), level, this).emit();
    }
}

impl Emittable for String {
    fn emit(level: Level, this: Self) {
        Diagnostic::spanned(proc_macro::Span::call_site(), level, this).emit();
    }
}

#[cfg(feature = "syn")]
impl Emittable for syn::Error {
    fn emit(level: Level, this: Self) {
        for err in this.into_iter() {
            Diagnostic::spanned(err.span().unwrap(), level, err.to_string()).emit();
        }
    }
}

#[cfg(feature = "venial")]
impl Emittable for venial::Error {
    fn emit(level: Level, this: Self) {
        // venial doesn't provide a way to iterate over errors,
        // so this hack will suffice by filtering out string literals as messages
        emit_compile_error_tokens_as_diagnostics(level, this.to_compile_error().into());
    }
}

#[cfg(feature = "darling")]
impl Emittable for darling_core::error::Error {
    fn emit(level: Level, this: Self) {
        // if darling has diagnostics enabled, we need to let it handle emitting them
        // since there is no way to get the diagnostic level from darling directly
        emit_compile_error_tokens_as_diagnostics(level, this.write_errors().into());
        // we can't cfg(feature = "dep:darling_core/diagnostics"), but if we could,
        // we would be able to iterate over non-diagnostic errors directly
    }
}

/// Helper for emitting a diagnostic.
///
/// Has two forms (for macros based on this one, leave out `level`):
/// - `($level:expr, $item:expr)`: emit a diagnostic with [`Level`] `level` and [`Emittable`] `item`
/// - `($level:expr, $spans:expr => $message:expr)`:
/// emit a diagnostic with [`Level`] `level` at [`ToSpans`] `spans` and [`Into<ToString>`] `message`.
///
/// For error types that can't implement [`Emittable`] (due to orphan rules),
/// it is recommended to use the newtype pattern.
#[macro_export]
macro_rules! emit {
    ($level:expr, $item:expr) => {{
        $crate::Emittable::emit($level, $item);
    }};
    ($level:expr, $spans:expr => $message:expr) => {
        $crate::Diagnostic::spanned($crate::ToSpans::to_spans($spans), $level, $message).emit()
    };
    ($level:expr, $spans:expr => $($message:tt)*) => {
        $crate::Diagnostic::spanned($crate::ToSpans::to_spans($spans), $level, ::std::format!($($message)*)).emit()
    };
}

/// Helper for emitting a [`Level::Help`] diagnostic.
///
/// See [`emit!()`] for usage.
#[macro_export]
macro_rules! help {
    ($($input:tt)*) => ($crate::emit!($crate::Level::Help, $($input)*))
}

/// Helper for emitting a [`Level::Note`] diagnostic.
///
/// See [`emit!()`] for usage.
#[macro_export]
macro_rules! note {
    ($($input:tt)*) => ($crate::emit!($crate::Level::Note, $($input)*))
}

/// Helper for emitting a [`Level::Warning`] diagnostic.
///
/// See [`emit!()`] for usage.
#[macro_export]
macro_rules! warn {
    ($($input:tt)*) => ($crate::emit!($crate::Level::Warning, $($input)*))
}

/// Helper for emitting a [`Level::Error`] diagnostic.
///
/// See [`emit!()`] for usage.
#[macro_export]
macro_rules! error {
    ($($input:tt)*) => ($crate::emit!($crate::Level::Error, $($input)*))
}

/// Emit an error diagnostic and then exit the current function with the [`Default::default`] value.
///
/// See [`emit!()`] for usage.
#[macro_export]
macro_rules! bail {
    ($item:expr) => {{
        $crate::Emittable::emit($crate::Level::Error, $item);
        return ::core::default::Default::default();
    }};
    ($spans:expr => $message:expr) => {{
        $crate::Diagnostic::spanned(
            $crate::ToSpans::to_spans($spans),
            $crate::Level::Error,
            $message,
        )
        .emit();
        return ::core::default::Default::default();
    }};
}

/// Emit an error diagnostic and then [`quit`].
///
/// See [`emit!()`] for usage.
#[macro_export]
macro_rules! fatal {
    ($item:expr) => {{
        $crate::Emittable::emit($crate::Level::Error, $item);
        $crate::quit();
    }};
    ($spans:expr => $message:expr) => {{
        $crate::Diagnostic::spanned(
            $crate::ToSpans::to_spans($spans),
            $crate::Level::Error,
            $message,
        )
        .emit();
        $crate::quit();
    }};
}

/// Asserts that a boolean expression is `true` at runtime.
///
/// This will invoke the [`fatal!`] macro if the provided expression
/// cannot be evaluated to true at runtime.
///
/// # Custom Messages
/// Like [`std::assert!`], it has a second form, where a custom error message can
/// be provided with or without arguments for formatting. See [`std::fmt`]
/// for syntax for this form. Expressions used as format arguments will only
/// be evaluated if the assertion fails.
#[macro_export]
macro_rules! mynt_assert {
    ($cond:expr $(,)?) => {{
        if !($cond) {
            $crate::fatal!(::core::stringify!($cond));
        }
    }};
    ($cond:expr, $($arg:tt)+) => {{
        if !($cond) {
            $crate::fatal!(::std::format!($($arg:tt)+));
        }
    }};
}

/// Asserts that two expressions are equal to each other (using [`std::cmp::PartialEq`]).
///
/// Like [`mynt_assert!`], this macro has a second form, where a custom panic message can be provided.
#[macro_export]
macro_rules! mynt_assert_eq {
    ($left:expr, $right:expr $(,)?) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = $crate::AssertKind::Eq;
                    $crate::assert_failed(
                        kind,
                        &*left_val,
                        &*right_val,
                        ::core::option::Option::None
                    );
                }
            }
        }
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = $crate::AssertKind::Eq;
                    $crate::assert_failed(
                        kind,
                        &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(::core::format_args!($($arg)+))
                    );
                }
            }
        }
    };
}

/// Asserts that two expressions are not equal to each other (using [`std::cmp::PartialEq`]).
///
/// Like [`mynt_assert!`], this macro has a second form, where a custom panic message can be provided.
#[macro_export]
macro_rules! mynt_assert_ne {
    ($left:expr, $right:expr $(,)?) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val != *right_val) {
                    let kind = $crate::AssertKind::Ne;
                    $crate::assert_failed(
                        kind,
                        &*left_val,
                        &*right_val,
                        ::core::option::Option::None
                    );
                }
            }
        }
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val != *right_val) {
                    let kind = $crate::AssertKind::Ne;
                    $crate::assert_failed(
                        kind,
                        &*left_val,
                        &*right_val,
                        ::core::option::Option::Some(::core::format_args!($($arg)+))
                    );
                }
            }
        }
    };
}

#[derive(Debug)]
#[doc(hidden)]
pub enum AssertKind {
    Eq,
    Ne,
    Match, // TODO: maybe implement mynt_assert_matches!
}

#[doc(hidden)]
pub fn assert_failed(
    kind: AssertKind,
    left: &dyn core::fmt::Debug,
    right: &dyn core::fmt::Debug,
    args: Option<core::fmt::Arguments<'_>>,
) -> ! {
    let op = match kind {
        AssertKind::Eq => "==",
        AssertKind::Ne => "!=",
        AssertKind::Match => "matches",
    };

    match args {
        Some(args) => {
            Diagnostic::spanned(
                proc_macro::Span::call_site(),
                Level::Error,
                format!(
                    "assertion `left {op} right` failed: {args}\n  left: {left:?}\n right: {right:?}"
                ),
            )
            .emit();
            quit();
        }
        None => {
            Diagnostic::spanned(
                proc_macro::Span::call_site(),
                Level::Error,
                format!("assertion `left {op} right` failed:\n  left: {left:?}\n right: {right:?}"),
            )
            .emit();
            quit();
        }
    }
}

/// A marker struct for panics originating from mynt interfaces.
struct MyntPanicMarker;

/// Panics with a marker that allows mynt to safely emit any errors accumulated
/// before returning an empty token stream.
pub fn quit() -> ! {
    ::std::panic::panic_any(MyntPanicMarker);
}

// handles caught panics that originate from mynt
#[doc(hidden)]
pub fn quit_handler(err: Box<dyn std::any::Any + Send>) -> proc_macro::TokenStream {
    if err.downcast_ref::<MyntPanicMarker>().is_some() {
        proc_macro::TokenStream::new()
    } else {
        ::std::panic::resume_unwind(err)
    }
}

/// Extension trait for [`Result`].
pub trait MyntResultExt<T, E>: Sized {
    /// Returns the contained [`Ok`] value or [`quit`]s the proc-macro.
    ///
    /// Quitting will emit the error as a diagnostic.
    fn unwrap_or_quit(self) -> T
    where
        E: Emittable;

    /// Returns the contained [`Ok`] value or returns a [`compile_error!`] token stream.
    ///
    /// The token stream is parsed for string literals which are emitted as diagnostics.
    /// This is a fallback if [`MyntResultExt::unwrap_or_quit`] doesn't support
    /// an error type, but a `to_compile_error` method is available.
    fn unwrap_or_compile_error<F, R>(self, f: F) -> T
    where
        F: FnOnce(&E) -> R,
        R: Into<proc_macro::TokenStream>;
}

impl<T, E> MyntResultExt<T, E> for Result<T, E> {
    fn unwrap_or_quit(self) -> T
    where
        E: Emittable,
    {
        match self {
            Ok(val) => val,
            Err(err) => {
                Emittable::emit(Level::Error, err);
                quit();
            }
        }
    }

    fn unwrap_or_compile_error<F, R>(self, f: F) -> T
    where
        F: FnOnce(&E) -> R,
        R: Into<proc_macro::TokenStream>,
    {
        match self {
            Ok(val) => val,
            Err(err) => {
                let tokens: proc_macro::TokenStream = f(&err).into();
                emit_compile_error_tokens_as_diagnostics(Level::Error, tokens);
                std::panic::panic_any(MyntPanicMarker);
            }
        }
    }
}

fn emit_compile_error_tokens_as_diagnostics(level: Level, tokens: proc_macro::TokenStream) {
    fn handle_tt(level: Level, tt: proc_macro::TokenTree) {
        match tt {
            proc_macro::TokenTree::Group(group) => {
                group
                    .stream()
                    .into_iter()
                    .for_each(|tt| handle_tt(level, tt));
            }
            proc_macro::TokenTree::Literal(literal) => {
                Diagnostic::spanned(literal.span(), level, literal.to_string()).emit();
            }
            _ => (),
        }
    }

    tokens.into_iter().for_each(|tt| handle_tt(level, tt));
}

#[doc(hidden)]
pub fn enter_diagnostics() {
    #[cfg(not(feature = "nightly"))]
    fallback::enter_diagnostics();
}

#[doc(hidden)]
pub fn exit_diagnostics(tokens: &mut proc_macro::TokenStream) {
    #[cfg(not(feature = "nightly"))]
    fallback::exit_diagnostics(tokens);
}

#[doc(hidden)]
#[macro_export]
macro_rules! mynt_impl {
    ($($call:tt)*) => {
        {
            $crate::enter_diagnostics();
            let result = ::std::panic::catch_unwind(|| $($call)*);
            let mut tokens: ::proc_macro::TokenStream = match result {
                Ok(value) => value.into(),
                Err(err) => $crate::quit_handler(err),
            };
            $crate::exit_diagnostics(&mut tokens);
            tokens
        }
    };
}

/// General use entrypoint that wraps any proc-macro.
#[macro_export]
macro_rules! mynt {
    {
        $(#[$meta:meta])*
        $vis:vis fn $name:ident
        ($($arg_name:ident : $arg_type:ty),*)
        -> $ret:ty
        $body:block
    } => {
        $(#[$meta])*
        $vis fn $name($($arg_name: ::proc_macro::TokenStream),*) -> ::proc_macro::TokenStream {
            fn f($($arg_name: $arg_type),*) -> $ret $body
            $crate::mynt_impl!(f($($arg_name.into()),*))
        }
    };
}

/// Declares a function-like proc-macro entrypoint.
///
/// # Usage
///
/// Calling `mynt_macro!(name => name_impl);` will declare a new macro called `name`
/// which calls the implementation `name_impl`.
///
/// `name_impl` must have a signature compatible with
/// `fn(impl Into<TokenStream>) -> impl Into<TokenStream>`.
#[macro_export]
macro_rules! mynt_macro {
    ($name:ident => $f:ident) => {
        #[proc_macro]
        pub fn $name(input: ::proc_macro::TokenStream) -> ::proc_macro::TokenStream {
            $crate::mynt_impl!($f(input.into()))
        }
    };
}

/// Declares an attribute proc-macro entrypoint.
///
/// # Usage
///
/// Calling `mynt_macro_attribute!(name => name_impl);` will declare
/// a new attribute macro called `name` which calls the implementation `name_impl`.
///
/// `name_impl` must have the signature compatible with
/// `fn(impl Into<TokenStream>, impl Into<TokenStream>) -> impl Into<TokenStream>`.
#[macro_export]
macro_rules! mynt_macro_attribute {
    ($name:ident => $f:ident) => {
        #[proc_macro_attribute]
        pub fn $name(
            attr: ::proc_macro::TokenStream,
            input: ::proc_macro::TokenStream,
        ) -> ::proc_macro::TokenStream {
            $crate::mynt_impl!($f(attr.into(), input.into()))
        }
    };
}

/// Declares a derive proc-macro entrypoint.
///
/// # Usage
///
/// Calling `mynt_macro_derive!(name for Trait => name_impl);` will declare
/// a new derive macro called `name` which calls the implementation `name_impl`.
///
/// Helper attributes can also be declared by adding `(attributes(attrs))`
/// after the `Trait`.
///
/// `name_impl` must have the signature compatible with
/// `fn(impl Into<TokenStream>) -> impl Into<TokenStream>`.
#[macro_export]
macro_rules! mynt_macro_derive {
    ($name:ident for $trait:ident $((attributes($($attr:ident),*)))? => $f:ident) => {
        #[proc_macro_derive($trait $(, attributes($($attr),*))?)]
        pub fn $name(
            input: ::proc_macro::TokenStream,
        ) -> ::proc_macro::TokenStream {
            $crate::mynt_impl!($f(input.into()))
        }
    };
}