sval_derive_macros 2.19.0

Minimal derive support for `sval`
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
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
/*!
Parsing and validation of `#[sval(...)]` attributes.

Each attribute key (e.g. `tag`, `label`, `index`, `skip`) has a dedicated unit struct implementing the `SvalAttribute` trait.
The trait provides `from_expr()` and `from_lit()` to parse a `syn::Expr` or `syn::Lit` into a typed result.

## Parsing flow

1. `sval_attr()` checks if an attribute's path is `sval`, then iterates its nested meta items, collecting `(Path, Expr)` pairs. Missing values default to `true` (for boolean flags like `#[sval(skip)]`).
2. `check()` validates all keys against a context-specific allowlist and detects duplicates.
3. `get()` retrieves a specific attribute value by key.

Feature-gated attributes (`flatten`, `ref`) return compile errors if used without the corresponding Cargo feature enabled.
*/

use std::collections::HashSet;

use crate::{index::IndexValue, label::LabelValue, lifetime::RefLifetime};
use syn::{spanned::Spanned, Attribute, Expr, ExprUnary, Lit, Path, UnOp};

pub(crate) struct TagAttr;

impl SvalAttribute for TagAttr {
    type Result = syn::Path;

    fn from_expr(&self, expr: &Expr) -> syn::Result<Self::Result> {
        match expr {
            Expr::Lit(lit) => Ok(self.from_lit(&lit.lit)?),
            Expr::Path(path) => Ok(path.path.clone()),
            _ => Err(syn::Error::new(
                expr.span(),
                "invalid `tag`: expected literal or path",
            )),
        }
    }

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Str(s) => s.parse().map_err(|e| {
                let mut r = syn::Error::new(s.span(), "invalid `tag`: expected valid path");
                r.combine(e);

                r
            }),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `tag`: expected string literal",
            )),
        }
    }
}

impl RawAttribute for TagAttr {
    fn key(&self) -> &str {
        "tag"
    }
}

/**
The `data_tag` attribute.

This attribute specifies a path to an `sval::Tag` to use
for the data of the annotated item.
 */
pub(crate) struct DataTagAttr;

impl SvalAttribute for DataTagAttr {
    type Result = syn::Path;

    fn from_expr(&self, expr: &Expr) -> syn::Result<Self::Result> {
        match expr {
            Expr::Lit(lit) => Ok(self.from_lit(&lit.lit)?),
            Expr::Path(path) => Ok(path.path.clone()),
            _ => Err(syn::Error::new(
                expr.span(),
                "invalid `data_tag`: expected literal or path",
            )),
        }
    }

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Str(s) => s.parse().map_err(|e| {
                let mut r = syn::Error::new(s.span(), "invalid `data_tag`: expected valid path");
                r.combine(e);

                r
            }),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `data_tag`: expected string literal",
            )),
        }
    }
}

impl RawAttribute for DataTagAttr {
    fn key(&self) -> &str {
        "data_tag"
    }
}

/**
The `label` attribute.

This attribute specifies an `sval::Label` as a constant
to use for the annotated item.
*/
pub(crate) struct LabelAttr;

impl SvalAttribute for LabelAttr {
    type Result = LabelValue;

    fn from_expr(&self, expr: &Expr) -> syn::Result<Self::Result> {
        match expr {
            Expr::Lit(lit) => Ok(self.from_lit(&lit.lit)?),
            Expr::Path(path) => Ok(LabelValue::Ident(quote!(#path))),
            _ => Err(syn::Error::new(
                expr.span(),
                "invalid `label`: expected literal or path",
            )),
        }
    }

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Str(s) => Ok(LabelValue::Const(s.value())),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `label`: expected string literal",
            )),
        }
    }
}

impl RawAttribute for LabelAttr {
    fn key(&self) -> &str {
        "label"
    }
}

/**
The `index` attribute.

This attribute specifies an `sval::Index` as a constant
to use for the annotated item.
*/
pub(crate) struct IndexAttr;

impl IndexAttr {
    fn const_from_lit(&self, lit: &Lit) -> syn::Result<isize> {
        match lit {
            Lit::Int(n) => n.base10_parse().map_err(|e| {
                let mut r = syn::Error::new(n.span(), "invalid `index`: expected integer");
                r.combine(e);

                r
            }),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `index`: expected integer",
            )),
        }
    }
}

impl SvalAttribute for IndexAttr {
    type Result = IndexValue;

