protto_derive 0.6.1

Automatically derive Protobuf and Rust conversions.
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
use crate::analysis::optionality::FieldOptionality;
use crate::constants;
use quote::quote;
use syn::parse::Parser;
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{Attribute, Expr, Field, Lit, Meta};

#[derive(Debug, Default, Clone)]
pub struct ProtoFieldMeta {
    pub expect: bool,
    pub error_fn: Option<String>,
    pub error_type: Option<String>,
    pub default_fn: Option<String>,
    pub optionality: Option<FieldOptionality>,
    pub from_proto_fn: Option<String>,
    pub to_proto_fn: Option<String>,
}

impl ProtoFieldMeta {
    pub fn from_field(field: &syn::Field) -> Result<Self, String> {
        let mut meta = ProtoFieldMeta::default();
        let field_name = field
            .ident
            .as_ref()
            .map(|i| i.to_string())
            .unwrap_or_else(|| "unknown".to_string());

        for attr in &field.attrs {
            if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
                && let Meta::List(meta_list) = &attr.meta
            {
                let nested_metas: Result<Punctuated<Meta, Comma>, _> =
                    Punctuated::parse_terminated.parse2(meta_list.tokens.clone());

                match nested_metas {
                    Ok(metas) => {
                        for nested_meta in metas {
                            match nested_meta {
                                Meta::Path(path) if path.is_ident("expect") => {
                                    meta.expect = true;
                                }
                                Meta::List(list) if list.path.is_ident("expect") => {
                                    // handle `expect(panic)` syntax
                                    meta.expect = true;
                                }

                                Meta::Path(path) if path.is_ident("proto_optional") => {
                                    if meta.optionality.is_some() {
                                        return Err(
                                            "Cannot specify both proto_optional and proto_required"
                                                .to_string(),
                                        );
                                    }
                                    meta.optionality = Some(FieldOptionality::Optional);
                                }
                                Meta::Path(path) if path.is_ident("proto_required") => {
                                    if meta.optionality.is_some() {
                                        return Err(
                                            "Cannot specify both proto_optional and proto_required"
                                                .to_string(),
                                        );
                                    }
                                    meta.optionality = Some(FieldOptionality::Required);
                                }

                                Meta::NameValue(nv) if nv.path.is_ident("error_type") => {
                                    if let Expr::Path(expr_path) = &nv.value {
                                        meta.error_type = Some(quote!(#expr_path).to_string());
                                    }
                                }
                                Meta::NameValue(nv) if nv.path.is_ident("error_fn") => {
                                    match parse_function_value(&nv.value, "error_fn", &field_name) {
                                        Ok(fn_name) => meta.error_fn = Some(fn_name),
                                        Err(err_msg) => return Err(err_msg),
                                    }
                                }

                                Meta::NameValue(nv) if nv.path.is_ident("default") => {
                                    if meta.default_fn.is_some() {
                                        return Err(format!(
                                            "Field '{}': Cannot specify both 'default' and 'default_fn'. \
                                                Use 'default = \"function_name\"' for custom default functions.",
                                            field_name
                                        ));
                                    }
                                    match &nv.value {
                                        Expr::Lit(expr_lit) => {
                                            if let Lit::Str(lit_str) = &expr_lit.lit {
                                                let fn_name = lit_str.value();
                                                meta.default_fn = Some(fn_name);
                                            }
                                        }
                                        Expr::Path(expr_path) => {
                                            let fn_name = quote!(#expr_path).to_string();
                                            meta.default_fn = Some(fn_name);
                                        }
                                        _ => {
                                            return Err(format!(
                                                "Field '{}': default value must be a string literal or path. \
                                                    Examples: default = \"my_function\" or default = my_function",
                                                field_name
                                            ));
                                        }
                                    }
                                }
                                Meta::NameValue(nv) if nv.path.is_ident("default_fn") => {
                                    if meta.default_fn.is_some() {
                                        return Err(format!(
                                            "Field '{}': Cannot specify both 'default' and 'default_fn'. \
                                                Use 'default = \"function_name\"' instead.",
                                            field_name
                                        ));
                                    }
                                    match &nv.value {
                                        Expr::Lit(expr_lit) => {
                                            if let Lit::Str(lit_str) = &expr_lit.lit {
                                                let fn_name = lit_str.value();
                                                meta.default_fn = Some(fn_name);
                                            }
                                        }
                                        Expr::Path(expr_path) => {
                                            let fn_name = quote!(#expr_path).to_string();
                                            meta.default_fn = Some(fn_name);
                                        }
                                        _ => {
                                            return Err(format!(
                                                "Field '{}': default_fn value must be a string literal or path. \
                                                    Examples: default_fn = \"my_function\" or default_fn = my_function",
                                                field_name
                                            ));
                                        }
                                    }
                                }
                                // Handle bare 'default' to use Default::default - add to separate field
                                Meta::Path(path) if path.is_ident("default") => {
                                    if meta.default_fn.is_some() {
                                        return Err(format!(
                                            "Field '{}': Cannot specify both 'default' and 'default_fn'. \
                                                Use 'default' for Default::default() or 'default_fn = \"function\"' for custom functions.",
                                            field_name
                                        ));
                                    }
                                    // Use a special marker to distinguish from custom default_fn
                                    meta.default_fn = Some(constants::USE_DEFAULT_IMPL.to_string());
                                }
                                Meta::Path(path) if path.is_ident("default_fn") => {
                                    return Err(format!(
                                        "Field '{}': 'default_fn' requires a value. \
                                            Use 'default_fn = \"function_name\"' or 'default = \"function_name\"'.",
                                        field_name
                                    ));
                                }

                                Meta::NameValue(nv) if nv.path.is_ident("from_proto_fn") => {
                                    match parse_function_value(
                                        &nv.value,
                                        "from_proto_fn",
                                        &field_name,
                                    ) {
                                        Ok(fn_name) => meta.from_proto_fn = Some(fn_name),
                                        Err(err_msg) => return Err(err_msg),
                                    }
                                }

                                Meta::NameValue(nv) if nv.path.is_ident("to_proto_fn") => {
                                    match parse_function_value(
                                        &nv.value,
                                        "to_proto_fn",
                                        &field_name,
                                    ) {
                                        Ok(fn_name) => meta.to_proto_fn = Some(fn_name),
                                        Err(err_msg) => return Err(err_msg),
                                    }
                                }

                                _ => {
                                    // ignore other attributes for now
                                }
                            }
                        }
                    }
                    Err(e) => {
                        return Err(format!(
                            "Failed to parse {} attribute: {e}",
                            constants::PROTTO_ATTRIBUTE
                        ));
                    }
                }
            }
        }

        Ok(meta)
    }

    /// Get the explicit proto optionality flag if present
    #[allow(unused)]
    pub fn get_proto_optionality(&self) -> Option<&FieldOptionality> {
        self.optionality.as_ref()
    }

    /// Check if this field is explicitly marked as proto optional
    #[allow(unused)]
    pub fn is_proto_optional(&self) -> bool {
        self.optionality.map(|o| o.is_optional()).unwrap_or(false)
    }

    /// Check if this field is explicitly marked as proto required
    #[allow(unused)]
    pub fn is_proto_required(&self) -> bool {
        self.optionality.map(|o| o.is_required()).unwrap_or(false)
    }

    /// Check if any explicit optionality annotation is present
    pub fn has_explicit_optionality(&self) -> bool {
        self.optionality.is_some()
    }

    /// Get the proto-to-rust conversion function if specified
    pub fn get_proto_to_rust_fn(&self) -> Option<&str> {
        self.from_proto_fn.as_deref()
    }

    /// Get the rust-to-proto conversion function if specified
    pub fn get_rust_to_proto_fn(&self) -> Option<&str> {
        self.to_proto_fn.as_deref()
    }

    /// Check if bidirectional custom conversion is specified
    #[allow(unused)]
    pub fn has_bidirectional_conversion(&self) -> bool {
        self.from_proto_fn.is_some() && self.to_proto_fn.is_some()
    }

    /// Check if any custom conversion function is specified
    #[allow(unused)]
    pub fn has_custom_conversion(&self) -> bool {
        self.from_proto_fn.is_some() || self.to_proto_fn.is_some()
    }
}

pub fn get_proto_struct_error_type(attrs: &[Attribute]) -> Option<syn::Type> {
    for attr in attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {}",
                        constants::PROTTO_ATTRIBUTE,
                        e
                    )
                });
            for meta in nested_metas {
                if let Meta::NameValue(meta_nv) = meta
                    && meta_nv.path.is_ident("error_type")
                {
                    if let Expr::Path(expr_path) = &meta_nv.value {
                        return Some(syn::Type::Path(syn::TypePath {
                            qself: None,
                            path: expr_path.path.clone(),
                        }));
                    }
                    panic!(
                        "error_type value must be a type path; e.g., #[{}(error_type = MyError)]",
                        constants::PROTTO_ATTRIBUTE
                    );
                }
            }
        }
    }
    None
}

