miden-node-tracing-macro 0.16.0

Procedural macros for Miden node tracing
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
use std::collections::BTreeSet;

use proc_macro::TokenStream;
use proc_macro2::{Delimiter, Group, TokenStream as TokenStream2, TokenTree};
use quote::{ToTokens, quote};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::Dot;
use syn::visit::Visit;
use syn::{
    Attribute,
    Block,
    Expr,
    Ident,
    ItemFn,
    LitStr,
    Macro,
    Meta,
    Result,
    Token,
    parse_macro_input,
    parse_quote,
};

/// Instruments a function using canonical tracing attributes.
///
/// Field values must implement `RecordAttribute`, and their names must be registered for the value
/// type. A field whose name ends in `.count` accepts any `usize` without registration. Append
/// `#[nonstandard]` to any other field value to permit an unregistered name while retaining its
/// canonical encoding.
#[proc_macro_attribute]
pub fn miden_instrument(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = match rewrite_explicit_fields(TokenStream2::from(attr)) {
        Ok(attr) => attr,
        Err(error) => return error.into_compile_error().into(),
    };
    let mut function = parse_macro_input!(item as ItemFn);
    let fields = collect_recorded_fields(&function);
    let args = match merge_inferred_fields(attr, &fields) {
        Ok(args) => args,
        Err(error) => return error.into_compile_error().into(),
    };
    let statements = &function.block.stmts;
    let block: Block = parse_quote! {{
        #[allow(unused_macros)]
        macro_rules! __miden_span_record_must_be_used_within_miden_instrument {
            () => {};
        }

        #(#statements)*
    }};
    *function.block = block;

    let expanded = quote! {
        #[::miden_node_tracing::__private::instrument(#args)]
        #function
    };

    expanded.into()
}

/// Emits a trace-level event.
///
/// An optional first argument may provide an error implementing `ErrorReport`. Its display value
/// and source chain are recorded as `exception.message`; callers do not provide that attribute
/// themselves.
///
/// The event name is required and must be a string literal. When an error is provided, optional
/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
/// error, they precede the name. Attributes follow the name and must use a registered field name
/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
/// trailing commas are not supported.
///
/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
/// as the event name.
///
/// ```rust,ignore
/// use miden_node_tracing::trace;
///
/// trace!(target: "node", "block.received", block.number = 42_u32);
///
/// let source = std::io::Error::other("invalid block");
/// trace!(&source, "block.rejected", block.number = 42_u32);
/// ```
#[proc_macro]
pub fn trace(input: TokenStream) -> TokenStream {
    expand_event(input, "trace", false)
}

/// Emits a debug-level event.
///
/// An optional first argument may provide an error implementing `ErrorReport`. Its display value
/// and source chain are recorded as `exception.message`; callers do not provide that attribute
/// themselves.
///
/// The event name is required and must be a string literal. When an error is provided, optional
/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
/// error, they precede the name. Attributes follow the name and must use a registered field name
/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
/// trailing commas are not supported.
///
/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
/// as the event name.
///
/// ```rust,ignore
/// use miden_node_tracing::debug;
///
/// debug!("block.queued", block.number = 42_u32);
///
/// let source = std::io::Error::other("upstream unavailable");
/// debug!(&source, "block.retrying", block.number = 42_u32);
/// ```
#[proc_macro]
pub fn debug(input: TokenStream) -> TokenStream {
    expand_event(input, "debug", false)
}

/// Emits an info-level event.
///
/// An optional first argument may provide an error implementing `ErrorReport`. Its display value
/// and source chain are recorded as `exception.message`; callers do not provide that attribute
/// themselves.
///
/// The event name is required and must be a string literal. When an error is provided, optional
/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
/// error, they precede the name. Attributes follow the name and must use a registered field name
/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
/// trailing commas are not supported.
///
/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
/// as the event name.
///
/// ```rust,ignore
/// use miden_node_tracing::info;
///
/// let parent = tracing::info_span!("block");
/// info!(parent: &parent, "block.accepted", block.number = 42_u32);
///
/// let source = std::io::Error::other("used fallback");
/// info!(&source, "block.fallback_used", block.number = 42_u32);
/// ```
#[proc_macro]
pub fn info(input: TokenStream) -> TokenStream {
    expand_event(input, "info", false)
}

