proc_macro2_diagnostic 0.5.0

Use `Diagnostic` compiler messages from proc_macro2 code with Result-like syntax.
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
#![cfg_attr(all(test, unstable_assert_matches), feature(assert_matches))]
#![cfg_attr(unstable_never_type, feature(never_type))]
#![cfg_attr(unstable_proc_macro_diagnostic, feature(proc_macro_diagnostic))]
#![cfg_attr(unstable_try_trait_v2, feature(try_trait_v2))]
#![cfg_attr(unstable_try_trait_v2_residual, feature(try_trait_v2_residual))]
#![doc = include_str!("../README.md")]

use std::fmt::{Debug, Display};

extern crate proc_macro;

use proc_macro::TokenStream as TokenStream1;
use proc_macro2::Span;

#[cfg(has_try_trait_v2)]
use crate::DiagnosticResult_::{Error, Ok as Ok_, Warning};

/// Prelude for easy `*`` imports: `use proc_macro2_diagnostic::prelude::*`
pub mod prelude {
    pub use super::AsDiagnostic;
    pub use super::DiagnosticKind;
    pub use super::DiagnosticResult;
    pub use super::DiagnosticStream;
    pub use super::{Ok, error, error_spanned, warn_spanned};
}

/// A convenience type which is designed to be returned from a proc_macro2-based macro
/// implementation.
///
/// ### Usage
/// 1. Shorten your proc_macro to `my_proc_macro2_impl(input.into()).to_tokens()`
/// 2. Return a DiagnosticStream from `my_proc_macro2_impl(input: proc_macro2::Tokenstream) -> DiagnosticStream`
/// 3. Use `Ok()`, `error` or `warn_spanned` within the function; return a `DiagnosticResult<_>`
///    from any supporting functions and handle it with `?`
///
/// All errors & warnings will be properly emitted by the compiler and nicely formatted.
pub type DiagnosticStream = DiagnosticResult<proc_macro2::TokenStream>;

#[derive(Clone, Debug)]
#[must_use = "this `DiagnosticResult` may be an error or a warning, which should be emitted"]
/// Result-like type which can represent a valid return value, an error or a warning accompanying
/// a valid return value. Warnings will be emitted upon `?`, allowing your code to continue with
/// the valid value. Errors will short-circuit upon `?` and be emitted upon final conversion to a
/// [proc_macro::TokenStream]
///
/// ### Usage
/// 1. Create a DiagnosticResult via `Ok()`, `error` or `warn_spanned`.
/// 2. Treat the DiagnosticResult as you would any other Result type and unpack it with `?` at a
///    suitable point in your code.
///
/// ### Stable / Nightly
/// On stable this will be replaced by a type alias which provides limited ergonomics for `Warning`s.
#[cfg(has_try_trait_v2)]
pub struct DiagnosticResult<T> {
    inner: DiagnosticResult_<T>,
}

#[cfg(not(has_try_trait_v2))]
/// This is a stable interface which provides limited ergonomics for `Warnings`
///
/// # WARNING
/// **DO NOT** expand this type alias, or your code will not compile on nightly, and will break at
/// some point in the future when try_trait_v2 is stabilised.
pub type DiagnosticResult<T> = Result<T, Diagnostic>;

#[derive(Clone, Debug)]
/// The type of top-level message contained in the DiagnosticResult
pub enum DiagnosticResultKind {
    Ok,
    Warning,
    Error,
}

pub trait DiagnosticKind {
    /// The type of top-level message
    fn kind(&self) -> DiagnosticResultKind;
    fn is_warning(&self) -> bool;
    fn is_error(&self) -> bool;
}

impl<T> DiagnosticKind for DiagnosticResult<T> {
    fn kind(&self) -> DiagnosticResultKind {
        #[cfg(has_try_trait_v2)]
        match self.inner {
            DiagnosticResult_::Ok(_) => DiagnosticResultKind::Ok,
            DiagnosticResult_::Warning(_, _) => DiagnosticResultKind::Warning,
            DiagnosticResult_::Error(_) => DiagnosticResultKind::Error,
        }
        #[cfg(not(has_try_trait_v2))]
        match self {
            Result::Ok(_) => DiagnosticResultKind::Ok,
            Result::Err(_) => DiagnosticResultKind::Error,
        }
    }

