zenoh-macros 1.9.0

Internal crate for zenoh.
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
763
764
765
766
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//

//! ⚠️ WARNING ⚠️
//!
//! This crate is intended for Zenoh's internal use.
//!
//! [Click here for Zenoh's documentation](https://docs.rs/zenoh/latest/zenoh)
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
    parse_macro_input, parse_quote, spanned::Spanned, Attribute, Error, Item, ItemImpl, LitStr,
    TraitItem,
};
use zenoh_keyexpr::{
    format::{
        macro_support::{self, SegmentBuilder},
        KeFormat,
    },
    key_expr::keyexpr,
};

const RUSTC_VERSION: &str = include_str!(concat!(env!("OUT_DIR"), "/version.rs"));

#[proc_macro]
pub fn rustc_version_release(_tokens: TokenStream) -> TokenStream {
    let release = RUSTC_VERSION
        .split('\n')
        .filter_map(|l| {
            let line = l.trim();
            if line.is_empty() {
                None
            } else {
                Some(line)
            }
        })
        .find_map(|l| l.strip_prefix("release: "))
        .unwrap();
    let commit = RUSTC_VERSION
        .split('\n')
        .filter_map(|l| {
            let line = l.trim();
            if line.is_empty() {
                None
            } else {
                Some(line)
            }
        })
        .find_map(|l| l.strip_prefix("commit-hash: "))
        .unwrap();
    (quote! {(#release, #commit)}).into()
}

/// An enumeration of items which can be annotated with `#[zenoh_macros::unstable_doc]`, #[zenoh_macros::unstable]`, `#[zenoh_macros::internal]`
#[allow(clippy::large_enum_variant)]
enum AnnotableItem {
    /// Wrapper around [`syn::Item`].
    Item(Item),
    /// Wrapper around [`syn::TraitItem`].
    TraitItem(TraitItem),
}

macro_rules! parse_annotable_item {
    ($tokens:ident) => {{
        let item: Item = parse_macro_input!($tokens as Item);

        if matches!(item, Item::Verbatim(_)) {
            let tokens = TokenStream::from(item.to_token_stream());
            let trait_item: TraitItem = parse_macro_input!(tokens as TraitItem);

            if matches!(trait_item, TraitItem::Verbatim(_)) {
                Err(Error::new_spanned(
                    trait_item,
                    "the `unstable` proc-macro attribute only supports items and trait items",
                ))
            } else {
                Ok(AnnotableItem::TraitItem(trait_item))
            }
        } else {
            Ok(AnnotableItem::Item(item))
        }
    }};
}

impl AnnotableItem {
    /// Mutably borrows the attribute list of this item.
    fn attributes_mut(&mut self) -> Result<&mut Vec<Attribute>, Error> {
        match self {
            AnnotableItem::Item(item) => match item {
                Item::Const(item) => Ok(&mut item.attrs),
                Item::Enum(item) => Ok(&mut item.attrs),
                Item::ExternCrate(item) => Ok(&mut item.attrs),
                Item::Fn(item) => Ok(&mut item.attrs),
                Item::ForeignMod(item) => Ok(&mut item.attrs),
                Item::Impl(item) => Ok(&mut item.attrs),
                Item::Macro(item) => Ok(&mut item.attrs),
                Item::Mod(item) => Ok(&mut item.attrs),
                Item::Static(item) => Ok(&mut item.attrs),
                Item::Struct(item) => Ok(&mut item.attrs),
                Item::Trait(item) => Ok(&mut item.attrs),
                Item::TraitAlias(item) => Ok(&mut item.attrs),
                Item::Type(item) => Ok(&mut item.attrs),
                Item::Union(item) => Ok(&mut item.attrs),
                Item::Use(item) => Ok(&mut item.attrs),
                other => Err(Error::new_spanned(
                    other,
                    "item is not supported by the `unstable` or `internal` proc-macro attribute",
                )),
            },
            AnnotableItem::TraitItem(trait_item) => match trait_item {
                TraitItem::Const(trait_item) => Ok(&mut trait_item.attrs),
                TraitItem::Fn(trait_item) => Ok(&mut trait_item.attrs),
                TraitItem::Type(trait_item) => Ok(&mut trait_item.attrs),
                TraitItem::Macro(trait_item) => Ok(&mut trait_item.attrs),
                other => Err(Error::new_spanned(
                    other,
                    "item is not supported by the `unstable` or `internal` proc-macro attribute",
                )),
            },
        }
    }

    /// Converts this item to a `proc_macro2::TokenStream`.
    fn to_token_stream(&self) -> proc_macro2::TokenStream {
        match self {
            AnnotableItem::Item(item) => item.to_token_stream(),
            AnnotableItem::TraitItem(trait_item) => trait_item.to_token_stream(),
        }
    }
}

/// Adds unstable warning to documentation. Returns Result for proper error handling.
fn add_unstable_warning(item: &mut AnnotableItem) -> Result<(), Error> {
    let attrs = item.attributes_mut()?;

    let mut old_attrs = std::mem::take(attrs).into_iter();

    // First loop: copy attrs until first doc attr, add warning after it
    for attr in old_attrs.by_ref() {
        attrs.push(attr);
        if get_doc_str(attrs.last().unwrap()).is_some() {
            // See: https://doc.rust-lang.org/rustdoc/how-to-write-documentation.html#adding-a-warning-block
            let message = "<div class=\"warning\">This API has been marked as <strong>unstable</strong>: it works as advertised, but it may be changed in a future release.</div>";
            let note: Attribute = parse_quote!(#[doc = #message]);
            attrs.push(note);
            break;
        }
    }

    // Second loop: copy attrs until second doc attr, validate that it's blank
    for attr in old_attrs.by_ref() {
        if let Some(lit_str) = get_doc_str(&attr) {
            if !lit_str.value().trim().is_empty() {
                return Err(Error::new_spanned(
                    attr,
                    "documentation for `#[unstable]` items must have a blank doc line after the brief description. \
                     This blank line is critical for proper formatting: it will separate the unstable warning from the content below and ensures that \
                     markdown links (like [`Type`](path::to::Type)) are correctly processed by rustdoc. \
                     Add an empty `///` line after your brief description and before detailed explanations.",
                ));
            }
            attrs.push(attr);
            break;
        }
        attrs.push(attr);
    }

    // Third loop: copy remaining attrs
    attrs.extend(old_attrs);

    Ok(())
}

#[proc_macro_attribute]
/// Adds only piece of documentation about the item being unstable but no unstable attribute itself.
/// This is useful when the whole crate is supposed to be used in unstable mode only, it makes sense
/// to mention it in documentation for the crate items, but not to add `#[cfg(feature = "unstable")]` to every item.
pub fn unstable_doc(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
    let mut item = match parse_annotable_item!(tokens) {
        Ok(item) => item,
        Err(err) => return err.into_compile_error().into(),
    };

    if let Err(err) = add_unstable_warning(&mut item) {
        return err.into_compile_error().into();
    }

    TokenStream::from(item.to_token_stream())
}

#[proc_macro_attribute]
/// Adds a `#[cfg(feature = "unstable")]` attribute to the item and appends piece of documentation about the item being unstable.
pub fn unstable(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
    let mut item = match parse_annotable_item!(tokens) {
        Ok(item) => item,
        Err(err) => return err.into_compile_error().into(),
    };

    if let Err(err) = add_unstable_warning(&mut item) {
        return err.into_compile_error().into();
    }

    let attrs = match item.attributes_mut() {
        Ok(attrs) => attrs,
        Err(err) => return err.into_compile_error().into(),
    };

    let feature_gate: Attribute = parse_quote!(#[cfg(feature = "unstable")]);
    attrs.push(feature_gate);

    TokenStream::from(item.to_token_stream())
}

#[proc_macro_attribute]
/// Adds a `#[cfg(feature = "internal")]` and `#[doc(hidden)]` attributes to the item.
pub fn internal(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
    let mut item = match parse_annotable_item!(tokens) {
        Ok(item) => item,
        Err(err) => return err.into_compile_error().into(),
    };

    let attrs = match item.attributes_mut() {
        Ok(attrs) => attrs,
        Err(err) => return err.into_compile_error().into(),
    };

    let feature_gate: Attribute = parse_quote!(#[cfg(feature = "internal")]);
    let hide_doc: Attribute = parse_quote!(#[doc(hidden)]);
    attrs.push(feature_gate);
    attrs.push(hide_doc);

    TokenStream::from(item.to_token_stream())
}

/// Extracts the string literal from a `#[doc = "..."]` attribute.
fn get_doc_str(attr: &Attribute) -> Option<&LitStr> {
    if attr
        .path()
        .get_ident()
        .is_some_and(|ident| &ident.to_string() == "doc")
    {
        if let syn::Meta::NameValue(nv) = &attr.meta {
            if let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(lit_str),
                ..
            }) = &nv.value
            {
                return Some(lit_str);
            }
        }
    }
    None
}

fn keformat_support(source: &str) -> proc_macro2::TokenStream {
    let format = match KeFormat::new(&source) {
        Ok(format) => format,
        Err(e) => panic!("{}", e),
    };
    let specs = unsafe { macro_support::specs(&format) };
    let len = specs.len();
    let setters = specs.iter().map(|spec| {
        let id = &source[spec.spec_start..(spec.spec_start + spec.id_end as usize)];
        let set_id = quote::format_ident!("{}", id);
        quote! {
            pub fn #set_id <S: ::core::fmt::Display>(&mut self, value: S) -> Result<&mut Self, ::zenoh::key_expr::format::FormatSetError> {
                match self.0.set(#id, value) {
                    Ok(_) => Ok(self),
                    Err(e) => Err(e)
                }
            }
        }
    });
    let getters = specs.iter().map(|spec| {
        let source = &source[spec.spec_start..spec.spec_end];
        let id = &source[..(spec.id_end as usize)];
        let get_id = quote::format_ident!("{}", id);
        let pattern = unsafe {
            keyexpr::from_str_unchecked(if spec.pattern_end != u16::MAX {
                &source[(spec.id_end as usize + 1)..(spec.spec_start + spec.pattern_end as usize)]
            } else {
                &source[(spec.id_end as usize + 1)..]
            })
        };
        let doc = format!("Get the parsed value for `{id}`.\n\nThis value is guaranteed to be a valid key expression intersecting with `{pattern}`");
        if pattern.as_bytes() == b"**" {
            quote! {
                #[doc = #doc]
                /// Since the pattern is `**`, this may return `None` if the pattern didn't consume any chunks.
                pub fn #get_id (&self) -> Option<& ::zenoh::key_expr::keyexpr> {
                    unsafe {
                        let s =self._0.get(#id).unwrap_unchecked();
                        (!s.is_empty()).then(|| ::zenoh::key_expr::keyexpr::from_str_unchecked(s))
                    }
                }
            }
        } else {
            quote! {
                #[doc = #doc]
                pub fn #get_id (&self) -> &::zenoh::key_expr::keyexpr {
                    unsafe {::zenoh::key_expr::keyexpr::from_str_unchecked(self._0.get(#id).unwrap_unchecked())}
                }
            }
        }
    });
    let segments = specs.iter().map(|spec| {
        let SegmentBuilder {
            segment_start,
            prefix_end,
            spec_start,
            id_end,
            pattern_end,
            spec_end,
            segment_end,
        } = spec;
        quote! {
            ::zenoh::key_expr::format::macro_support::SegmentBuilder {
                segment_start: #segment_start,
                prefix_end: #prefix_end,
                spec_start: #spec_start,
                id_end: #id_end,
                pattern_end: #pattern_end,
                spec_end: #spec_end,
                segment_end: #segment_end,
            },
        }
    });

    let format_doc = format!("The `{source}` format, as a zero-sized-type.");
    let formatter_doc = format!("And instance of a formatter for `{source}`.");

    quote! {
            use ::zenoh::Result as ZResult;
            const FORMAT_INNER: ::zenoh::key_expr::format::KeFormat<'static, [::zenoh::key_expr::format::Segment<'static>; #len]> = unsafe {
                ::zenoh::key_expr::format::macro_support::const_new(#source, [#(#segments)*])
            };
            #[doc = #format_doc]
            #[derive(Copy, Clone, Hash)]
            pub struct Format;

            #[doc = #formatter_doc]
            #[derive(Clone)]
            pub struct Formatter(::zenoh::key_expr::format::KeFormatter<'static, [::zenoh::key_expr::format::Segment<'static>; #len]>);
            impl ::core::fmt::Debug for Format {
                fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                    ::core::fmt::Debug::fmt(&FORMAT_INNER, f)
                }
            }
            impl ::core::fmt::Debug for Formatter {
                fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                    ::core::fmt::Debug::fmt(&self.0, f)
                }
            }
            impl ::core::fmt::Display for Format {
                fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                    ::core::fmt::Display::fmt(&FORMAT_INNER, f)
                }
            }
            impl ::core::ops::Deref for Format {
                type Target = ::zenoh::key_expr::format::KeFormat<'static, [::zenoh::key_expr::format::Segment<'static>; #len]>;
                fn deref(&self) -> &Self::Target {&FORMAT_INNER}
            }
            impl ::core::ops::Deref for Formatter {
                type Target = ::zenoh::key_expr::format::KeFormatter<'static, [::zenoh::key_expr::format::Segment<'static>; #len]>;
                fn deref(&self) -> &Self::Target {&self.0}
            }
            impl ::core::ops::DerefMut for Formatter {
                fn deref_mut(&mut self) -> &mut Self::Target {&mut self.0}
            }
            impl Formatter {
                #(#setters)*
            }
            pub struct Parsed<'s>{_0: ::zenoh::key_expr::format::Parsed<'s, [::zenoh::key_expr::format::Segment<'s>; #len]>}
            impl<'s> ::core::ops::Deref for Parsed<'s> {
                type Target = ::zenoh::key_expr::format::Parsed<'s, [::zenoh::key_expr::format::Segment<'s>; #len]>;
                fn deref(&self) -> &Self::Target {&self._0}
            }
            impl Parsed<'_> {
                #(#getters)*
            }
            impl Format {
                pub fn formatter() -> Formatter {
                    Formatter(Format.formatter())
                }
                pub fn parse<'s>(target: &'s ::zenoh::key_expr::keyexpr) -> ZResult<Parsed<'s>> {
                    Ok(Parsed{_0: Format.parse(target)?})
                }
                pub fn into_inner(self) -> ::zenoh::key_expr::format::KeFormat<'static, [::zenoh::key_expr::format::Segment<'static>; #len]> {
                    FORMAT_INNER
                }
            }
            pub fn formatter() -> Formatter {
                Format::formatter()
            }
            pub fn parse<'s>(target: &'s ::zenoh::key_expr::keyexpr) -> ZResult<Parsed<'s>> {
                Format::parse(target)
            }
    }
}