/// Emits a warning-level event.
///
/// An optional first argument may provide an error implementing `ErrorReport`. Its display value
/// and source chain are recorded as `exception.message`; callers do not provide that attribute
/// themselves.
///
/// The event name is required and must be a string literal. When an error is provided, optional
/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
/// error, they precede the name. Attributes follow the name and must use a registered field name
/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
/// trailing commas are not supported.
///
/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
/// as the event name.
///
/// ```rust,ignore
/// use miden_node_tracing::warn;
///
/// warn!("block.delayed", block.number = 42_u32);
///
/// let source = std::io::Error::other("upstream unavailable");
/// warn!(&source, "block.retrying", block.number = 42_u32);
/// ```
#[proc_macro]
pub fn warn(input: TokenStream) -> TokenStream {
    expand_event(input, "warn", false)
}

/// Emits an error-level event with a complete error report.
///
/// The first argument is required and must implement `ErrorReport`. Its display value and source
/// chain are recorded as `exception.message`; callers do not provide that attribute themselves.
///
/// The event name follows the error and must be a string literal. Optional `target:` and `parent:`
/// arguments go between the error and name, in that order. Additional attributes follow the name
/// and must use a registered field name and a value implementing `RecordAttribute`. Append
/// `#[nonstandard]` to a field value to permit an unregistered name while retaining its canonical
/// encoding. Tracing format specifiers and trailing commas are not supported.
///
/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
/// as the event name.
///
/// ```rust,ignore
/// use miden_node_tracing::error;
///
/// let source = std::io::Error::other("database unavailable");
/// error!(source, target: "node", "block.store_failed", block.number = 42_u32);
/// ```
#[proc_macro]
pub fn error(input: TokenStream) -> TokenStream {
    expand_event(input, "error", true)
}

fn expand_event(input: TokenStream, level: &str, error_required: bool) -> TokenStream {
    let event = if error_required {
        syn::parse::<ErrorEvent>(input).map(|event| event.0)
    } else {
        syn::parse::<OptionalErrorEvent>(input).map(|event| event.0)
    };
    let event = match event {
        Ok(event) => event,
        Err(error) => return error.into_compile_error().into(),
    };

    event.tokens(&Ident::new(level, proc_macro2::Span::call_site())).into()
}

struct ErrorEvent(Event);

impl Parse for ErrorEvent {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let event = parse_error_event(input)?;
        event.reject_exception_message()?;

        Ok(Self(event))
    }
}

struct OptionalErrorEvent(Event);

impl Parse for OptionalErrorEvent {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let event = if starts_without_error(input) {
            Event::parse_after_error(input, None)?
        } else {
            parse_error_event(input)?
        };
        event.reject_exception_message()?;

        Ok(Self(event))
    }
}

fn parse_error_event(input: ParseStream<'_>) -> Result<Event> {
    if input.is_empty() {
        return Err(input.error("expected an error expression"));
    }

    let error = input.parse()?;
    if input.is_empty() {
        return Err(syn::Error::new_spanned(error, "expected a static event name string literal"));
    }
    input.parse::<Token![,]>()?;

    Event::parse_after_error(input, Some(error))
}

struct Event {
    error: Option<Expr>,
    target: Option<Expr>,
    parent: Option<Expr>,
    name: LitStr,
    fields: Vec<RecordField>,
}