pub fn get_struct_level_error_fn(attrs: &[Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {e}",
                        constants::PROTTO_ATTRIBUTE
                    )
                });
            for meta in nested_metas {
                if let Meta::NameValue(meta_nv) = meta
                    && meta_nv.path.is_ident("error_fn")
                {
                    match &meta_nv.value {
                        Expr::Lit(expr_lit) => {
                            if let Lit::Str(lit_str) = &expr_lit.lit {
                                return Some(lit_str.value());
                            }
                        }
                        Expr::Path(expr_path) => {
                            return Some(quote!(#expr_path).to_string());
                        }
                        _ => {
                            panic!(
                                "error_fn value must be a string literal or path. \
                                Examples: error_fn = \"my_function\" or error_fn = my_function"
                            );
                        }
                    }
                }
            }
        }
    }
    None
}

pub fn validate_error_configuration(
    struct_level_error_type: &Option<syn::Type>,
    struct_level_error_fn: &Option<String>,
    fields: &syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
) -> Result<(), String> {
    if struct_level_error_type.is_some() {
        // Check if any field uses expect without error_fn
        let mut fields_needing_fallback = Vec::new();

        for field in fields {
            // DMR_3: Check for expect attribute directly without ProtoFieldMeta
            let has_expect = field.attrs.iter().any(|attr| {
                if attr.path().is_ident(constants::PROTTO_ATTRIBUTE) {
                    if let Meta::List(meta_list) = &attr.meta {
                        let tokens_str = meta_list.tokens.to_string();
                        tokens_str.contains("expect")
                    } else {
                        false
                    }
                } else {
                    false
                }
            });

            // DMR_3: Check for error_fn attribute directly
            let has_error_fn = field.attrs.iter().any(|attr| {
                if attr.path().is_ident(constants::PROTTO_ATTRIBUTE) {
                    if let Meta::List(meta_list) = &attr.meta {
                        let tokens_str = meta_list.tokens.to_string();
                        tokens_str.contains("error_fn")
                    } else {
                        false
                    }
                } else {
                    false
                }
            });

            if has_expect && !has_error_fn {
                fields_needing_fallback.push(field.ident.as_ref().unwrap().to_string());
            }
        }

        if !fields_needing_fallback.is_empty() && struct_level_error_fn.is_none() {
            return Err(format!(
                "When 'error_type' is specified, fields with 'expect' but no 'error_fn' require \
                a struct-level 'error_fn' as fallback. Fields needing fallback: {}. \
                Add: #[protto(error_fn = \"YourErrorType::missing_field\")]",
                fields_needing_fallback.join(", ")
            ));
        }
    }

    Ok(())
}

