zng_app_proc_macros/
util.rs

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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{borrow::Cow, env, fmt, fs, path::PathBuf};

use proc_macro2::*;
use quote::{quote_spanned, ToTokens};
use syn::{
    self,
    parse::{discouraged::Speculative, Parse, ParseStream},
    parse_quote, parse_quote_spanned,
    punctuated::Punctuated,
    spanned::Spanned,
    Attribute, LitStr, Token,
};

use once_cell::sync::OnceCell;

/// `Ident` with custom span.
macro_rules! ident_spanned {
    ($span:expr=> $($format_name:tt)+) => {
        proc_macro2::Ident::new(&format!($($format_name)+), $span)
    };
}

/// `Ident` with call_site span.
macro_rules! ident {
    ($($tt:tt)*) => {
        ident_spanned!(proc_macro2::Span::call_site()=> $($tt)*)
    };
}

pub fn parse_braces<'a>(input: &syn::parse::ParseBuffer<'a>) -> syn::Result<(syn::token::Brace, syn::parse::ParseBuffer<'a>)> {
    let r;
    let b = syn::braced!(r in input);
    Ok((b, r))
}

/// Returns `true` if the proc-macro is running in one of the rust-analyzer proc-macro servers.
#[expect(unexpected_cfgs)] // rust_analyzer exists: https://github.com/rust-lang/rust-analyzer/pull/15528
pub fn is_rust_analyzer() -> bool {
    cfg!(rust_analyzer)
}