impl Event {
    fn parse_after_error(input: ParseStream<'_>, error: Option<Expr>) -> Result<Self> {
        let target = if input.peek(event_kw::target) {
            input.parse::<event_kw::target>()?;
            input.parse::<Token![:]>()?;
            let target = input.parse()?;
            input.parse::<Token![,]>()?;
            Some(target)
        } else {
            None
        };

        let parent = if input.peek(event_kw::parent) {
            input.parse::<event_kw::parent>()?;
            input.parse::<Token![:]>()?;
            let parent = input.parse()?;
            input.parse::<Token![,]>()?;
            Some(parent)
        } else {
            None
        };

        let name = input
            .parse::<LitStr>()
            .map_err(|_| input.error("expected a static event name string literal"))?;
        let mut fields = Vec::new();

        if !input.is_empty() {
            let comma = input.parse::<Token![,]>()?;
            if input.is_empty() {
                return Err(syn::Error::new_spanned(comma, "trailing commas are not supported"));
            }

            loop {
                fields.push(RecordField::parse(input, true)?);
                if input.is_empty() {
                    break;
                }

                let comma = input.parse::<Token![,]>()?;
                if input.is_empty() {
                    return Err(syn::Error::new_spanned(
                        comma,
                        "trailing commas are not supported",
                    ));
                }
            }
        }

        Ok(Self { error, target, parent, name, fields })
    }

    fn reject_exception_message(&self) -> Result<()> {
        if let Some(field) =
            self.fields.iter().find(|field| field.path.name() == "exception.message")
        {
            Err(syn::Error::new_spanned(
                &field.path,
                "pass the error as the first argument instead of recording `exception.message`",
            ))
        } else {
            Ok(())
        }
    }