/// Parse struct-level `ignore` attribute
/// Returns a HashSet of field names to ignore during proto generation
pub fn get_struct_level_proto_ignore(attrs: &[Attribute]) -> std::collections::HashSet<String> {
    let mut ignored_fields = std::collections::HashSet::new();

    for attr in attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {e}",
                        constants::PROTTO_ATTRIBUTE
                    )
                });

            for meta in nested_metas {
                if let Meta::NameValue(meta_nv) = meta
                    && meta_nv.path.is_ident("ignore")
                {
                    if let Expr::Lit(expr_lit) = &meta_nv.value
                        && let Lit::Str(lit_str) = &expr_lit.lit
                    {
                        // Parse comma-separated field names
                        let field_names = lit_str.value();
                        for field_name in field_names.split(',') {
                            let trimmed = field_name.trim();
                            if !trimmed.is_empty() {
                                ignored_fields.insert(trimmed.to_string());
                            }
                        }
                    } else {
                        panic!(
                            "ignore value must be a string literal with comma-separated field names, \
                            e.g., #[{}(ignore = \"field1, field2\")]",
                            constants::PROTTO_ATTRIBUTE
                        );
                    }
                }
            }
        }
    }

    ignored_fields
}

pub fn get_proto_module(attrs: &[Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {e}",
                        constants::PROTTO_ATTRIBUTE
                    )
                });
            for meta in nested_metas {
                if let Meta::NameValue(meta_nv) = meta
                    && meta_nv.path.is_ident("module")
                {
                    if let Expr::Lit(expr_lit) = meta_nv.value
                        && let Lit::Str(lit_str) = expr_lit.lit
                    {
                        return Some(lit_str.value());
                    }
                    panic!(
                        "module value must be a string literal, e.g., #[{}(module = \"path\")]",
                        constants::PROTTO_ATTRIBUTE
                    );
                }
            }
        }
    }
    None
}

