wacore-derive 0.3.0

Derive macros for wacore protocol types
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
//! Derive macros for wacore protocol types.
//!
//! This crate provides derive macros for implementing the `ProtocolNode` trait
//! on structs that represent WhatsApp protocol nodes.
//!
//! # Example
//!
//! ```ignore
//! use wacore_derive::{ProtocolNode, StringEnum};
//!
//! /// A query request node.
//! /// Wire format: `<query request="interactive"/>`
//! #[derive(ProtocolNode)]
//! #[protocol(tag = "query")]
//! pub struct QueryRequest {
//!     #[attr(name = "request", default = "interactive")]
//!     pub request_type: String,
//! }
//!
//! /// An enum with string representation.
//! #[derive(StringEnum)]
//! pub enum MemberAddMode {
//!     #[str = "admin_add"]
//!     AdminAdd,
//!     #[str = "all_member_add"]
//!     AllMemberAdd,
//! }
//! ```

use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, parse_macro_input};

/// Derive macro for implementing `ProtocolNode` on structs with attributes.
///
/// # Attributes
///
/// - `#[protocol(tag = "tagname")]` - Required. Specifies the XML tag name.
/// - `#[attr(name = "attrname")]` - Marks a String field as an XML attribute.
/// - `#[attr(name = "attrname", default = "value")]` - Attribute with default value.
///   For `Option<String>` fields, a default always yields `Some(default)`.
/// - `#[attr(name = "attrname", jid)]` - Marks a Jid field as a JID attribute (required).
/// - `#[attr(name = "attrname", jid, optional)]` - Marks an Option<Jid> field as optional.
///
/// # Example
///
/// ```ignore
/// #[derive(ProtocolNode)]
/// #[protocol(tag = "message")]
/// pub struct MessageStanza {
///     #[attr(name = "from", jid)]
///     pub from: Jid,
///     
///     #[attr(name = "to", jid)]
///     pub to: Jid,
///     
///     #[attr(name = "id")]
///     pub id: String,
///     
///     #[attr(name = "sender_lid", jid, optional)]
///     pub sender_lid: Option<Jid>,
/// }
/// ```
#[proc_macro_derive(ProtocolNode, attributes(protocol, attr))]
pub fn derive_protocol_node(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let name = &input.ident;

    let tag = match extract_tag(&input.attrs) {
        Ok(Some(tag)) => tag,
        Ok(None) => {
            return syn::Error::new_spanned(
                &input.ident,
                "ProtocolNode requires #[protocol(tag = \"...\")]",
            )
            .to_compile_error()
            .into();
        }
        Err(e) => return e.to_compile_error().into(),
    };

    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => &fields.named,
            Fields::Unit => return generate_empty_impl(name, &tag).into(),
            _ => {
                return syn::Error::new_spanned(
                    &input.ident,
                    "ProtocolNode only supports named fields or unit structs",
                )
                .to_compile_error()
                .into();
            }
        },
        _ => {
            return syn::Error::new_spanned(
                &input.ident,
                "ProtocolNode can only be derived for structs",
            )
            .to_compile_error()
            .into();
        }
    };

    let mut attr_fields = Vec::new();
    for field in fields {
        match extract_attr_info(field) {
            Ok(Some(attr_info)) => attr_fields.push(attr_info),
            Ok(None) => {}
            Err(e) => return e.to_compile_error().into(),
        }
    }

    let attr_setters: Vec<_> = attr_fields
        .iter()
        .map(|info| {
            let field_ident = &info.field_ident;
            let attr_name = &info.attr_name;

            match (&info.attr_type, info.optional) {
                (AttrType::Jid, true) => {
                    // Option<Jid> - only insert if Some
                    quote! {
                        if let Some(jid) = self.#field_ident {
                            builder = builder.jid_attr(#attr_name, jid);
                        }
                    }
                }
                (AttrType::Jid, false) => {
                    // Required Jid - always insert
                    quote! {
                        builder = builder.jid_attr(#attr_name, self.#field_ident);
                    }
                }
                (AttrType::String, true) => {
                    // Option<String> - only insert if Some
                    quote! {
                        if let Some(s) = self.#field_ident {
                            builder = builder.attr(#attr_name, s);
                        }
                    }
                }
                (AttrType::String, false) => {
                    // Required String - always insert
                    quote! {
                        builder = builder.attr(#attr_name, self.#field_ident);
                    }
                }
            }
        })
        .collect();

    let field_parsers: Vec<_> = attr_fields
        .iter()
        .map(|info| {
            let field_ident = &info.field_ident;
            let attr_name = &info.attr_name;

            match (&info.attr_type, info.optional, &info.default) {
                (AttrType::Jid, false, _) => {
                    // Required Jid
                    quote! {
                        #field_ident: node.attrs().optional_jid(#attr_name)
                            .ok_or_else(|| ::anyhow::anyhow!("missing required attribute '{}'", #attr_name))?
                    }
                }
                (AttrType::Jid, true, _) => {
                    // Optional Jid
                    quote! {
                        #field_ident: node.attrs().optional_jid(#attr_name)
                    }
                }
                (AttrType::String, false, Some(default)) => {
                    // String with default
                    quote! {
                        #field_ident: node.attrs().optional_string(#attr_name)
                            .map(|s| s.to_string())
                            .unwrap_or_else(|| #default.to_string())
                    }
                }
                (AttrType::String, false, None) => {
                    // Required String
                    quote! {
                        #field_ident: node.attrs().required_string(#attr_name)?.to_string()
                    }
                }
                (AttrType::String, true, Some(default)) => {
                    // Optional String with default (always Some)
                    quote! {
                        #field_ident: node.attrs().optional_string(#attr_name)
                            .map(|s| s.to_string())
                            .or_else(|| Some(#default.to_string()))
                    }
                }
                (AttrType::String, true, None) => {
                    // Optional String
                    quote! {
                        #field_ident: node.attrs().optional_string(#attr_name).map(|s| s.to_string())
                    }
                }
            }
        })
        .collect();

    // Only generate Default impl if all fields have defaults or are optional
    let all_have_defaults = attr_fields
        .iter()
        .all(|info| info.default.is_some() || info.optional);

    let default_impl = if all_have_defaults {
        let default_fields: Vec<_> = attr_fields
            .iter()
            .map(|info| {
                let field_ident = &info.field_ident;
                match (&info.attr_type, info.optional, &info.default) {
                    (_, true, Some(default)) => quote! { #field_ident: Some(#default.to_string()) },
                    (_, true, None) => quote! { #field_ident: None },
                    (AttrType::String, false, Some(default)) => {
                        quote! { #field_ident: #default.to_string() }
                    }
                    _ => unreachable!("all_have_defaults check should prevent this branch"),
                }
            })
            .collect();

        quote! {
            impl ::core::default::Default for #name {
                fn default() -> Self {
                    Self {
                        #(#default_fields),*
                    }
                }
            }
        }
    } else {
        quote! {}
    };

    let expanded = quote! {
        impl ::wacore::protocol::ProtocolNode for #name {
            fn tag(&self) -> &'static str {
                #tag
            }

            fn into_node(self) -> ::wacore_binary::node::Node {
                let mut builder = ::wacore_binary::builder::NodeBuilder::new(#tag);
                #(#attr_setters)*
                builder.build()
            }

            fn try_from_node(node: &::wacore_binary::node::Node) -> ::anyhow::Result<Self> {
                if node.tag != #tag {
                    return Err(::anyhow::anyhow!("expected <{}>, got <{}>", #tag, node.tag));
                }
                Ok(Self {
                    #(#field_parsers),*
                })
            }
        }

        #default_impl
    };

    expanded.into()
}

/// Derive macro for empty protocol nodes (tag only, no attributes).
///
/// # Attributes
///
/// - `#[protocol(tag = "tagname")]` - Required. Specifies the XML tag name.
///
/// # Example
///
/// ```ignore
/// #[derive(EmptyNode)]
/// #[protocol(tag = "participants")]
/// pub struct ParticipantsRequest;
/// ```
#[proc_macro_derive(EmptyNode, attributes(protocol))]
pub fn derive_empty_node(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let name = &input.ident;

    let tag = match extract_tag(&input.attrs) {
        Ok(Some(tag)) => tag,
        Ok(None) => {
            return syn::Error::new_spanned(
                &input.ident,
                "EmptyNode requires #[protocol(tag = \"...\")]",
            )
            .to_compile_error()
            .into();
        }
        Err(e) => return e.to_compile_error().into(),
    };

    generate_empty_impl(name, &tag).into()
}

fn generate_empty_impl(name: &syn::Ident, tag: &str) -> proc_macro2::TokenStream {
    quote! {
        impl ::wacore::protocol::ProtocolNode for #name {
            fn tag(&self) -> &'static str {
                #tag
            }

            fn into_node(self) -> ::wacore_binary::node::Node {
                ::wacore_binary::builder::NodeBuilder::new(#tag).build()
            }

            fn try_from_node(node: &::wacore_binary::node::Node) -> ::anyhow::Result<Self> {
                if node.tag != #tag {
                    return Err(::anyhow::anyhow!("expected <{}>, got <{}>", #tag, node.tag));
                }
                Ok(Self)
            }
        }

        impl ::core::default::Default for #name {
            fn default() -> Self {
                Self
            }
        }
    }
}

enum AttrType {
    String,
    Jid,
}

struct AttrFieldInfo {
    field_ident: syn::Ident,
    attr_name: String,
    attr_type: AttrType,
    optional: bool,
    default: Option<String>,
}

fn extract_tag(attrs: &[syn::Attribute]) -> Result<Option<String>, syn::Error> {
    for attr in attrs {
        if attr.path().is_ident("protocol") {
            let mut tag = None;
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("tag") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    tag = Some(value.value());
                }
                Ok(())
            })?;
            if tag.is_some() {
                return Ok(tag);
            }
        }
    }
    Ok(None)
}

fn extract_attr_info(field: &syn::Field) -> Result<Option<AttrFieldInfo>, syn::Error> {
    let field_ident = match field.ident.clone() {
        Some(ident) => ident,
        None => return Ok(None),
    };

    // Check if field type is Option<T>
    let is_optional = is_option_type(&field.ty);

    for attr in &field.attrs {
        if attr.path().is_ident("attr") {
            let mut attr_name = None;
            let mut default = None;
            let mut is_jid = false;
            let mut explicit_optional = false;

            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("name") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    attr_name = Some(value.value());
                } else if meta.path.is_ident("default") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    default = Some(value.value());
                } else if meta.path.is_ident("jid") {
                    is_jid = true;
                } else if meta.path.is_ident("optional") {
                    explicit_optional = true;
                }
                Ok(())
            })?;

            match attr_name {
                Some(name) => {
                    let attr_type = if is_jid {
                        AttrType::Jid
                    } else {
                        AttrType::String
                    };

                    // Determine if optional: either explicit marker or Option<T> type
                    let optional = explicit_optional || is_optional;

                    return Ok(Some(AttrFieldInfo {
                        field_ident,
                        attr_name: name,
                        attr_type,
                        optional,
                        default,
                    }));
                }
                None => {
                    return Err(syn::Error::new_spanned(
                        attr,
                        "missing required `name` in #[attr(...)]",
                    ));
                }
            }
        }
    }
    Ok(None)
}