    fn from_expr(&self, expr: &Expr) -> syn::Result<Self::Result> {
        match expr {
            // Take `-` into account
            Expr::Unary(ExprUnary {
                op: UnOp::Neg(_),
                expr: inner_expr,
                ..
            }) => {
                if let Expr::Lit(ref lit) = **inner_expr {
                    Ok(IndexValue::Const(-(self.const_from_lit(&lit.lit)?)))
                } else {
                    Err(syn::Error::new(
                        inner_expr.span(),
                        "invalid `index`: expected integer",
                    ))
                }
            }
            Expr::Lit(lit) => Ok(IndexValue::Const(self.const_from_lit(&lit.lit)?)),
            Expr::Path(path) => Ok(IndexValue::Ident(quote!(#path))),
            _ => Err(syn::Error::new(
                expr.span(),
                "invalid `index`: expected literal, path, or integer",
            )),
        }
    }

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        Ok(IndexValue::Const(self.const_from_lit(lit)?))
    }
}

impl RawAttribute for IndexAttr {
    fn key(&self) -> &str {
        "index"
    }
}

/**
The `skip` attribute.

This attribute signals that an item should be skipped
from streaming.
*/
pub(crate) struct SkipAttr;

impl SvalAttribute for SkipAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `skip`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for SkipAttr {
    fn key(&self) -> &str {
        "skip"
    }
}

/**
The `unlabeled_fields` attribute.

This attribute signals that all fields should be unlabeled.
*/
pub(crate) struct UnlabeledFieldsAttr;

impl SvalAttribute for UnlabeledFieldsAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `unlabeled_fields`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for UnlabeledFieldsAttr {
    fn key(&self) -> &str {
        "unlabeled_fields"
    }
}

/**
The `unindexed_fields` attribute.

This attribute signals that all fields should be unindexed.
*/
pub(crate) struct UnindexedFieldsAttr;

impl SvalAttribute for UnindexedFieldsAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `unindexed_fields`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for UnindexedFieldsAttr {
    fn key(&self) -> &str {
        "unindexed_fields"
    }
}

/**
The `unlabeled_variants` attribute.

This attribute signals that all variants should be unlabeled.
*/
pub(crate) struct UnlabeledVariantsAttr;

impl SvalAttribute for UnlabeledVariantsAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `unlabeled_variants`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for UnlabeledVariantsAttr {
    fn key(&self) -> &str {
        "unlabeled_variants"
    }
}

/**
The `unindexed_variants` attribute.

This attribute signals that all variants should be unindexed.
*/
pub(crate) struct UnindexedVariantsAttr;

impl SvalAttribute for UnindexedVariantsAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `unindexed_variants`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for UnindexedVariantsAttr {
    fn key(&self) -> &str {
        "unindexed_variants"
    }
}

/**
The `dynamic` attribute.

This attribute signals that an enum should be dynamic.
*/
pub(crate) struct DynamicAttr;

impl SvalAttribute for DynamicAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `dynamic`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for DynamicAttr {
    fn key(&self) -> &str {
        "dynamic"
    }
}

/**
The `transparent` attribute.

This attribute signals that a newtype should stream its inner field
without wrapping it in a tag.
*/
pub(crate) struct TransparentAttr;

impl SvalAttribute for TransparentAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) => Ok(b.value),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `transparent`: expected boolean",
            )),
        }
    }
}

impl RawAttribute for TransparentAttr {
    fn key(&self) -> &str {
        "transparent"
    }
}

/**
The `flatten` attribute.

This attribute will flatten the fields of a value onto its parent.
 */
pub(crate) struct FlattenAttr;

impl SvalAttribute for FlattenAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        #[cfg(not(feature = "flatten"))]
        {
            Err(syn::Error::new(
                lit.span(),
                "the `flatten` attribute can only be used when the `flatten` Cargo feature of `sval_derive` is enabled",
            ))
        }
        #[cfg(feature = "flatten")]
        {
            match lit {
                Lit::Bool(b) => Ok(b.value),
                _ => Err(syn::Error::new(
                    lit.span(),
                    "invalid `flatten`: expected boolean",
                )),
            }
        }
    }
}

impl RawAttribute for FlattenAttr {
    fn key(&self) -> &str {
        "flatten"
    }
}

/**
The `ref` attribute for enabling ValueRef derive.
*/
pub(crate) struct RefAttr;

impl SvalAttribute for RefAttr {
    type Result = RefValue;