struct FormatDeclaration {
    vis: syn::Visibility,
    name: syn::Ident,
    lit: syn::LitStr,
}
impl syn::parse::Parse for FormatDeclaration {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let vis = input.parse()?;
        let name = input.parse()?;
        let _: syn::Token!(:) = input.parse()?;
        let lit = input.parse()?;
        Ok(FormatDeclaration { vis, name, lit })
    }
}
struct FormatDeclarations(syn::punctuated::Punctuated<FormatDeclaration, syn::Token!(,)>);
impl syn::parse::Parse for FormatDeclarations {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        Ok(Self(input.parse_terminated(
            FormatDeclaration::parse,
            syn::Token![,],
        )?))
    }
}

/// Create format modules from a format specification.
///
/// `kedefine!($($vis $ident: $lit),*)` will validate each `$lit` to be a valid KeFormat, and declare a module called `$ident` with `$vis` visibility at its call-site for each format.
///  The modules contain the following elements:
/// - `Format`, a zero-sized type that represents your format.
/// - `formatter()`, a function that constructs a `Formatter` specialized for your format:
///     - for every spec in your format, `Formatter` will have a method named after the spec's `id` that lets you set a value for that field of your format. These methods will return `Result<&mut Formatter, FormatError>`.
/// - `parse(target: &keyexpr) -> ZResult<Parsed<'_>>` will parse the provided key expression according to your format. Just like `KeFormat::parse`, parsing is lazy: each field will match the smallest subsection of your `target` that is included in its pattern.
///     - like `Formatter`, `Parsed` will have a method named after each spec's `id` that returns `&keyexpr`; except for specs whose pattern was `**`, these will return an `Option<&keyexpr>`, where `None` signifies that the pattern was matched by an empty list of chunks.
#[proc_macro]
pub fn kedefine(tokens: TokenStream) -> TokenStream {
    let declarations: FormatDeclarations = syn::parse(tokens).unwrap();
    let content = declarations.0.into_iter().map(|FormatDeclaration { vis, name, lit }|
    {
    let source = lit.value();
    let docstring = format!(
        r"The module associated with the `{source}` format, it contains:
- `Format`, a zero-sized type that represents your format.
- `formatter()`, a function that constructs a `Formatter` specialized for your format:
    - for every spec in your format, `Formatter` will have a method named after the spec's `id` that lets you set a value for that field of your format. These methods will return `Result<&mut Formatter, FormatError>`.
- `parse(target: &keyexpr) -> ZResult<Parsed<'_>>` will parse the provided key expression according to your format. Just like `KeFormat::parse`, parsing is lazy: each field will match the smallest subsection of your `target` that is included in its pattern.
    - like `Formatter`, `Parsed` will have a method named after each spec's `id` that returns `&keyexpr`; except for specs whose pattern was `**`, these will return an `Option<&keyexpr>`, where `None` signifies that the pattern was matched by an empty list of chunks."
    );
    let support = keformat_support(&source);
    quote! {
        #[doc = #docstring]
        #vis mod #name{
            #support
        }
    }});
    quote!(#(#content)*).into()
}