/// Return the equivalent of `$crate`.
pub fn crate_core() -> TokenStream {
    let (ident, module) = if is_rust_analyzer() {
        // rust-analyzer gets the wrong crate sometimes if we cache, maybe they use the same server instance
        // for the entire workspace?
        let (ident, module) = crate_core_parts();
        (Cow::Owned(ident), module)
    } else {
        static CRATE: OnceCell<(String, &'static str)> = OnceCell::new();

        let (ident, module) = CRATE.get_or_init(crate_core_parts);
        (Cow::Borrowed(ident.as_str()), *module)
    };

    let ident = Ident::new(&ident, Span::call_site());
    if !module.is_empty() {
        let module = Ident::new(module, Span::call_site());
        quote! { #ident::#module }
    } else {
        ident.to_token_stream()
    }
}
fn crate_core_parts() -> (String, &'static str) {
    if let Ok(ident) = crate_name("zng") {
        // using the main crate.
        match ident {
            FoundCrate::Name(name) => (name, "__proc_macro_util"),
            FoundCrate::Itself => ("zng".to_owned(), "__proc_macro_util"),
        }
    } else if let Ok(ident) = crate_name("zng-wgt") {
        // using the wgt crate.
        match ident {
            FoundCrate::Name(name) => (name, "__proc_macro_util"),
            FoundCrate::Itself => ("zng_wgt".to_owned(), "__proc_macro_util"),
        }
    } else if let Ok(ident) = crate_name("zng-app") {
        // using the core crate only.
        match ident {
            FoundCrate::Name(name) => (name, ""),
            FoundCrate::Itself => ("zng_app".to_owned(), ""),
        }
    } else {
        // failed, at least shows "zng" in the compile error.
        ("zng".to_owned(), "__proc_macro_util")
    }
}

#[derive(PartialEq, Debug)]
enum FoundCrate {
    Name(String),
    Itself,
}

/// Gets the module name of a given crate name (same behavior as $crate).
fn crate_name(orig_name: &str) -> Result<FoundCrate, ()> {
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(|_| ())?);

    let toml = fs::read_to_string(manifest_dir.join("Cargo.toml")).map_err(|_| ())?;

    crate_name_impl(orig_name, &toml)
}
fn crate_name_impl(orig_name: &str, toml: &str) -> Result<FoundCrate, ()> {
    // some of this code is based on the crate `proc-macro-crate` code, we
    // don't depend on that crate to speedup compile time.
    enum State<'a> {
        Seeking,
        Package,
        Dependencies,
        Dependency(&'a str),
    }

    let mut state = State::Seeking;

    for line in toml.lines() {
        let line = line.trim();

        let new_state = if line == "[package]" {
            Some(State::Package)
        } else if line.contains("dependencies.") && line.ends_with(']') {
            let name_start = line.rfind('.').unwrap();
            let name = line[name_start + 1..].trim_end_matches(']');
            Some(State::Dependency(name))
        } else if line.ends_with("dependencies]") {
            Some(State::Dependencies)
        } else if line.starts_with('[') {
            Some(State::Seeking)
        } else {
            None
        };

        if let Some(new_state) = new_state {
            if let State::Dependency(name) = state {
                if name == orig_name {
                    // finished `[*dependencies.<name>]` without finding a `package = "other"`
                    return Ok(FoundCrate::Name(orig_name.replace('-', "_")));
                }
            }

            state = new_state;
            continue;
        }

        match state {
            State::Seeking => continue,
            // Check if it is the crate itself, or one of its tests.
            State::Package => {
                if line.starts_with("name ") || line.starts_with("name=") {
                    if let Some(name_start) = line.find('"') {
                        if let Some(name_end) = line.rfind('"') {
                            let name = &line[name_start + 1..name_end];

                            if name == orig_name {
                                return Ok(if env::var_os("CARGO_TARGET_TMPDIR").is_none() {
                                    FoundCrate::Itself
                                } else {
                                    FoundCrate::Name(orig_name.replace('-', "_"))
                                });
                            }
                        }
                    }
                }
            }
            // Check dependencies, dev-dependencies, target.`..`.dependencies
            State::Dependencies => {
                if let Some(eq) = line.find('=') {
                    let name = line[..eq].trim();
                    let value = line[eq + 1..].trim();

                    if value.starts_with('"') {
                        if name == orig_name {
                            return Ok(FoundCrate::Name(orig_name.replace('-', "_")));
                        }
                    } else if value.starts_with('{') {
                        let value = value.replace(' ', "");
                        if let Some(pkg) = value.find("package=\"") {
                            let pkg = &value[pkg + "package=\"".len()..];
                            if let Some(pkg_name_end) = pkg.find('"') {
                                let pkg_name = &pkg[..pkg_name_end];
                                if pkg_name == orig_name {
                                    return Ok(FoundCrate::Name(name.replace('-', "_")));
                                }
                            }
                        } else if name == orig_name {
                            return Ok(FoundCrate::Name(orig_name.replace('-', "_")));
                        }
                    }
                }
            }
            // Check a dependency in the style [dependency.foo]
            State::Dependency(name) => {
                if line.starts_with("package ") || line.starts_with("package=") {
                    if let Some(pkg_name_start) = line.find('"') {
                        if let Some(pkg_name_end) = line.rfind('"') {
                            let pkg_name = &line[pkg_name_start + 1..pkg_name_end];

                            if pkg_name == orig_name {
                                return Ok(FoundCrate::Name(name.replace('-', "_")));
                            }
                        }
                    }
                }
            }
        }
    }

    if let State::Dependency(name) = state {
        if name == orig_name {
            // finished `[*dependencies.<name>]` without finding a `package = "other"`
            return Ok(FoundCrate::Name(orig_name.replace('-', "_")));
        }
    }

    Err(())
}

/// Generates a return of a compile_error message in the given span.
macro_rules! abort {
    ($span:expr, $($tt:tt)*) => {{
        let error = format!($($tt)*);
        let error = syn::LitStr::new(&error, proc_macro2::Span::call_site());

        return quote_spanned!($span=> compile_error!{#error}).into();
    }};
}

/// Generates a return of a compile_error message in the call_site span.
macro_rules! abort_call_site {
    ($($tt:tt)*) => {
        abort!(proc_macro2::Span::call_site(), $($tt)*)
    };
}

/// Input error not caused by the user.
macro_rules! non_user_error {
    ($e:expr) => {
        panic!("[{}:{}] invalid non-user input: {}", file!(), line!(), $e)
    };
    ($fmt:tt, $($args:tt)+) => {
        non_user_error! {
            format_args!($fmt, $($args)+)
        }
    }
}

macro_rules! non_user_group {
    ($group_kind:ident, $input:expr) => {
        {
            fn inner(input: syn::parse::ParseStream) -> syn::Result<syn::parse::ParseBuffer> {
                let inner;
                // this macro inserts a return Err(..) but we want to panic
                syn::$group_kind!(inner in input);
                Ok(inner)
            }
            inner($input).unwrap_or_else(|e| non_user_error!(e))
        }
    };
    ($group_kind:ident, $input:expr, $ident:expr) => {
        {
            let id: syn::Ident = $input.parse().unwrap_or_else(|e| non_user_error!(e));
            let ident = $ident;
            if id != ident {
                non_user_error!(format!("expected `{ident}`"));
            }
            non_user_group! { $group_kind, $input }
        }
    }
}
/// Does a `braced!` parse but panics with [`non_user_error!()`](non_user_error) if the parsing fails.
macro_rules! non_user_braced {
    ($input:expr) => {
        non_user_group! { braced, $input }
    };
    ($input:expr, $ident:expr) => {
        non_user_group! { braced, $input, $ident }
    };
}

/// Does a `parenthesized!` parse but panics with [`non_user_error!()`](non_user_error) if the parsing fails.
#[allow(unused)] // depends on cfg
macro_rules! non_user_parenthesized {
    ($input:expr) => {
        non_user_group! { parenthesized, $input }
    };
}

/// Does a `bracketed!` parse but panics with [`non_user_error!()`](non_user_error) if the parsing fails.
macro_rules! non_user_bracketed {
    ($input:expr) => {
        non_user_group! { bracketed, $input }
    };
}

/// Collection of compile errors.
#[derive(Default)]
pub struct Errors {
    tokens: TokenStream,
}
impl Errors {
    /// Push a compile error.
    pub fn push(&mut self, error: impl ToString, span: Span) {
        let error = error.to_string();
        self.tokens.extend(quote_spanned! {span=>
            compile_error!{#error}
        })
    }

    /// Push all compile errors in `error`.
    pub fn push_syn(&mut self, error: syn::Error) {
        for error in error {
            let span = error.span();
            let msg = error.to_string();
            if msg != RECOVERABLE_TAG {
                self.push(error, span);
            }
        }
    }

    pub fn is_empty(&self) -> bool {
        self.tokens.is_empty()
    }
}
impl ToTokens for Errors {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.extend(self.tokens.clone())
    }
    fn to_token_stream(&self) -> TokenStream {
        self.tokens.clone()
    }
    fn into_token_stream(self) -> TokenStream {
        self.tokens
    }
}

/// Separated attributes.
#[derive(Clone)]
pub struct Attributes {
    pub docs: Vec<Attribute>,
    pub inline: Option<Attribute>,
    pub cfg: Option<Attribute>,
    pub lints: Vec<Attribute>,
    pub others: Vec<Attribute>,
}
impl Attributes {
    pub fn new(attrs: Vec<Attribute>) -> Self {
        let mut docs = vec![];
        let mut inline = None;
        let mut cfg = None;
        let mut lints = vec![];
        let mut others = vec![];

        for attr in attrs {
            if let Some(ident) = attr.path().get_ident() {
                if ident == "doc" {
                    docs.push(attr);
                    continue;
                } else if ident == "inline" {
                    inline = Some(attr);
                } else if ident == "cfg" {
                    cfg = Some(attr);
                } else if ident == "allow" || ident == "expect" || ident == "warn" || ident == "deny" || ident == "forbid" {
                    lints.push(attr);
                } else {
                    others.push(attr);
                }
            } else {
                others.push(attr);
            }
        }

        Attributes {
            docs,
            inline,
            cfg,
            lints,
            others,
        }
    }

    /// Insert a tag on the first doc line, does nothing if docs are missing (to cause a doc missing warning).
    pub fn tag_doc(&mut self, text: &str, help: &str) {
        let txt = format!("<strong title='{help}' data-tag='{text}'><code>{text}</code></strong> ");
        for first in self.docs.iter_mut() {
            match syn::parse2::<DocAttr>(first.tokens()) {
                Ok(doc) => {
                    let mut msg = doc.msg.value();
                    msg.insert_str(0, &txt);
                    *first = parse_quote_spanned! {first.span()=>
                        #[doc = #msg]
                    };

                    return;
                }
                Err(_) => continue,
            }
        }
    }

    pub(crate) fn cfg_and_lints(&self) -> TokenStream {
        let mut tts = self.cfg.to_token_stream();
        for l in &self.lints {
            l.to_tokens(&mut tts);
        }
        tts
    }
}
impl ToTokens for Attributes {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        for attr in self
            .docs
            .iter()
            .chain(&self.inline)
            .chain(&self.cfg)
            .chain(&self.lints)
            .chain(&self.others)
        {
            attr.to_tokens(tokens);
        }
    }
}

struct DocAttr {
    msg: LitStr,
}
impl Parse for DocAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<Token![=]>()?;
        Ok(DocAttr { msg: input.parse()? })
    }
}