    fn is_warning(&self) -> bool {
        #[cfg(has_try_trait_v2)]
        {
            matches!(&self.kind(), DiagnosticResultKind::Warning)
        }
        #[cfg(not(has_try_trait_v2))]
        {
            // Warnings cannot be carried alongside values without try_trait_v2
            false
        }
    }

    fn is_error(&self) -> bool {
        matches!(&self.kind(), DiagnosticResultKind::Error)
    }
}

#[derive(Clone, Debug)]
/// Indirection via hidden inner to ensure invariant:
///   - Warning/Error must hold correct kind of Diagnostic
#[cfg(has_try_trait_v2)]
enum DiagnosticResult_<T> {
    Ok(T),
    Warning(T, Diagnostic),
    Error(Diagnostic),
}

/// Create an `Ok` result.
#[expect(non_snake_case, reason = "same feel as a Result type alias")]
pub fn Ok<T>(val: T) -> DiagnosticResult<T> {
    #[cfg(has_try_trait_v2)]
    {
        DiagnosticResult { inner: Ok_(val) }
    }
    #[cfg(not(has_try_trait_v2))]
    {
        Result::Ok(val)
    }
}

/// Create an error **spanning the macro call_site**
///
/// The message can be anything that implements `ToString` (incl. everything `Display`),
/// this means you can use format_args!() to avoid intermediate allocations.
pub fn error<T, MSG: ToString>(message: MSG) -> DiagnosticResult<T> {
    let diagnostic = Diagnostic::new(Level::Error, Span::call_site(), message);
    #[cfg(has_try_trait_v2)]
    {
        DiagnosticResult {
            inner: Error(diagnostic),
        }
    }
    #[cfg(not(has_try_trait_v2))]
    {
        Err(diagnostic)
    }
}

/// Create an error at the given `Span`s.
///
/// The message can be anything that implements `ToString` (incl. everything `Display`),
/// this means you can use format_args!() to avoid intermediate allocations.
///
/// A note will be added to the error when emitted, which highlights the original call site,
/// unless you add one manually.
pub fn error_spanned<T, MSG: ToString, SPN: MultiSpan>(
    span: SPN,
    message: MSG,
) -> DiagnosticResult<T> {
    let diagnostic = Diagnostic::new(Level::Error, span, message);
    #[cfg(has_try_trait_v2)]
    {
        DiagnosticResult {
            inner: Error(diagnostic),
        }
    }
    #[cfg(not(has_try_trait_v2))]
    {
        Err(diagnostic)
    }
}

/// Create a warning which will emit a message at the given `Span`s and deconstruct
/// to a valid value via `?`.
///
/// The message can be anything that implements `ToString` (incl. everything `Display`),
/// this means you can use format_args!() to avoid intermediate allocations.
///
/// A note will be added to the warning when emitted, which highlights the original call site,
/// unless you add one manually.
///
/// # Stable / Nightly
/// - Where try_trait_v2 is not available `Warnings` will be emitted immediately. See the readme
///   for more information
///
/// # Considerations for testing, etc.
/// - If code used outside a proc_macro context attempts to emit a Warning this will cause a
///   runtime failure. Be careful when constructing Warnings in code which will be subject to
///   unit tests or used in other contexts, e.g. in a build script.
pub fn warn_spanned<T, MSG: ToString, SPN: MultiSpan>(
    value: T,
    #[allow(
        unused_variables,
        reason = "warnings ignored if try trait not available"
    )]
    span: SPN,
    #[allow(
        unused_variables,
        reason = "warnings ignored if try trait not available"
    )]
    message: MSG,
) -> DiagnosticResult<T> {
    let warning = Diagnostic::new(Level::Warning, span, message);
    #[cfg(has_try_trait_v2)]
    {
        DiagnosticResult {
            inner: Warning(value, warning),
        }
    }
    #[cfg(not(has_try_trait_v2))]
    {
        warning.emit();
        Result::Ok(value)
    }
}