pub fn get_proto_struct_name(attrs: &[Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {e}",
                        constants::PROTTO_ATTRIBUTE
                    )
                });
            for meta in nested_metas {
                if let Meta::NameValue(meta_nv) = meta
                    && meta_nv.path.is_ident("proto_name")
                {
                    if let Expr::Lit(expr_lit) = meta_nv.value
                        && let Lit::Str(lit_str) = expr_lit.lit
                    {
                        return Some(lit_str.value());
                    }
                    panic!(
                        "proto_name value must be a string literal, e.g., #[{}(proto_name = \"...\")]",
                        constants::PROTTO_ATTRIBUTE
                    );
                }
            }
        }
    }
    None
}

pub fn has_transparent_attr(field: &Field) -> bool {
    for attr in &field.attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            // Parse the nested metas properly instead of string searching
            let nested_metas: Result<Punctuated<Meta, Comma>, _> =
                Punctuated::parse_terminated.parse2(meta_list.tokens.clone());

            if let Ok(metas) = nested_metas {
                for nested_meta in metas {
                    match nested_meta {
                        // Only match actual transparent attribute, not values containing "transparent"
                        Meta::Path(path) if path.is_ident("transparent") => {
                            return true;
                        }
                        Meta::NameValue(nv) if nv.path.is_ident("transparent") => {
                            // Handle transparent = true/false
                            if let Expr::Lit(expr_lit) = &nv.value
                                && let Lit::Bool(lit_bool) = &expr_lit.lit
                            {
                                return lit_bool.value;
                            }

                            return true; // Default to true if not a boolean
                        }
                        _ => {} // Ignore other attributes
                    }
                }
            }
        }
    }
    false
}

pub fn get_proto_field_name(field: &Field) -> Option<String> {
    for attr in &field.attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {e}",
                        constants::PROTTO_ATTRIBUTE
                    )
                });
            for meta in nested_metas {
                if let Meta::NameValue(meta_nv) = meta
                    && meta_nv.path.is_ident("proto_name")
                {
                    if let Expr::Lit(expr_lit) = &meta_nv.value
                        && let Lit::Str(lit_str) = &expr_lit.lit
                    {
                        return Some(lit_str.value());
                    }
                    panic!(
                        "proto_name value must be a string literal, e.g., proto_name = \"field_name\""
                    );
                }
            }
        }
    }
    None
}

pub fn has_proto_ignore(field: &Field) -> bool {
    for attr in &field.attrs {
        if attr.path().is_ident(constants::PROTTO_ATTRIBUTE)
            && let Meta::List(meta_list) = &attr.meta
        {
            let nested_metas: Punctuated<Meta, Comma> = Punctuated::parse_terminated
                .parse2(meta_list.tokens.clone())
                .unwrap_or_else(|e| {
                    panic!(
                        "Failed to parse {} attribute: {e}",
                        constants::PROTTO_ATTRIBUTE
                    )
                });
            for meta in nested_metas {
                if let Meta::Path(path) = meta
                    && path.is_ident("ignore")
                {
                    return true;
                }
            }
        }
    }
    false
}

fn parse_function_value(value: &Expr, attr_name: &str, field_name: &str) -> Result<String, String> {
    match value {
        Expr::Lit(expr_lit) => {
            if let Lit::Str(lit_str) = &expr_lit.lit {
                Ok(lit_str.value())
            } else {
                Err(format!(
                    "Field '{}': {} value must be a string literal or path. \
                    Examples: {} = \"my_function\" or {} = my_function",
                    field_name, attr_name, attr_name, attr_name
                ))
            }
        }
        Expr::Path(expr_path) => Ok(quote!(#expr_path).to_string()),
        _ => Err(format!(
            "Field '{}': {} value must be a string literal or path. \
                Examples: {} = \"my_function\" or {} = my_function",
            field_name, attr_name, attr_name, attr_name
        )),
    }
}