struct FormatUsage {
    id: syn::Expr,
    assigns: Vec<(syn::Expr, syn::Expr)>,
}
impl syn::parse::Parse for FormatUsage {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let id = input.parse()?;
        let mut assigns = Vec::new();
        if !input.is_empty() {
            input.parse::<syn::Token!(,)>()?;
        }
        assigns.extend(
            input
                .parse_terminated(syn::Expr::parse, syn::Token![,])?
                .into_iter()
                .map(|a| match a {
                    syn::Expr::Assign(a) => (*a.left, *a.right),
                    a => (a.clone(), a),
                }),
        );
        Ok(FormatUsage { id, assigns })
    }
}

/// Write a set of values into a `Formatter`, stopping as soon as a value doesn't fit the specification for its field.
/// Contrary to `keformat` doesn't build the Formatter into a Key Expression.
///
/// `kewrite!($formatter, $($ident [= $expr]),*)` will attempt to write `$expr` into their respective `$ident` fields for `$formatter`.
/// `$formatter` must be an expression that dereferences to `&mut Formatter`.
/// `$expr` must resolve to a value that implements `core::fmt::Display`.
/// `$expr` defaults to `$ident` if omitted.
///
/// This macro always results in an expression that resolves to `Result<&mut Formatter, FormatSetError>`.
#[proc_macro]
pub fn kewrite(tokens: TokenStream) -> TokenStream {
    let FormatUsage { id, assigns } = syn::parse(tokens).unwrap();
    let mut sets = None;
    for (l, r) in assigns.iter().rev() {
        if let Some(set) = sets {
            sets = Some(quote!(.#l(#r).and_then(|x| x #set)));
        } else {
            sets = Some(quote!(.#l(#r)));
        }
    }
    quote!(#id #sets).into()
}

/// Write a set of values into a `Formatter` and then builds it into an `OwnedKeyExpr`, stopping as soon as a value doesn't fit the specification for its field.
///
/// `keformat!($formatter, $($ident [= $expr]),*)` will attempt to write `$expr` into their respective `$ident` fields for `$formatter`.
/// `$formatter` must be an expression that dereferences to `&mut Formatter`.
/// `$expr` must resolve to a value that implements `core::fmt::Display`.
/// `$expr` defaults to `$ident` if omitted.
///
/// This macro always results in an expression that resolves to `ZResult<OwnedKeyExpr>`, and leaves `$formatter` in its written state.
#[proc_macro]
pub fn keformat(tokens: TokenStream) -> TokenStream {
    let formatted: proc_macro2::TokenStream = kewrite(tokens).into();
    quote!(match #formatted {
        Ok(ok) => ok.build(),
        Err(e) => Err(e.into()),
    })
    .into()
}

/// Equivalent to [`keyexpr::new`](zenoh_keyexpr::keyexpr::new), but the check is run at compile-time and will throw a compile error in case of failure.
#[proc_macro]
pub fn ke(tokens: TokenStream) -> TokenStream {
    let value: LitStr = syn::parse(tokens).unwrap();
    let ke = value.value();
    match zenoh_keyexpr::keyexpr::new(&ke) {
        Ok(_) => quote!(unsafe { zenoh::key_expr::keyexpr::from_str_unchecked(#ke)}).into(),
        Err(e) => panic!("{}", e),
    }
}

/// Equivalent to [`nonwild_keyexpr::new`](zenoh_keyexpr::nonwild_keyexpr::new), but the check is run at compile-time and will throw a compile error in case of failure.
#[proc_macro]
pub fn nonwild_ke(tokens: TokenStream) -> TokenStream {
    let value: LitStr = syn::parse(tokens).unwrap();
    let ke = value.value();
    match zenoh_keyexpr::nonwild_keyexpr::new(&ke) {
        Ok(_) => quote!(unsafe { zenoh::key_expr::nonwild_keyexpr::from_str_unchecked(#ke)}).into(),
        Err(e) => panic!("{}", e),
    }
}

mod zenoh_runtime_derive;
use syn::DeriveInput;
use zenoh_runtime_derive::{derive_generic_runtime_param, derive_register_param};

/// Make the underlying struct `Param` be generic over any `T` satisfying a generated `trait DefaultParam { fn param() -> Param; }`
/// ```rust,ignore
/// #[derive(GenericRuntimeParam)]
/// struct Param {
///    ...
/// }
/// ```
#[proc_macro_derive(GenericRuntimeParam)]
pub fn generic_runtime_param(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: DeriveInput = syn::parse_macro_input!(input);
    derive_generic_runtime_param(input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Register the input `Enum` with the struct `Param` specified in the param attribute
/// ```rust,ignore
/// #[derive(RegisterParam)]
/// #[param(Param)]
/// enum Enum {
///    ...
/// }
/// ```
#[proc_macro_derive(RegisterParam, attributes(alias, param))]
pub fn register_param(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: DeriveInput = syn::parse_macro_input!(input);
    derive_register_param(input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Macro `#[internal_trait]` should precede
/// `impl Trait for Struct { ... }`
///
/// This macro wraps the implementations of "internal" tratis.
///
/// These traits are used to group set of functions which should be implemented
/// together and with the same prototype. E.g. `QoSBuilderTrait` provides set of
/// setters (`congestion_control`, `priority`, `express`) and we should not
/// forget to implement all these setters for each entity which supports
/// QoS functionality.
///
/// The traits mechanism is a good way to group functions. But additional traits
/// adds extra burden to end user who have to import it every time.
///
/// The macro `internal_trait` solves this problem by adding
/// methods with same names as in trait to structure implementation itself,
/// making them available to user without additional trait import.
///
#[proc_macro_attribute]
pub fn internal_trait(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(item as ItemImpl);
    let trait_path = &input.trait_.as_ref().unwrap().1;
    let struct_path = &input.self_ty;
    let generics = &input.generics;
    // let struct_lifetime = get_type_path_lifetime(struct_path);

    let mut struct_methods = quote! {};
    for item_fn in input.items.iter_mut() {
        if let syn::ImplItem::Fn(method) = item_fn {
            let method_name = &method.sig.ident;
            let method_generic_params = &method.sig.generics.params;
            let method_generic_params = if method_generic_params.is_empty() {
                quote! {}
            } else {
                quote! {<#method_generic_params>}
            };
            let method_args = &method.sig.inputs;
            let method_output = &method.sig.output;
            let where_clause = &method.sig.generics.where_clause;
            let mut method_call_args = quote! {};
            for arg in method_args.iter() {
                match arg {
                    syn::FnArg::Receiver(_) => {
                        method_call_args.extend(quote! { self, });
                    }
                    syn::FnArg::Typed(pat_type) => {
                        let pat = &pat_type.pat;
                        method_call_args.extend(quote! { #pat, });
                    }
                }
            }
            let mut attributes = quote! {};
            for attr in &method.attrs {
                attributes.extend(quote! {
                    #attr
                });
            }
            method
                .attrs
                .retain(|attr| !attr.meta.path().is_ident("deprecated"));
            // call corresponding trait method from struct method
            struct_methods.extend(quote! {
                #attributes
                pub fn #method_name #method_generic_params (#method_args) #method_output #where_clause {
                    <#struct_path as #trait_path>::#method_name(#method_call_args)
                }
            });
        }
    }
    let struct_methods_output = quote! {
        impl #generics #struct_path {
            #struct_methods
        }
    };
    (quote! {
        #input
        #struct_methods_output
    })
    .into()
}

#[proc_macro_attribute]
pub fn pub_visibility_if_internal(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
    let mut out = TokenStream::new();
    let mut item_original: syn::Item = syn::parse(tokens).expect("failed to parse input");
    let item_modified;
    let not_internal_feature_gate: Attribute = parse_quote!(#[cfg(not(feature = "internal"))]);
    let internal_feature_gate: Attribute = parse_quote!(#[cfg(feature = "internal")]);
    let hide_doc: Attribute = parse_quote!(#[doc(hidden)]);
    let allow_dead_code: Attribute = parse_quote!(#[allow(dead_code)]);
    match &mut item_original {
        Item::Fn(item_fn) => {
            let mut item_fn_modified = item_fn.clone();
            item_fn_modified.vis = syn::Visibility::Public(syn::token::Pub(item_fn.span()));
            item_fn_modified
                .attrs
                .splice(0..0, vec![internal_feature_gate, hide_doc, allow_dead_code]);
            item_modified = Item::Fn(item_fn_modified);
            item_fn.attrs.splice(0..0, vec![not_internal_feature_gate]);
        }
        Item::Struct(item_struct) => {
            let mut item_struct_modified = item_struct.clone();
            item_struct_modified
                .attrs
                .splice(0..0, vec![internal_feature_gate, hide_doc, allow_dead_code]);
            item_struct_modified.vis = syn::Visibility::Public(syn::token::Pub(item_struct.span()));
            item_modified = Item::Struct(item_struct_modified);
            item_struct
                .attrs
                .splice(0..0, vec![not_internal_feature_gate]);
        }
        Item::Type(item_type) => {
            let mut item_type_modified = item_type.clone();
            item_type_modified
                .attrs
                .splice(0..0, vec![internal_feature_gate, hide_doc, allow_dead_code]);
            item_type_modified.vis = syn::Visibility::Public(syn::token::Pub(item_type.span()));
            item_modified = Item::Type(item_type_modified);
            item_type
                .attrs
                .splice(0..0, vec![not_internal_feature_gate]);
        }
        _ => panic!("pub_visibility_if_internal only works with struct, type and fn"),
    }
    let ts: TokenStream = item_original.into_token_stream().into();
    out.extend(ts);
    let ts: TokenStream = item_modified.into_token_stream().into();
    out.extend(ts);
    out
}

// applies zenoh_macros::internal if unstable feature is disabled, otherwise applies zenoh_macros::unstable
#[proc_macro_attribute]
pub fn internal_or_unstable(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
    let mut out = TokenStream::new();
    let mut item_original: syn::Item = syn::parse(tokens).expect("failed to parse input");
    let item_modified;
    let non_unstable_feature_gate: Attribute = parse_quote!(#[cfg(not(feature = "unstable"))]);
    let internal_feature_gate: Attribute = parse_quote!(#[zenoh_macros::internal]);
    let unstable_feature_gate: Attribute = parse_quote!(#[zenoh_macros::unstable]);
    match &mut item_original {
        Item::Fn(item_fn) => {
            let mut item_fn_modified = item_fn.clone();
            item_fn_modified.vis = syn::Visibility::Public(syn::token::Pub(item_fn.span()));
            item_fn_modified
                .attrs
                .splice(0..0, vec![non_unstable_feature_gate, internal_feature_gate]);
            item_modified = Item::Fn(item_fn_modified);
            item_fn.attrs.splice(0..0, vec![unstable_feature_gate]);
        }
        Item::Struct(item_struct) => {
            let mut item_struct_modified = item_struct.clone();
            item_struct_modified
                .attrs
                .splice(0..0, vec![non_unstable_feature_gate, internal_feature_gate]);
            item_struct_modified.vis = syn::Visibility::Public(syn::token::Pub(item_struct.span()));
            item_modified = Item::Struct(item_struct_modified);
            item_struct.attrs.splice(0..0, vec![unstable_feature_gate]);
        }
        Item::Type(item_type) => {
            let mut item_type_modified = item_type.clone();
            item_type_modified
                .attrs
                .splice(0..0, vec![non_unstable_feature_gate, internal_feature_gate]);
            item_type_modified.vis = syn::Visibility::Public(syn::token::Pub(item_type.span()));
            item_modified = Item::Type(item_type_modified);
            item_type.attrs.splice(0..0, vec![unstable_feature_gate]);
        }
        _ => panic!("internal_or_unstable only works with struct, type and fn"),
    }
    let ts: TokenStream = item_original.into_token_stream().into();
    out.extend(ts);
    let ts: TokenStream = item_modified.into_token_stream().into();
    out.extend(ts);
    out
}