/// Provides methods to generate a diagnostic in "failure" case. This is a bit like
/// `Option::ok_or()` but returns a `DiagnosticResult` and can be implemented on
/// additional types.
pub trait ToDiagnostic<T> {
    /// Wrap the contained `T` in a `DiagnosticResult<T>` or create an error, spanning
    /// the call site with the given `message`
    fn or_error<MSG: ToString>(self, message: MSG) -> DiagnosticResult<T>;
    /// Wrap the contained `T` in a `DiagnosticResult<T>` or create an error at the
    /// given `span` with the given `message`
    fn or_error_spanned<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T>;
    /// Wrap the contained `T` in a `DiagnosticResult<T>` or create a warning, at the
    /// given `span` with the given `message` and containing the default value for `T`
    ///     
    ///
    /// A note will be added to the warning when emitted, which highlights the original call site,
    /// unless you add one manually.
    ///
    /// # Stable / Nightly
    /// - Where try_trait_v2 is not available `Warnings` will be emitted immediately. See the readme
    ///   for more information
    ///
    /// # Considerations for testing, etc.
    /// - If code used outside a proc_macro context attempts to emit a Warning this will cause a
    ///   runtime failure. Be careful when contructing Warnings in code which will be subject to
    ///   unit tests or used in other contexts, e.g. in a build script.
    fn or_warn_spanned_with_default<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T>
    where
        T: Default;
}

impl<T> ToDiagnostic<T> for Option<T> {
    fn or_error<MSG: ToString>(self, message: MSG) -> DiagnosticResult<T> {
        self.or_error_spanned(Span::call_site(), message)
    }

    fn or_error_spanned<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T> {
        match self {
            Some(val) => Ok(val),
            None => error_spanned(span, message),
        }
    }

    fn or_warn_spanned_with_default<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T>
    where
        T: Default,
    {
        match self {
            Some(val) => Ok(val),
            None => warn_spanned(Default::default(), span, message),
        }
    }
}

pub trait AsDiagnostic<T> {
    /// Add a `Help` message to an existing _error_ or _warning_ at one or more `Span`s.
    ///
    /// The message can be anything that implements `ToString` (incl. everything `Display`),
    /// this means you can use format_args!() to avoid intermediate allocations.
    fn add_help<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T>;

    /// Add a `Note` to an existing _error_ or _warning_ at one or more `Span`s.
    ///
    /// The message can be anything that implements `ToString` (incl. everything `Display`),
    /// this means you can use format_args!() to avoid intermediate allocations.
    fn add_note<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T>;
}