    fn from_expr(&self, expr: &Expr) -> syn::Result<Self::Result> {
        #[cfg(not(feature = "ref"))]
        {
            Err(syn::Error::new(
                expr.span(),
                "the `ref` attribute requires the `ref` feature of `sval_derive`",
            ))
        }
        #[cfg(feature = "ref")]
        {
            match expr {
                Expr::Lit(lit) => Ok(self.from_lit(&lit.lit)?),
                Expr::Path(_) => Ok(RefValue::Infer),
                _ => Err(syn::Error::new(
                    expr.span(),
                    "invalid `ref`, expected a lifetime or path",
                )),
            }
        }
    }

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        #[cfg(not(feature = "ref"))]
        {
            Err(syn::Error::new(
                lit.span(),
                "the `ref` attribute requires the `ref` feature of `sval_derive`",
            ))
        }
        #[cfg(feature = "ref")]
        {
            match lit {
                Lit::Bool(b) if b.value => Ok(RefValue::Infer),
                Lit::Str(s) => {
                    // Use syn's parser to parse lifetime and optional where clause
                    // Format: "'a" or "'b where 'a: 'b"
                    let spec: RefLifetime = s.parse().map_err(|e| {
                        let mut r = syn::Error::new(
                            s.span(),
                            "invalid `ref`, expected a lifetime such as `'a` or `'b where 'a: 'b`",
                        );
                        r.combine(e);
                        r
                    })?;
                    Ok(RefValue::Explicit(spec))
                }
                _ => Err(syn::Error::new(
                    lit.span(),
                    "invalid `ref`, expected a string literal",
                )),
            }
        }
    }
}

impl RawAttribute for RefAttr {
    fn key(&self) -> &str {
        "ref"
    }
}

/**
Parsed value for the `ref` attribute.
*/
#[derive(Clone)]
#[allow(dead_code)]
pub(crate) enum RefValue {
    /**
    Infer lifetime from the type's single lifetime parameter.
    */
    Infer,
    /**
    Explicit lifetime with optional bounds (e.g., "'a" or "'c: 'a + 'b").
    */
    Explicit(RefLifetime),
}

impl RefValue {
    pub(crate) fn lifetime(&self) -> Option<&RefLifetime> {
        let RefValue::Explicit(spec) = self else {
            return None;
        };

        Some(spec)
    }
}

/**
The `outer_ref` attribute for fields.
*/
pub(crate) struct OuterRefAttr;

impl SvalAttribute for OuterRefAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        #[cfg(not(feature = "ref"))]
        {
            Err(syn::Error::new(
                lit.span(),
                "the `outer_ref` attribute requires the `ref` feature of `sval_derive`",
            ))
        }
        #[cfg(feature = "ref")]
        {
            match lit {
                Lit::Bool(b) if b.value => Ok(true),
                _ => Err(syn::Error::new(
                    lit.span(),
                    "invalid `outer_ref`, expected the boolean value `true`",
                )),
            }
        }
    }
}

impl RawAttribute for OuterRefAttr {
    fn key(&self) -> &str {
        "outer_ref"
    }
}

/**
The `inner_ref` attribute for fields.
*/
pub(crate) struct InnerRefAttr;

impl SvalAttribute for InnerRefAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        #[cfg(not(feature = "ref"))]
        {
            Err(syn::Error::new(
                lit.span(),
                "the `inner_ref` attribute requires the `ref` feature of `sval_derive`",
            ))
        }
        #[cfg(feature = "ref")]
        {
            match lit {
                Lit::Bool(b) if b.value => Ok(true),
                _ => Err(syn::Error::new(
                    lit.span(),
                    "invalid `inner_ref`, expected the boolean value `true`",
                )),
            }
        }
    }
}

impl RawAttribute for InnerRefAttr {
    fn key(&self) -> &str {
        "inner_ref"
    }
}

/**
The `computed` attribute for fields.
*/
pub(crate) struct ComputedAttr;

impl SvalAttribute for ComputedAttr {
    type Result = bool;

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result> {
        match lit {
            Lit::Bool(b) if b.value => Ok(true),
            _ => Err(syn::Error::new(
                lit.span(),
                "invalid `computed`: expected boolean value `true`",
            )),
        }
    }
}

impl RawAttribute for ComputedAttr {
    fn key(&self) -> &str {
        "computed"
    }
}

pub(crate) trait RawAttribute {
    fn key(&self) -> &str;
}