    fn tokens(&self, level: &Ident) -> TokenStream2 {
        let target = self.target.as_ref().map(|target| quote! { target: #target, });
        let parent = self.parent.as_ref().map(|parent| quote! { parent: #parent, });
        let name = &self.name;
        let error = self.error.as_ref().map(|error| {
            quote! {
                , exception.message = ::miden_node_tracing::record_attribute(
                    &({
                        use ::miden_node_tracing::ErrorReport as _;
                        (#error).as_report()
                    })
                )
            }
        });
        let fields = self.fields.iter().map(RecordField::instrument_tokens);

        quote! {
            ::miden_node_tracing::__private::#level!(
                #target
                #parent
                message = #name
                #error
                #(, #fields)*
            )
        }
    }
}

mod event_kw {
    syn::custom_keyword!(parent);
    syn::custom_keyword!(target);
}

fn starts_without_error(input: ParseStream<'_>) -> bool {
    if input.peek(LitStr) {
        return true;
    }

    let ahead = input.fork();
    let starts_with_target =
        ahead.parse::<event_kw::target>().is_ok() && ahead.parse::<Token![:]>().is_ok();
    if starts_with_target {
        return true;
    }

    let ahead = input.fork();
    ahead.parse::<event_kw::parent>().is_ok() && ahead.parse::<Token![:]>().is_ok()
}

fn merge_inferred_fields(attr: TokenStream2, fields: &[FieldPath]) -> Result<TokenStream2> {
    let mut args = split_top_level_args(attr);
    reject_skip_directives(&args)?;

    // Function arguments often contain large or sensitive values. Always skip them so spans only
    // contain fields explicitly declared by the caller or inferred from `miden_span_record!`.
    args.push(quote! { skip_all });

    if fields.is_empty() {
        return Ok(quote! { #(#args),* });
    }

    let inferred_fields = quote! { #(#fields = ::miden_node_tracing::field::Empty),* };
    let mut merged_existing_fields = false;
    let args = args
        .into_iter()
        .map(|arg| {
            if let Some(group) = fields_group(&arg) {
                merged_existing_fields = true;
                let existing_fields = group.stream();
                let merged_fields = if existing_fields.is_empty() {
                    inferred_fields.clone()
                } else if ends_with_comma(&existing_fields) {
                    quote! { #existing_fields #inferred_fields }
                } else {
                    quote! { #existing_fields, #inferred_fields }
                };
                let mut merged_group = Group::new(Delimiter::Parenthesis, merged_fields);
                merged_group.set_span(group.span());
                quote! { fields #merged_group }
            } else {
                arg
            }
        })
        .collect::<Vec<_>>();

    if merged_existing_fields {
        Ok(quote! { #(#args),* })
    } else {
        Ok(quote! { #(#args,)* fields(#inferred_fields) })
    }
}

fn reject_skip_directives(args: &[TokenStream2]) -> Result<()> {
    for arg in args {
        let Some(TokenTree::Ident(ident)) = arg.clone().into_iter().next() else {
            continue;
        };
        if ident == "skip" || ident == "skip_all" {
            return Err(syn::Error::new_spanned(
                arg,
                format!(
                    "`{ident}` is not supported by `miden_instrument`; function arguments are \
                     always skipped, record fields explicitly with `fields(...)`"
                ),
            ));
        }
    }

    Ok(())
}

fn rewrite_explicit_fields(attr: TokenStream2) -> Result<TokenStream2> {
    let args = split_top_level_args(attr)
        .into_iter()
        .map(|arg| {
            if let Some(group) = fields_group(&arg) {
                let fields = syn::parse2::<InstrumentFields>(group.stream())?;
                let fields = fields.fields.iter().map(RecordField::instrument_tokens);
                let mut rewritten = Group::new(Delimiter::Parenthesis, quote! { #(#fields),* });
                rewritten.set_span(group.span());
                Ok(quote! { fields #rewritten })
            } else {
                Ok(arg)
            }
        })
        .collect::<Result<Vec<_>>>()?;

    Ok(quote! { #(#args),* })
}

fn reject_formatter(input: ParseStream<'_>) -> Result<()> {
    let formatter = if input.peek(Token![%]) {
        Some(input.parse::<Token![%]>()?.span)
    } else if input.peek(Token![?]) {
        Some(input.parse::<Token![?]>()?.span)
    } else {
        None
    };

    if let Some(span) = formatter {
        Err(syn::Error::new(
            span,
            "tracing format specifiers are not supported; implement `RecordAttribute` to define \
             the type's canonical encoding",
        ))
    } else {
        Ok(())
    }
}

impl RecordField {
    fn instrument_tokens(&self) -> TokenStream2 {
        let path = &self.path;
        if let Some(value) = &self.value {
            let value = value.value_tokens(&self.path.name(), self.path.is_count());
            quote! { #path = #value }
        } else {
            quote! { #path }
        }
    }
}

fn split_top_level_args(tokens: TokenStream2) -> Vec<TokenStream2> {
    let mut args = Vec::new();
    let mut current = TokenStream2::new();

    for token in tokens {
        match &token {
            TokenTree::Punct(punct) if punct.as_char() == ',' => {
                args.push(current);
                current = TokenStream2::new();
            },
            _ => current.extend([token]),
        }
    }

    if !current.is_empty() {
        args.push(current);
    }

    args
}

fn fields_group(arg: &TokenStream2) -> Option<Group> {
    let mut tokens = arg.clone().into_iter();
    let Some(TokenTree::Ident(ident)) = tokens.next() else {
        return None;
    };
    if ident != "fields" {
        return None;
    }

    let Some(TokenTree::Group(group)) = tokens.next() else {
        return None;
    };
    if group.delimiter() != Delimiter::Parenthesis || tokens.next().is_some() {
        return None;
    }

    Some(group)
}

fn ends_with_comma(tokens: &TokenStream2) -> bool {
    matches!(
        tokens.clone().into_iter().last(),
        Some(TokenTree::Punct(punct)) if punct.as_char() == ','
    )
}

/// Records canonical attributes on the current `miden_instrument` span.
///
/// Field values must implement `RecordAttribute`, and their names must be registered for the value
/// type. A field whose name ends in `.count` accepts any `usize` without registration. Append
/// `#[nonstandard]` to any other field value to permit an unregistered name while retaining its
/// canonical encoding.
#[proc_macro]
pub fn miden_span_record(input: TokenStream) -> TokenStream {
    let records = parse_macro_input!(input as RecordFields);
    let records = records.fields.into_iter().map(|field| {
        let name = field.path.name();
        let value = field
            .value
            .expect("record fields are parsed with required values")
            .value_tokens(&name, field.path.is_count());

        quote! {
            ::miden_node_tracing::Span::current().record(#name, #value);
        }
    });

    quote! {
        __miden_span_record_must_be_used_within_miden_instrument!();
        #(#records)*
    }
    .into()
}

fn collect_recorded_fields(function: &ItemFn) -> Vec<FieldPath> {
    let mut visitor = MacroVisitor::default();
    visitor.visit_block(&function.block);

    let mut names = BTreeSet::new();
    visitor.fields.into_iter().filter(|field| names.insert(field.name())).collect()
}

#[derive(Default)]
struct MacroVisitor {
    fields: Vec<FieldPath>,
}

impl<'ast> Visit<'ast> for MacroVisitor {
    fn visit_macro(&mut self, mac: &'ast Macro) {
        if mac
            .path
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "miden_span_record")
        {
            if let Ok(records) = syn::parse2::<RecordFields>(mac.tokens.clone()) {
                self.fields.extend(records.fields.into_iter().map(|field| field.path));
            }
        }

        syn::visit::visit_macro(self, mac);
    }
}

type InstrumentFields = Fields<false>;
type RecordFields = Fields<true>;

struct Fields<const VALUE_REQUIRED: bool> {
    fields: Punctuated<RecordField, Token![,]>,
}

impl<const VALUE_REQUIRED: bool> Parse for Fields<VALUE_REQUIRED> {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Ok(Self {
            fields: Punctuated::parse_terminated_with(input, |input| {
                RecordField::parse(input, VALUE_REQUIRED)
            })?,
        })
    }
}

struct RecordField {
    path: FieldPath,
    value: Option<RecordValue>,
}

impl RecordField {
    fn parse(input: ParseStream<'_>, value_required: bool) -> Result<Self> {
        reject_formatter(input)?;
        let path = input.parse()?;
        let value = if value_required || input.peek(Token![=]) {
            input.parse::<Token![=]>()?;
            reject_formatter(input)?;
            Some(input.parse()?)
        } else {
            None
        };

        Ok(Self { path, value })
    }
}

struct FieldPath {
    first: Ident,
    rest: Vec<(Dot, Ident)>,
}

impl FieldPath {
    fn name(&self) -> String {
        std::iter::once(&self.first)
            .chain(self.rest.iter().map(|(_, ident)| ident))
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(".")
    }

    fn is_count(&self) -> bool {
        self.rest.last().is_some_and(|(_, ident)| ident == "count")
    }
}

impl Parse for FieldPath {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let first = input.parse()?;
        let mut rest = Vec::new();

        while input.peek(Token![.]) {
            rest.push((input.parse()?, input.parse()?));
        }

        Ok(Self { first, rest })
    }
}

impl ToTokens for FieldPath {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        self.first.to_tokens(tokens);
        for (dot, ident) in &self.rest {
            dot.to_tokens(tokens);
            ident.to_tokens(tokens);
        }
    }
}

struct RecordValue {
    expr: Expr,
    nonstandard: bool,
}

impl RecordValue {
    fn value_tokens(&self, field_name: &str, is_count: bool) -> TokenStream2 {
        let expr = &self.expr;
        let assert_field_name = (!self.nonstandard && !is_count).then(|| {
            quote! {
                fn __miden_assert_field_name<T>(_: &T)
                where
                    T: ::miden_node_tracing::RecordAttribute + ?Sized,
                {
                    const {
                        assert!(
                            ::miden_node_tracing::field_name_allowed(
                                T::FIELD_NAMES,
                                #field_name,
                                T::PLURALIZE_FIELD_NAMES,
                            ),
                            concat!(
                                "tracing field `",
                                #field_name,
                                "` is not allowed for this attribute type",
                            ),
                        );
                    }
                }

                __miden_assert_field_name(value);
            }
        });
        let assert_count = is_count.then(|| {
            quote! {
                fn __miden_assert_count(_: &usize) {}

                __miden_assert_count(value);
            }
        });

        quote! {
            match &(#expr) {
                value => {
                    #assert_field_name
                    #assert_count
                    ::miden_node_tracing::record_attribute(value)
                }
            }
        }
    }
}

impl Parse for RecordValue {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let expr = input.parse()?;
        let attributes = input.call(Attribute::parse_outer)?;
        let nonstandard = match attributes.as_slice() {
            [] => false,
            [attribute] if matches!(&attribute.meta, Meta::Path(path) if path.is_ident("nonstandard")) => {
                true
            },
            [attribute, ..] => {
                return Err(syn::Error::new_spanned(
                    attribute,
                    "only `#[nonstandard]` is supported after a tracing field value",
                ));
            },
        };

        Ok(Self { expr, nonstandard })
    }
}