/// Convert a [`Path`] to a formatted [`String`].
pub fn display_path(path: &syn::Path) -> String {
    path.to_token_stream().to_string().replace(' ', "")
}

/// Gets a span that best represent the path.
pub fn path_span(path: &syn::Path) -> Span {
    path.segments.last().map(|s| s.span()).unwrap_or_else(|| path.span())
}

struct OuterAttr {
    pound_token: Token![#],
    style: syn::AttrStyle,
    bracket_token: syn::token::Bracket,
    path: syn::Path,
    tokens: TokenStream,
}
impl syn::parse::Parse for OuterAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let inner;

        Ok(OuterAttr {
            pound_token: input.parse()?,
            style: if input.peek(Token![!]) {
                syn::AttrStyle::Inner(input.parse()?)
            } else {
                syn::AttrStyle::Outer
            },
            bracket_token: syn::bracketed!(inner in input),
            path: inner.parse()?,
            tokens: inner.parse()?,
        })
    }
}
impl From<OuterAttr> for Attribute {
    fn from(s: OuterAttr) -> Self {
        Attribute {
            pound_token: s.pound_token,
            style: s.style,
            bracket_token: s.bracket_token,
            meta: {
                let path = s.path;
                let tokens = s.tokens;
                parse_quote!(#path #tokens)
            },
        }
    }
}

/// Runs `rustfmt` in the `expr`.
pub fn format_rust_expr(value: String) -> String {
    // credits: https://github.com/rust-lang/rustfmt/issues/3257#issuecomment-523573838
    use std::io::Write;
    use std::process::{Command, Stdio};
    const PREFIX: &str = "const x:() = ";
    const SUFFIX: &str = ";\n";
    if let Ok(mut proc) = Command::new("rustfmt")
        .arg("--emit=stdout")
        .arg("--edition=2018")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
    {
        {
            let stdin = proc.stdin.as_mut().unwrap();
            stdin.write_all(PREFIX.as_bytes()).unwrap();
            stdin.write_all(value.as_bytes()).unwrap();
            stdin.write_all(SUFFIX.as_bytes()).unwrap();
        }
        if let Ok(output) = proc.wait_with_output() {
            if output.status.success() {
                // slice between after the prefix and before the suffix
                // (currently 14 from the start and 2 before the end, respectively)
                let start = PREFIX.len() + 1;
                let end = output.stdout.len() - SUFFIX.len();
                return std::str::from_utf8(&output.stdout[start..end]).unwrap().to_owned();
            }
        }
    }
    value
}

/// Gets the span of the last item or the span_close if the last item is a group.
pub fn last_span(tts: TokenStream) -> Span {
    if let Some(tt) = tts.into_iter().last() {
        if let proc_macro2::TokenTree::Group(g) = tt {
            g.span_close()
        } else {
            tt.span()
        }
    } else {
        Span::call_site()
    }
}

/// A lint level.
///
/// NOTE: We add an underline `_` after the lint display name because rustc validates
/// custom tools even for lint attributes removed by proc-macros.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintLevel {
    Allow,
    Warn,
    Deny,
    Forbid,
}
impl fmt::Display for LintLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LintLevel::Allow => write!(f, "allow_"),
            LintLevel::Warn => write!(f, "warn_"),
            LintLevel::Deny => write!(f, "deny_"),
            LintLevel::Forbid => write!(f, "forbid_"),
        }
    }
}