pub(crate) trait SvalAttribute: RawAttribute {
    type Result: 'static;

    fn from_expr(&self, expr: &Expr) -> syn::Result<Self::Result> {
        if let Expr::Lit(lit) = expr {
            Ok(self.from_lit(&lit.lit)?)
        } else {
            Err(syn::Error::new(
                expr.span(),
                format_args!("invalid {}: expected literal", self.key()),
            ))
        }
    }

    fn from_lit(&self, lit: &Lit) -> syn::Result<Self::Result>;
}

pub(crate) fn ensure_empty(ctxt: &str, attrs: &[Attribute]) -> syn::Result<()> {
    // Just ensure the attribute list is empty
    for attr in attrs {
        let Some(meta) = sval_attr(ctxt, attr)? else {
            continue;
        };

        for (value_key, _) in meta {
            return Err(syn::Error::new(
                value_key.span(),
                format_args!("unsupported attribute `{}` on {}", quote!(#value_key), ctxt),
            ));
        }
    }

    Ok(())
}

pub(crate) fn ensure_missing<T: SvalAttribute>(
    ctxt: &str,
    request: T,
    attrs: &[Attribute],
) -> syn::Result<()> {
    let key = request.key().to_owned();

    if let Some((unexpected, _)) = find(ctxt, request.key(), attrs)? {
        return Err(syn::Error::new(
            unexpected.span(),
            format_args!("unsupported attribute `{}` on {}", key, ctxt),
        ));
    }

    Ok(())
}

/**
Check the set of attributes, failing if any are duplicated, or aren't known or supported by the derive context.
*/
pub(crate) fn check(
    ctxt: &str,
    allowed: &[&dyn RawAttribute],
    attrs: &[Attribute],
) -> syn::Result<()> {
    let mut seen = HashSet::new();

    for attr in attrs {
        let Some(meta) = sval_attr(ctxt, attr)? else {
            continue;
        };

        for (value_key, _) in meta {
            let mut is_valid_attr = false;

            for allowed in allowed {
                let attr_key = allowed.key();

                if value_key.is_ident(attr_key) {
                    is_valid_attr = true;

                    if !seen.insert(attr_key) {
                        return Err(syn::Error::new(
                            value_key.span(),
                            format_args!(
                                "duplicate attribute `{}` on {}",
                                quote!(#value_key),
                                ctxt
                            ),
                        ));
                    }
                }
            }

            if !is_valid_attr {
                return Err(syn::Error::new(
                    value_key.span(),
                    format_args!("unsupported attribute `{}` on {}", quote!(#value_key), ctxt),
                ));
            }
        }
    }

    Ok(())
}

/**
Get the value of an attribute, without checking the set itself for validity.

This function will still fail if the requested attribute is invalid, but won't handle duplicates, which are expected to have been caught by an earlier call to `check`.
*/
pub(crate) fn get<T: SvalAttribute>(
    ctxt: &str,
    request: T,
    attrs: &[Attribute],
) -> syn::Result<Option<T::Result>> {
    let Some((_, value)) = find(ctxt, request.key(), attrs)? else {
        return Ok(None);
    };

    Ok(Some(request.from_expr(&value)?))
}

fn find(ctxt: &str, request_key: &str, attrs: &[Attribute]) -> syn::Result<Option<(Path, Expr)>> {
    for attr in attrs {
        let Some(meta) = sval_attr(ctxt, attr)? else {
            continue;
        };

        for (value_key, value) in meta {
            if value_key.is_ident(request_key) {
                return Ok(Some((value_key, value)));
            }
        }
    }

    Ok(None)
}

fn sval_attr<'a>(
    ctxt: &'a str,
    attr: &'_ Attribute,
) -> syn::Result<Option<impl IntoIterator<Item = (Path, Expr)> + 'a>> {
    if !attr.path().is_ident("sval") {
        return Ok(None);
    }

    let mut results = Vec::new();
    attr.parse_nested_meta(|meta| {
        let expr: Expr = match meta.value() {
            Ok(value) => value.parse()?,
            // If there isn't a value associated with the item
            // then use the boolean `true`
            Err(_) => syn::parse_quote!(true),
        };

        let path = meta.path;

        results.push((path, expr));

        Ok(())
    })
    .map_err(|e| {
        let mut r = syn::Error::new(
            attr.span(),
            format_args!("failed to parse attribute on {ctxt}"),
        );
        r.combine(e);

        r
    })?;

    Ok(Some(results))
}