/// Check if a type is Option<T>
fn is_option_type(ty: &syn::Type) -> bool {
    if let syn::Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
    {
        return segment.ident == "Option";
    }
    false
}

/// Derive macro for enums with string representations.
///
/// Automatically implements:
/// - `as_str(&self) -> &'static str`
/// - `std::fmt::Display`
/// - `TryFrom<&str>`
/// - `Default` (first variant is default, or use `#[string_default]`)
///
/// # Attributes
///
/// - `#[str = "value"]` - Required on each variant. The string representation.
/// - `#[string_default]` - Optional. Marks this variant as the default.
///
/// # Example
///
/// ```ignore
/// #[derive(StringEnum)]
/// pub enum MemberAddMode {
///     #[str = "admin_add"]
///     AdminAdd,
///     #[string_default]
///     #[str = "all_member_add"]
///     AllMemberAdd,
/// }
///
/// assert_eq!(MemberAddMode::AdminAdd.as_str(), "admin_add");
/// assert_eq!(MemberAddMode::try_from("all_member_add").unwrap(), MemberAddMode::AllMemberAdd);
/// ```
#[proc_macro_derive(StringEnum, attributes(str, string_default))]
pub fn derive_string_enum(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let name = &input.ident;

    let variants = match &input.data {
        Data::Enum(data) => &data.variants,
        _ => {
            return syn::Error::new_spanned(
                &input.ident,
                "StringEnum can only be derived for enums",
            )
            .to_compile_error()
            .into();
        }
    };

    let mut variant_infos = Vec::new();
    let mut default_variant = None;
    let mut seen_str_values: std::collections::HashMap<String, syn::Ident> =
        std::collections::HashMap::new();

    for variant in variants {
        let variant_ident = &variant.ident;

        if !matches!(variant.fields, syn::Fields::Unit) {
            return syn::Error::new_spanned(
                variant_ident,
                "StringEnum only supports unit variants",
            )
            .to_compile_error()
            .into();
        }

        let mut str_value = None;
        let mut is_default = false;

        for attr in &variant.attrs {
            if attr.path().is_ident("str") {
                if let syn::Meta::NameValue(nv) = &attr.meta
                    && let syn::Expr::Lit(expr_lit) = &nv.value
                    && let syn::Lit::Str(lit_str) = &expr_lit.lit
                {
                    str_value = Some(lit_str.value());
                }
            } else if attr.path().is_ident("string_default") {
                is_default = true;
            }
        }

        let str_val = match str_value {
            Some(v) => v,
            None => {
                return syn::Error::new_spanned(
                    variant_ident,
                    format!(
                        "StringEnum variant {} requires #[str = \"...\"] attribute",
                        variant_ident
                    ),
                )
                .to_compile_error()
                .into();
            }
        };

        if let Some(prev_variant) = seen_str_values.get(&str_val) {
            return syn::Error::new_spanned(
                variant_ident,
                format!(
                    "duplicate #[str = \"{}\"] value; already used by variant `{}`",
                    str_val, prev_variant
                ),
            )
            .to_compile_error()
            .into();
        }
        seen_str_values.insert(str_val.clone(), variant_ident.clone());

        if is_default {
            if default_variant.is_some() {
                return syn::Error::new_spanned(
                    variant_ident,
                    "Multiple #[string_default] attributes found; only one variant may be the default",
                )
                .to_compile_error()
                .into();
            }
            default_variant = Some(variant_ident.clone());
        }

        variant_infos.push((variant_ident.clone(), str_val));
    }

    // Check for empty enums
    if variant_infos.is_empty() {
        return syn::Error::new_spanned(
            &input.ident,
            "StringEnum cannot be derived for empty enums",
        )
        .to_compile_error()
        .into();
    }

    // If no explicit default, use first variant
    let default_variant = default_variant.unwrap_or_else(|| variant_infos[0].0.clone());

    // Generate as_str() match arms
    let as_str_arms: Vec<_> = variant_infos
        .iter()
        .map(|(ident, str_val)| {
            quote! { #name::#ident => #str_val }
        })
        .collect();

    // Generate TryFrom match arms
    let try_from_arms: Vec<_> = variant_infos
        .iter()
        .map(|(ident, str_val)| {
            quote! { #str_val => Ok(#name::#ident) }
        })
        .collect();

    let expanded = quote! {
        impl #name {
            /// Returns the string representation of this enum variant.
            pub fn as_str(&self) -> &'static str {
                match self {
                    #(#as_str_arms),*
                }
            }
        }

        impl ::core::fmt::Display for #name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                f.write_str(self.as_str())
            }
        }

        impl ::core::convert::TryFrom<&str> for #name {
            type Error = ::anyhow::Error;

            fn try_from(value: &str) -> ::core::result::Result<Self, Self::Error> {
                match value {
                    #(#try_from_arms),*,
                    _ => Err(::anyhow::anyhow!("unknown {}: {}", stringify!(#name), value)),
                }
            }
        }

        impl ::core::default::Default for #name {
            fn default() -> Self {
                #name::#default_variant
            }
        }
    };

    expanded.into()
}