/// Converts `Err` to `Error`.
impl<T, E> AsDiagnostic<T> for Result<T, E>
where
    Diagnostic: From<E>,
{
    fn add_help<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T> {
        match self {
            Result::Ok(val) => Ok(val),
            Result::Err(e) => {
                let mut diagnostic = Diagnostic::from(e);
                diagnostic.add_help(span, message);
                #[cfg(not(has_try_trait_v2))]
                {
                    Err(diagnostic)
                }
                #[cfg(has_try_trait_v2)]
                {
                    DiagnosticResult {
                        inner: Error(diagnostic),
                    }
                }
            }
        }
    }

    fn add_note<MSG: ToString, SPN: MultiSpan>(
        self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T> {
        match self {
            Result::Ok(val) => Ok(val),
            Result::Err(e) => {
                let mut diagnostic = Diagnostic::from(e);
                diagnostic.add_note(span, message);
                #[cfg(not(has_try_trait_v2))]
                {
                    Err(diagnostic)
                }
                #[cfg(has_try_trait_v2)]
                {
                    DiagnosticResult {
                        inner: Error(diagnostic),
                    }
                }
            }
        }
    }
}

#[cfg(has_try_trait_v2)]
impl<T> AsDiagnostic<T> for DiagnosticResult<T> {
    fn add_help<MSG: ToString, SPN: MultiSpan>(
        mut self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T> {
        match self.inner {
            Ok_(_) => self,
            Warning(_, ref mut diagnostic) | Error(ref mut diagnostic) => {
                diagnostic.add_help(span, message);
                self
            }
        }
    }

    fn add_note<MSG: ToString, SPN: MultiSpan>(
        mut self,
        span: SPN,
        message: MSG,
    ) -> DiagnosticResult<T> {
        match self.inner {
            Ok_(_) => self,
            Warning(_, ref mut diagnostic) | Error(ref mut diagnostic) => {
                diagnostic.add_note(span, message);
                self
            }
        }
    }
}

#[cfg(has_try_trait_v2)]
// TODO: use traits from try_v2
impl<T> DiagnosticResult<T> {
    pub fn is_ok(&self) -> bool {
        matches!(&self.kind(), DiagnosticResultKind::Ok)
    }

    /// Return the Ok result or panic.
    pub fn unwrap(self) -> T
    where
        T: Debug,
    {
        match self.inner {
            Ok_(t) => t,
            Warning(val, warning) => panic!(
                "Called unwrap on value {:?} with accompanying warning: {:?}",
                val, warning
            ),
            Error(error) => panic!("Called unwrap on an error: {:?}", error),
        }
    }
}

#[derive(Debug, Clone)]
/// The internal Diagnostic stored within DiagnosticResult.
/// Not (currently) designed for direct usage.
///
/// 1:1 structure to match [proc_macro::Diagnostic]
pub struct Diagnostic {
    level: Level,
    message: String,
    spans: Vec<Span>,
    children: Vec<Diagnostic>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// 1:1 match for [proc_macro::Level].
pub enum Level {
    Error,
    Warning,
    Note,
    Help,
}

impl Display for Level {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Level::Error => write!(f, "error"),
            Level::Warning => write!(f, "warning"),
            Level::Note => write!(f, "note"),
            Level::Help => write!(f, "help"),
        }
    }
}

impl Diagnostic {
    fn new<MSG: ToString, SPN: MultiSpan>(level: Level, span: SPN, message: MSG) -> Self {
        Self {
            level,
            message: message.to_string(),
            spans: span.into_spans(),
            children: vec![],
        }
    }

    fn push(&mut self, child: Diagnostic) {
        self.children.push(child);
    }

    fn add_child<MSG: ToString, SPN: MultiSpan>(&mut self, level: Level, span: SPN, message: MSG) {
        self.children.push(Diagnostic::new(level, span, message));
    }

    fn add_help<MSG: ToString, SPN: MultiSpan>(&mut self, span: SPN, message: MSG) {
        self.add_child(Level::Help, span, message);
    }

    fn add_note<MSG: ToString, SPN: MultiSpan>(&mut self, span: SPN, message: MSG) {
        self.add_child(Level::Note, span, message);
    }

    /// Does any message _exactly_ span the call_site (not just across it)?
    fn spans_call_site(&self) -> bool {
        let call_site = Span::call_site();
        let cs_file = call_site.local_file();
        let cs_start = call_site.start();
        let cs_end = call_site.end();
        let is_call_site = |span: &Span| {
            span.local_file() == cs_file && span.start() == cs_start && span.end() == cs_end
        };

        self.spans.iter().any(is_call_site) || self.children.iter().any(Diagnostic::spans_call_site)
    }
}

impl From<syn::Error> for Diagnostic {
    fn from(error: syn::Error) -> Self {
        let mut diagnostic = Diagnostic::new(Level::Error, error.span(), error.to_string());
        for err in error.into_iter().skip(1) {
            diagnostic.push(err.into());
        }
        diagnostic
    }
}

/// Functions for the conversion to the proc_macro world.
impl Diagnostic {
    /// Convert to a [`proc_macro::Diagnostic`] (or [`syn::Error`] if
    /// [`proc_macro::Diagnostic`] is not available) and then emit.
    ///
    /// Returns a [proc_macro::TokenStream] which *should be used*. On toolchains without
    /// the experiment Diagnostic API, this will contain a compiler error, on toolchains
    /// with the experimental API it will be empty.
    pub fn emit(mut self) -> TokenStream1 {
        if !self.spans_call_site() {
            self.add_note(
                Span::call_site(),
                format!(
                    "this {} originates from the macro invocation here",
                    self.level
                ),
            );
        };
        #[cfg(has_proc_macro_diagnostic)]
        {
            let spans = self.as_spans();
            let mut pm_diagnostic =
                proc_macro::Diagnostic::spanned(spans, self.level.into(), self.message);
            for child in self.children {
                pm_diagnostic = child.add_to_parent(pm_diagnostic);
            }
            pm_diagnostic.emit();
            TokenStream1::new()
        }
        #[cfg(not(has_proc_macro_diagnostic))]
        {
            self.into_syn_err().into_compile_error().into()
        }
    }

    #[cfg(not(has_proc_macro_diagnostic))]
    fn into_syn_err(self) -> syn::Error {
        // take first span as all functions needed to join are nightly only
        let span = self.spans.into_iter().next().expect("at least one span");
        // new syn err
        let message = if matches!(self.level, Level::Error) {
            self.message
        } else {
            format!("{}: {}", self.level, self.message)
        };
        let mut err = syn::Error::new(span, message);
        for child in self.children {
            err.combine(child.into_syn_err());
        }
        err
    }

    /// Add this [Diagnostic] as the child of a [proc_macro::Diagnostic].
    /// Consumes both and returns a new [proc_macro::Diagnostic].
    #[cfg(has_proc_macro_diagnostic)]
    fn add_to_parent(self, parent: proc_macro::Diagnostic) -> proc_macro::Diagnostic {
        let msg = self.message.clone();
        match self.level {
            Level::Error => parent.span_error(self.as_spans(), msg),
            Level::Warning => parent.span_warning(self.as_spans(), msg),
            Level::Note => parent.span_note(self.as_spans(), msg),
            Level::Help => parent.span_help(self.as_spans(), msg),
        }
    }

    /// Get and convert the spans to use in a new [proc_macro::Diagnostic].
    #[cfg(has_proc_macro_diagnostic)]
    fn as_spans(&self) -> Vec<proc_macro::Span> {
        self.spans.iter().map(|span| span.unwrap()).collect()
    }
}

#[cfg(has_proc_macro_diagnostic)]
impl From<Level> for proc_macro::Level {
    fn from(level: Level) -> Self {
        match level {
            Level::Error => Self::Error,
            Level::Help => Self::Help,
            Level::Note => Self::Note,
            Level::Warning => Self::Warning,
        }
    }
}

/// A helper trait for APIs that accept one or more `Span`s.
///
/// This mirrors the behavior of [proc_macro::diagnostic::MultiSpan] and allows
/// callers to pass a `Span`, `Vec<Span>`, or `&[Span]` to supported APIs.
pub trait MultiSpan {
    /// Consume `self` and convert into an owned `Vec<Span>`.
    fn into_spans(self) -> Vec<Span>;
}

impl MultiSpan for Span {
    fn into_spans(self) -> Vec<Span> {
        vec![self]
    }
}

/// WARNING: Only first Span will be used if not has proc_macro_diagnostic
impl MultiSpan for Vec<Span> {
    fn into_spans(self) -> Vec<Span> {
        self
    }
}

impl MultiSpan for &[Span] {
    fn into_spans(self) -> Vec<Span> {
        self.to_vec()
    }
}

/// Will emit diagnostics in non-fatal cases:
/// - `Ok(val)?` -> `val`
/// - `Warning(val, diag)` -> `val` _and_ emits `diag` immediately
/// - `Err(diag)` -> short-circuits with `Err(diag)` but _does NOT emit_ `diag` as this would lead to
///   repeat emissions
#[cfg(all(has_never_type, has_try_trait_v2))]
impl<T> std::ops::Try for DiagnosticResult<T> {
    type Output = T;

    type Residual = DiagnosticResult<!>;

    fn from_output(output: Self::Output) -> Self {
        Self { inner: Ok_(output) }
    }

    fn branch(self) -> std::ops::ControlFlow<Self::Residual, Self::Output> {
        match self.inner {
            Ok_(t) => std::ops::ControlFlow::Continue(t),
            Warning(t, d) => {
                d.emit();
                std::ops::ControlFlow::Continue(t)
            }
            Error(d) => std::ops::ControlFlow::Break(DiagnosticResult { inner: Error(d) }),
        }
    }
}

#[cfg(all(has_never_type, has_try_trait_v2))]
impl<T> std::ops::FromResidual<DiagnosticResult<!>> for DiagnosticResult<T> {
    fn from_residual(residual: DiagnosticResult<!>) -> Self {
        match residual.inner {
            Error(residual) => Self {
                inner: Error(residual),
            },
        }
    }
}

#[cfg(all(has_never_type, has_try_trait_v2_residual))]
impl<T> std::ops::Residual<T> for DiagnosticResult<!> {
    type TryType = DiagnosticResult<T>;
}

#[cfg(has_try_trait_v2)]
impl<T, E> std::ops::FromResidual<Result<std::convert::Infallible, E>> for DiagnosticResult<T>
where
    E: Into<Diagnostic>,
{
    fn from_residual(result: Result<std::convert::Infallible, E>) -> Self {
        match result {
            Err(e) => DiagnosticResult {
                inner: DiagnosticResult_::Error(e.into()),
            },
        }
    }
}

#[cfg(has_try_trait_v2)]
impl<T, E> From<E> for DiagnosticResult<T>
where
    E: Into<Diagnostic> + std::error::Error,
{
    fn from(error: E) -> Self {
        Self {
            inner: DiagnosticResult_::Error(error.into()),
        }
    }
}

pub trait ToTokens {
    /// Convert the underlying [proc_macro2::TokenStream] to a [proc_macro::TokenStream] and/or convert
    /// and emit the contained [Diagnostic] as per [proc_macro::Diagnostic], returning an empty
    /// [proc_macro::TokenStream] in case of [DiagnosticResult::Err].
    fn to_tokens(self) -> TokenStream1;
}

impl ToTokens for DiagnosticStream {
    fn to_tokens(self) -> TokenStream1 {
        #[cfg(has_try_trait_v2)]
        match self.inner {
            Ok_(t) => t.into(),
            Warning(t, warning) => {
                _ = warning.emit();
                t.into()
            }
            Error(error) => error.emit(),
        }
        #[cfg(not(has_try_trait_v2))]
        match self {
            Self::Ok(t) => t.into(),
            Self::Err(error) => error.emit(),
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(assert_matches_location = "root")]
    use std::assert_matches;

    #[cfg(assert_matches_location = "module")]
    use std::assert_matches::assert_matches;

    use super::*;

    #[test]
    fn is_ok() {
        assert!(Ok(()).is_ok());
    }

    #[test]
    #[cfg(has_try_trait_v2)] // Cannot test without, warning would be emitted on construction.
    fn is_warning() {
        assert!(warn_spanned((), Span::call_site(), "foo").is_warning());
    }

    #[test]
    fn is_error() {
        assert!(error::<(), &str>("foo").is_error());
    }

    #[test]
    fn kind() {
        match Ok(()).kind() {
            DiagnosticResultKind::Ok => (),
            DiagnosticResultKind::Warning => panic!("not a warning"),
            DiagnosticResultKind::Error => panic!("not an error"),
        }
    }

    #[test]
    #[cfg(has_assert_matches)]
    fn ok_with_help() {
        assert_matches!(
            Ok(()).add_help(Span::call_site(), "help text").kind(),
            DiagnosticResultKind::Ok
        )
    }

    #[test]
    fn ok_or() {
        fn five() -> DiagnosticResult<i32> {
            let five = Some(5).or_error("oops!")?;
            Ok(five)
        }
        assert_eq!(five().unwrap(), 5)
    }
}