/// Takes lint attributes in the `zng::` namespace.
///
/// Pushes `errors` for unsupported `warn` and already attempt of setting
/// level of forbidden zng lints.
///
/// NOTE: We add an underline `_` after the lint ident because rustc validates
/// custom tools even for lint attributes removed by proc-macros.
pub fn take_zng_lints(
    attrs: &mut Vec<Attribute>,
    errors: &mut Errors,
    forbidden: &std::collections::HashSet<&Ident>,
) -> Vec<(Ident, LintLevel, Attribute)> {
    let mut r = vec![];
    let mut i = 0;
    while i < attrs.len() {
        if let Some(ident) = attrs[i].path().get_ident() {
            let level = if ident == "allow_" {
                LintLevel::Allow
            } else if ident == "warn_" {
                LintLevel::Warn
            } else if ident == "deny_" {
                LintLevel::Deny
            } else if ident == "forbid_" {
                LintLevel::Forbid
            } else {
                i += 1;
                continue;
            };
            if let Ok(path) = syn::parse2::<LintPath>(attrs[i].tokens()) {
                let path = path.path;
                if path.segments.len() == 2 && path.segments[0].ident == "zng" {
                    let attr = attrs.remove(i);
                    let lint_ident = path.segments[1].ident.clone();
                    match level {
                        LintLevel::Warn => errors.push(
                            "cannot set zng lints to warn because warning diagnostics are not stable",
                            attr.path().span(),
                        ),
                        LintLevel::Allow if forbidden.contains(&lint_ident) => {
                            errors.push(format_args!("lint `zng::{lint_ident}` is `forbid` in this context"), attr.span())
                        }
                        _ => {
                            r.push((lint_ident, level, attr));
                        }
                    }

                    continue; // same i new attribute
                }
            }
        }

        i += 1;
    }
    r
}
struct LintPath {
    _paren: syn::token::Paren,
    path: syn::Path,
}
impl syn::parse::Parse for LintPath {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let inner;
        Ok(LintPath {
            _paren: syn::parenthesized!(inner in input),
            path: inner.parse()?,
        })
    }
}

pub fn span_is_call_site(a: proc_macro2::Span) -> bool {
    span_eq(a, proc_macro2::Span::call_site())
}

pub fn span_eq(a: proc_macro2::Span, b: proc_macro2::Span) -> bool {
    format!("{a:?}") == format!("{b:?}")
}

/// Parses all outer attributes and stores any parsing errors in `errors`.
/// Note: If a malformed attribute is passed, only the attributes after that one will be returned.
pub fn parse_outer_attrs(input: ParseStream, errors: &mut Errors) -> Vec<Attribute> {
    let mut attrs;
    loop {
        let fork = input.fork();
        let mut parsed = true;

        attrs = Attribute::parse_outer(&fork).unwrap_or_else(|e| {
            parsed = false;
            errors.push_syn(e);
            vec![]
        });
        if parsed {
            input.advance_to(&fork);
            break;
        } else {
            let _ = input.parse::<Token![#]>();
            if input.peek(Token![!]) {
                let _ = input.parse::<Token![!]>();
            }
            let _ = non_user_bracketed!(input).parse::<TokenStream>();
        }
    }

    attrs
}

/// New [`syn::Error`] marked [recoverable](ErrorRecoverable).
pub fn recoverable_err(span: Span, msg: impl std::fmt::Display) -> syn::Error {
    syn::Error::new(span, msg).set_recoverable()
}

const RECOVERABLE_TAG: &str = "<recoverable>";
fn recoverable_tag() -> syn::Error {
    syn::Error::new(Span::call_site(), RECOVERABLE_TAG)
}

/// Extension to [`syn::Error`] that lets you mark an error as recoverable,
/// meaning that a sequence of the parse stream is not correct but the parser
/// manage to skip to the end of what was expected to be parsed.
pub trait ErrorRecoverable {
    /// Returns a new error that contains all the errors in `self` but is also marked recoverable.
    fn set_recoverable(self) -> Self;
    /// Returns if `self` is recoverable and all the errors in `self`.
    ///
    /// Note: An error is considered recoverable only if all inner errors are marked recoverable.
    fn recoverable(self) -> (bool, Self);
}
impl ErrorRecoverable for syn::Error {
    fn set_recoverable(self) -> Self {
        let mut errors = self.into_iter();
        let mut e = errors.next().unwrap();

        debug_assert!(e.to_string() != RECOVERABLE_TAG);

        e.combine(recoverable_tag());

        for error in errors {
            if e.to_string() != RECOVERABLE_TAG {
                e.combine(error);
                e.combine(recoverable_tag());
            }
        }

        e
    }
    fn recoverable(self) -> (bool, Self) {
        let mut errors = self.into_iter();
        let mut e = errors.next().unwrap();

        debug_assert!(e.to_string() != RECOVERABLE_TAG);

        let mut errors_count = 1;
        let mut tags_count = 0;

        for error in errors {
            if error.to_string() == RECOVERABLE_TAG {
                tags_count += 1;
            } else {
                errors_count += 1;
                e.combine(error);
            }
        }

        (errors_count == tags_count, e)
    }
}

// Debug tracing if it was enabled during run-time.
//
// This is useful for debugging say the widget macros but only for a widget.
//
// Use [`enable_trace!`] and [`trace!`].
#[allow(unused)] // depends on cfg
#[cfg(debug_assertions)]
pub mod debug_trace {
    use std::sync::atomic::{AtomicBool, Ordering};

    static ENABLED: AtomicBool = AtomicBool::new(false);

    pub fn enable(enable: bool) {
        let prev = ENABLED.swap(enable, Ordering::SeqCst);
        if prev != enable {
            eprintln!("zng-proc-macros::debug_trace {}", if enable { "enabled" } else { "disabled" });
        }
    }

    pub fn display(msg: impl std::fmt::Display) {
        if ENABLED.load(Ordering::SeqCst) {
            eprintln!("{msg}");
        }
    }
}

#[allow(unused)] // depends on cfg
#[cfg(debug_assertions)]
macro_rules! enable_trace {
    () => {
        $crate::util::debug_trace::enable(true);
    };
    (if $bool_expr:expr) => {
        $crate::util::debug_trace::enable($bool_expr);
    };
}
#[allow(unused)] // depends on cfg
#[cfg(debug_assertions)]
macro_rules! trace {
    ($msg:tt) => {
        $crate::util::debug_trace::display($msg);
    };
    ($fmt:tt, $($args:tt)+) => {
        $crate::util::debug_trace::display(format_args!($fmt, $($args)+));
    };
}

/// `Punctuated::parse_terminated` from a `TokenStream`.
pub fn parse_punct_terminated2<T: Parse, P: syn::token::Token + Parse>(input: TokenStream) -> syn::Result<Punctuated<T, P>> {
    struct PunctTerm<T: Parse, P: syn::token::Token + Parse>(Punctuated<T, P>);

    impl<T: Parse, P: syn::token::Token + Parse> Parse for PunctTerm<T, P> {
        fn parse(input: ParseStream) -> syn::Result<Self> {
            Ok(Self(Punctuated::parse_terminated(input)?))
        }
    }

    syn::parse2::<PunctTerm<T, P>>(input).map(|p| p.0)
}

/// Returns `true` if the stream has at least 3 more tokens.
pub fn peek_any3(stream: ParseStream) -> bool {
    let mut cursor = stream.cursor();

    if let Some(group) = stream.cursor().group(Delimiter::None) {
        cursor = group.0;
    }

    if let Some((_, cursor)) = cursor.token_tree() {
        if let Some((_, cursor)) = cursor.token_tree() {
            if let Some((_tt, _)) = cursor.token_tree() {
                return true;
            }
        }
    }

    false
}

/// Set the span for each token-tree in the stream.
pub fn set_stream_span(stream: TokenStream, span: Span) -> TokenStream {
    stream
        .into_iter()
        .map(|mut tt| {
            tt.set_span(span);
            tt
        })
        .collect()
}

pub trait AttributeExt {
    fn tokens(&self) -> TokenStream;
}
impl AttributeExt for Attribute {
    fn tokens(&self) -> TokenStream {
        match &self.meta {
            syn::Meta::Path(_) => quote!(),
            syn::Meta::List(m) => {
                let t = &m.tokens;
                match &m.delimiter {
                    syn::MacroDelimiter::Paren(p) => quote_spanned!(p.span.join()=> (#t)),
                    syn::MacroDelimiter::Brace(b) => quote_spanned!(b.span.join()=> {#t}),
                    syn::MacroDelimiter::Bracket(b) => quote_spanned!(b.span.join()=> [#t]),
                }
            }
            syn::Meta::NameValue(m) => {
                let eq = &m.eq_token;
                let tk = &m.value;
                quote!(#eq #tk)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn crate_name_itself_1() {
        let toml = r#"
        [package]
        name = "crate-name"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Itself, r);
    }

    #[test]
    fn crate_name_itself_2() {
        let toml = r#"
        [package]
        version = "0.1.0"
        edition = "2021"
        name = "crate-name"
        license = "Apache-2.0"
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Itself, r);
    }

    #[test]
    fn crate_name_dependencies_1() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [dependencies]
        bar = "1.0"
        crate-name = "*"

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("crate_name".to_owned()), r);
    }

    #[test]
    fn crate_name_dependencies_2() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [dependencies]
        zum = "1.0"
        super-name = { version = "*", package = "crate-name" }

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("super_name".to_owned()), r);
    }

    #[test]
    fn crate_name_dependencies_3() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [target.'cfg(windows)'.dependencies]
        zum = "1.0"
        super-name = { version = "*", package = "crate-name" }

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("super_name".to_owned()), r);
    }

    #[test]
    fn crate_name_dependencies_4() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [dev-dependencies]
        zum = "1.0"
        super-name = { version = "*", package = "crate-name" }

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("super_name".to_owned()), r);
    }

    #[test]
    fn crate_name_dependency_1() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [dev-dependencies.super-foo]
        version = "*"
        package = "crate-name"

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("super_foo".to_owned()), r);
    }

    #[test]
    fn crate_name_dependency_2() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [dependencies.super-foo]
        version = "*"
        package = "crate-name"

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("super_foo".to_owned()), r);
    }

    #[test]
    fn crate_name_dependency_3() {
        let toml = r#"
        [package]
        name = "foo"
        version = "0.1.0"
        edition = "2021"
        license = "Apache-2.0"

        [dependencies.crate-name]
        version = "*"

        [workspace]
        "#;

        let r = crate_name_impl("crate-name", toml).unwrap();
        assert_eq!(FoundCrate::Name("crate_name".to_owned()), r);
    }
}