Skip to main content

miden_node_tracing_macro/
lib.rs

1use std::collections::BTreeSet;
2
3use proc_macro::TokenStream;
4use proc_macro2::{Delimiter, Group, TokenStream as TokenStream2, TokenTree};
5use quote::{ToTokens, quote};
6use syn::parse::{Parse, ParseStream};
7use syn::punctuated::Punctuated;
8use syn::token::Dot;
9use syn::visit::Visit;
10use syn::{
11    Attribute,
12    Block,
13    Expr,
14    Ident,
15    ItemFn,
16    LitStr,
17    Macro,
18    Meta,
19    Result,
20    Token,
21    parse_macro_input,
22    parse_quote,
23};
24
25mod instrument;
26
27/// Instruments a function using canonical tracing attributes and a scoped target.
28///
29/// Field values must implement `RecordAttribute`, and their names must be registered for the value
30/// type. A field whose name ends in `.count` accepts any `usize` without registration. Append
31/// `#[nonstandard]` to any other field value to permit an unregistered name while retaining its
32/// canonical encoding.
33///
34/// `err` records a typed error. The subscriber controls how it records the source chain.
35/// Errors must implement `std::error::Error + 'static` or dereference to that trait.
36/// `err(level = "warn")` sets the event level. Error formatters are not supported.
37/// Return value logging with `ret` is not supported.
38///
39/// Uses the target declared for this module unless an explicit `target` is supplied.
40/// An explicit target works without a declaration; otherwise a missing scope is a compile error.
41#[proc_macro_attribute]
42pub fn instrument(attr: TokenStream, item: TokenStream) -> TokenStream {
43    let attr = TokenStream2::from(attr);
44    let item = TokenStream2::from(item);
45    let explicit_target = split_top_level_args(attr.clone()).iter().any(|arg| {
46        matches!(arg.clone().into_iter().next(), Some(TokenTree::Ident(ident)) if ident == "target")
47    });
48
49    if explicit_target {
50        expand_instrument(attr.into(), item.into())
51    } else {
52        // Constants use item-name resolution, so hygiene alone cannot prevent collisions. Choose a
53        // name absent from both the function and its instrumentation arguments.
54        let mut name = "__MIDEN_TRACING_TARGET".to_owned();
55        while contains_ident(item.clone(), &name) || contains_ident(attr.clone(), &name) {
56            name.push('_');
57        }
58        let target = Ident::new(&name, proc_macro2::Span::mixed_site());
59        // Upstream requires parent and follows_from options to precede the target.
60        let args = split_top_level_args(attr);
61        expand_instrument(
62            quote!(#(#args,)* target = #target).into(),
63            quote! {
64                #[::miden_node_tracing::__with_tracing_target(#target)]
65                #item
66            }
67            .into(),
68        )
69    }
70}
71
72fn contains_ident(tokens: TokenStream2, name: &str) -> bool {
73    tokens.into_iter().any(|token| match token {
74        TokenTree::Ident(ident) => ident == name,
75        TokenTree::Group(group) => contains_ident(group.stream(), name),
76        _ => false,
77    })
78}
79
80/// Binds the lexical target after upstream instrumentation has generated its function body.
81///
82/// The upstream attribute accepts only literals or identifiers for targets. Inserting this
83/// constant after expansion makes it visible to both generated spans and automatic error events.
84#[doc(hidden)]
85#[proc_macro_attribute]
86pub fn __with_tracing_target(attr: TokenStream, item: TokenStream) -> TokenStream {
87    let target = parse_macro_input!(attr as Ident);
88    let mut function = parse_macro_input!(item as ItemFn);
89    function.block.stmts.insert(
90        0,
91        syn::parse_quote! {
92            const #target: &str = tracing_target!();
93        },
94    );
95    quote!(#function).into()
96}
97
98fn expand_instrument(attr: TokenStream, item: TokenStream) -> TokenStream {
99    let attr = match rewrite_explicit_fields(TokenStream2::from(attr)) {
100        Ok(attr) => attr,
101        Err(error) => return error.into_compile_error().into(),
102    };
103    let mut function = parse_macro_input!(item as ItemFn);
104    let fields = collect_recorded_fields(&function);
105    let attr = match instrument::instrument_result(attr, &mut function) {
106        Ok(attr) => attr,
107        Err(error) => return error.into_compile_error().into(),
108    };
109    let args = match merge_inferred_fields(attr, &fields) {
110        Ok(args) => args,
111        Err(error) => return error.into_compile_error().into(),
112    };
113    let statements = &function.block.stmts;
114    let block: Block = parse_quote! {{
115        #[allow(unused_macros)]
116        macro_rules! __miden_span_record_must_be_used_within_instrument {
117            () => {};
118        }
119
120        #(#statements)*
121    }};
122    *function.block = block;
123
124    let expanded = quote! {
125        #[::miden_node_tracing::__private::instrument(#args)]
126        #function
127    };
128
129    expanded.into()
130}
131
132/// Emits a trace-level event.
133///
134/// An optional first argument can provide a typed error. The error must implement
135/// `std::error::Error + 'static` or dereference to that trait. The OpenTelemetry layer records
136/// its message as `exception.message` and its sources as `exception.stacktrace`.
137///
138/// The event name is required and must be a string literal. When an error is provided, optional
139/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
140/// error, they precede the name. Attributes follow the name and must use a registered field name
141/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
142/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
143/// trailing commas are not supported.
144///
145/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
146/// as the event name.
147///
148/// ```rust,ignore
149/// use miden_node_tracing::trace;
150///
151/// miden_node_tracing::declare_targets! { default: "miden::process", }
152///
153/// trace!(target: "node", "block.received", block.number = 42_u32);
154///
155/// let source = std::io::Error::other("invalid block");
156/// trace!(&source, "block.rejected", block.number = 42_u32);
157/// ```
158///
159/// Uses the target declared for this module. An explicit `target:` overrides it and
160/// works without a declaration; otherwise a missing scope is a compile error.
161#[proc_macro]
162pub fn trace(input: TokenStream) -> TokenStream {
163    expand_event(input, "trace", false)
164}
165
166/// Emits a debug-level event.
167///
168/// An optional first argument can provide a typed error. The error must implement
169/// `std::error::Error + 'static` or dereference to that trait. The OpenTelemetry layer records
170/// its message as `exception.message` and its sources as `exception.stacktrace`.
171///
172/// The event name is required and must be a string literal. When an error is provided, optional
173/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
174/// error, they precede the name. Attributes follow the name and must use a registered field name
175/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
176/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
177/// trailing commas are not supported.
178///
179/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
180/// as the event name.
181///
182/// ```rust,ignore
183/// use miden_node_tracing::debug;
184///
185/// miden_node_tracing::declare_targets! { default: "miden::process", }
186///
187/// debug!("block.queued", block.number = 42_u32);
188///
189/// let source = std::io::Error::other("upstream unavailable");
190/// debug!(&source, "block.retrying", block.number = 42_u32);
191/// ```
192///
193/// Uses the target declared for this module. An explicit `target:` overrides it and
194/// works without a declaration; otherwise a missing scope is a compile error.
195#[proc_macro]
196pub fn debug(input: TokenStream) -> TokenStream {
197    expand_event(input, "debug", false)
198}
199
200/// Emits an info-level event.
201///
202/// An optional first argument can provide a typed error. The error must implement
203/// `std::error::Error + 'static` or dereference to that trait. The OpenTelemetry layer records
204/// its message as `exception.message` and its sources as `exception.stacktrace`.
205///
206/// The event name is required and must be a string literal. When an error is provided, optional
207/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
208/// error, they precede the name. Attributes follow the name and must use a registered field name
209/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
210/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
211/// trailing commas are not supported.
212///
213/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
214/// as the event name.
215///
216/// ```rust,ignore
217/// use miden_node_tracing::info;
218///
219/// miden_node_tracing::declare_targets! { default: "miden::process", }
220///
221/// let parent = tracing::info_span!("block");
222/// info!(parent: &parent, "block.accepted", block.number = 42_u32);
223///
224/// let source = std::io::Error::other("used fallback");
225/// info!(&source, "block.fallback_used", block.number = 42_u32);
226/// ```
227///
228/// Uses the target declared for this module. An explicit `target:` overrides it and
229/// works without a declaration; otherwise a missing scope is a compile error.
230#[proc_macro]
231pub fn info(input: TokenStream) -> TokenStream {
232    expand_event(input, "info", false)
233}
234
235/// Emits a warning-level event.
236///
237/// An optional first argument can provide a typed error. The error must implement
238/// `std::error::Error + 'static` or dereference to that trait. The OpenTelemetry layer records
239/// its message as `exception.message` and its sources as `exception.stacktrace`.
240///
241/// The event name is required and must be a string literal. When an error is provided, optional
242/// `target:` and `parent:` arguments go between the error and name, in that order. Without an
243/// error, they precede the name. Attributes follow the name and must use a registered field name
244/// and a value implementing `RecordAttribute`. Append `#[nonstandard]` to a field value to permit
245/// an unregistered name while retaining its canonical encoding. Tracing format specifiers and
246/// trailing commas are not supported.
247///
248/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
249/// as the event name.
250///
251/// ```rust,ignore
252/// use miden_node_tracing::warn;
253///
254/// miden_node_tracing::declare_targets! { default: "miden::process", }
255///
256/// warn!("block.delayed", block.number = 42_u32);
257///
258/// let source = std::io::Error::other("upstream unavailable");
259/// warn!(&source, "block.retrying", block.number = 42_u32);
260/// ```
261///
262/// Uses the target declared for this module. An explicit `target:` overrides it and
263/// works without a declaration; otherwise a missing scope is a compile error.
264#[proc_macro]
265pub fn warn(input: TokenStream) -> TokenStream {
266    expand_event(input, "warn", false)
267}
268
269/// Emits an error-level event with a typed error.
270///
271/// The first argument is required. It must implement `std::error::Error + 'static` or dereference
272/// to that trait. The OpenTelemetry layer records its message as `exception.message` and its
273/// sources as `exception.stacktrace`.
274///
275/// The event name follows the error and must be a string literal. Optional `target:` and `parent:`
276/// arguments go between the error and name, in that order. Additional attributes follow the name
277/// and must use a registered field name and a value implementing `RecordAttribute`. Append
278/// `#[nonstandard]` to a field value to permit an unregistered name while retaining its canonical
279/// encoding. Tracing format specifiers and trailing commas are not supported.
280///
281/// The name is recorded as tracing's `message` field, which the OpenTelemetry tracing layer uses
282/// as the event name.
283///
284/// ```rust,ignore
285/// use miden_node_tracing::error;
286///
287/// miden_node_tracing::declare_targets! { default: "miden::process", }
288///
289/// let source = std::io::Error::other("database unavailable");
290/// error!(source, target: "node", "block.store_failed", block.number = 42_u32);
291/// ```
292///
293/// Uses the target declared for this module. An explicit `target:` overrides it and
294/// works without a declaration; otherwise a missing scope is a compile error.
295#[proc_macro]
296pub fn error(input: TokenStream) -> TokenStream {
297    expand_event(input, "error", true)
298}
299
300/// Creates a trace-level span using the lexically visible `tracing_target!` target.
301///
302/// Accepts the same arguments as `tracing::trace_span!`. A leading `target:` overrides the
303/// scope and can be used without a target declaration.
304#[proc_macro]
305pub fn trace_span(input: TokenStream) -> TokenStream {
306    expand_scoped_macro(input, "trace_span")
307}
308
309/// Creates a debug-level span using the lexically visible `tracing_target!` target.
310///
311/// Accepts the same arguments as `tracing::debug_span!`. A leading `target:` overrides the
312/// scope and can be used without a target declaration.
313#[proc_macro]
314pub fn debug_span(input: TokenStream) -> TokenStream {
315    expand_scoped_macro(input, "debug_span")
316}
317
318/// Creates an info-level span using the lexically visible `tracing_target!` target.
319///
320/// Accepts the same arguments as `tracing::info_span!`. A leading `target:` overrides the
321/// scope and can be used without a target declaration.
322#[proc_macro]
323pub fn info_span(input: TokenStream) -> TokenStream {
324    expand_scoped_macro(input, "info_span")
325}
326
327/// Creates a warn-level span using the lexically visible `tracing_target!` target.
328///
329/// Accepts the same arguments as `tracing::warn_span!`. A leading `target:` overrides the
330/// scope and can be used without a target declaration.
331#[proc_macro]
332pub fn warn_span(input: TokenStream) -> TokenStream {
333    expand_scoped_macro(input, "warn_span")
334}
335
336/// Creates an error-level span using the lexically visible `tracing_target!` target.
337///
338/// Accepts the same arguments as `tracing::error_span!`. A leading `target:` overrides the
339/// scope and can be used without a target declaration.
340#[proc_macro]
341pub fn error_span(input: TokenStream) -> TokenStream {
342    expand_scoped_macro(input, "error_span")
343}
344
345/// Checks subscriber interest at a level using the lexically visible `tracing_target!` target.
346///
347/// Accepts a level followed by optional field names, just like `tracing::enabled!`. A leading
348/// `target:` overrides the scope and can be used without one. Otherwise, a `tracing_target!` declaration must be in lexical scope.
349/// This is an interest hint, not a guarantee that a particular span or event will be recorded.
350#[proc_macro]
351pub fn enabled(input: TokenStream) -> TokenStream {
352    expand_scoped_macro(input, "enabled")
353}
354
355fn expand_scoped_macro(input: TokenStream, name: &str) -> TokenStream {
356    let name = Ident::new(name, proc_macro2::Span::call_site());
357    let input = TokenStream2::from(input);
358    let mut tokens = input.clone().into_iter();
359    let explicit_target = matches!(tokens.next(), Some(TokenTree::Ident(name)) if name == "target")
360        && matches!(tokens.next(), Some(TokenTree::Punct(punct)) if punct.as_char() == ':');
361
362    if explicit_target {
363        quote! { ::miden_node_tracing::__private::#name!(#input) }
364    } else {
365        quote! { ::miden_node_tracing::__private::#name!(target: tracing_target!(), #input) }
366    }
367    .into()
368}
369
370fn expand_event(input: TokenStream, level: &str, error_required: bool) -> TokenStream {
371    let event = if error_required {
372        syn::parse::<ErrorEvent>(input).map(|event| event.0)
373    } else {
374        syn::parse::<OptionalErrorEvent>(input).map(|event| event.0)
375    };
376    let event = match event {
377        Ok(event) => event,
378        Err(error) => return error.into_compile_error().into(),
379    };
380
381    event.tokens(&Ident::new(level, proc_macro2::Span::call_site())).into()
382}
383
384struct ErrorEvent(Event);
385
386impl Parse for ErrorEvent {
387    fn parse(input: ParseStream<'_>) -> Result<Self> {
388        let event = parse_error_event(input)?;
389        event.reject_exception_fields()?;
390
391        Ok(Self(event))
392    }
393}
394
395struct OptionalErrorEvent(Event);
396
397impl Parse for OptionalErrorEvent {
398    fn parse(input: ParseStream<'_>) -> Result<Self> {
399        let event = if starts_without_error(input) {
400            Event::parse_after_error(input, None)?
401        } else {
402            parse_error_event(input)?
403        };
404        event.reject_exception_fields()?;
405
406        Ok(Self(event))
407    }
408}
409
410fn parse_error_event(input: ParseStream<'_>) -> Result<Event> {
411    if input.is_empty() {
412        return Err(input.error("expected an error expression"));
413    }
414
415    let error = input.parse()?;
416    if input.is_empty() {
417        return Err(syn::Error::new_spanned(error, "expected a static event name string literal"));
418    }
419    input.parse::<Token![,]>()?;
420
421    Event::parse_after_error(input, Some(error))
422}
423
424struct Event {
425    error: Option<Expr>,
426    target: Option<Expr>,
427    parent: Option<Expr>,
428    name: LitStr,
429    fields: Vec<RecordField>,
430}
431
432impl Event {
433    fn parse_after_error(input: ParseStream<'_>, error: Option<Expr>) -> Result<Self> {
434        let target = if input.peek(event_kw::target) {
435            input.parse::<event_kw::target>()?;
436            input.parse::<Token![:]>()?;
437            let target = input.parse()?;
438            input.parse::<Token![,]>()?;
439            Some(target)
440        } else {
441            None
442        };
443
444        let parent = if input.peek(event_kw::parent) {
445            input.parse::<event_kw::parent>()?;
446            input.parse::<Token![:]>()?;
447            let parent = input.parse()?;
448            input.parse::<Token![,]>()?;
449            Some(parent)
450        } else {
451            None
452        };
453
454        let name = input
455            .parse::<LitStr>()
456            .map_err(|_| input.error("expected a static event name string literal"))?;
457        let mut fields = Vec::new();
458
459        if !input.is_empty() {
460            let comma = input.parse::<Token![,]>()?;
461            if input.is_empty() {
462                return Err(syn::Error::new_spanned(comma, "trailing commas are not supported"));
463            }
464
465            loop {
466                fields.push(RecordField::parse(input, true)?);
467                if input.is_empty() {
468                    break;
469                }
470
471                let comma = input.parse::<Token![,]>()?;
472                if input.is_empty() {
473                    return Err(syn::Error::new_spanned(
474                        comma,
475                        "trailing commas are not supported",
476                    ));
477                }
478            }
479        }
480
481        Ok(Self { error, target, parent, name, fields })
482    }
483
484    fn reject_exception_fields(&self) -> Result<()> {
485        if let Some(field) = self.fields.iter().find(|field| {
486            matches!(field.path.name().as_str(), "exception.message" | "exception.stacktrace")
487        }) {
488            Err(syn::Error::new_spanned(
489                &field.path,
490                format!(
491                    "pass the error as the first argument instead of recording `{}`",
492                    field.path.name()
493                ),
494            ))
495        } else {
496            Ok(())
497        }
498    }
499
500    fn tokens(&self, level: &Ident) -> TokenStream2 {
501        let target = self.target.as_ref().map(|target| quote! { target: #target, });
502        let parent = self.parent.as_ref().map(|parent| quote! { parent: #parent, });
503        let name = &self.name;
504        let error_import = self.error.as_ref().map(|_| {
505            quote! { use ::miden_node_tracing::__private::AsDynError as _; }
506        });
507        let error = self.error.as_ref().map(|error| {
508            quote! {
509                , error = (#error).as_dyn_error()
510            }
511        });
512        let fields = self.fields.iter().map(RecordField::instrument_tokens);
513        let args = quote! {
514            #target
515            #parent
516            message = #name
517            #error
518            #(, #fields)*
519        };
520        let event = if self.target.is_none() {
521            quote! { ::miden_node_tracing::__private::#level!(target: tracing_target!(), #args) }
522        } else {
523            quote! { ::miden_node_tracing::__private::#level!(#args) }
524        };
525
526        quote! {{
527            #error_import
528            #event
529        }}
530    }
531}
532
533mod event_kw {
534    syn::custom_keyword!(parent);
535    syn::custom_keyword!(target);
536}
537
538fn starts_without_error(input: ParseStream<'_>) -> bool {
539    if input.peek(LitStr) {
540        return true;
541    }
542
543    let ahead = input.fork();
544    let starts_with_target =
545        ahead.parse::<event_kw::target>().is_ok() && ahead.parse::<Token![:]>().is_ok();
546    if starts_with_target {
547        return true;
548    }
549
550    let ahead = input.fork();
551    ahead.parse::<event_kw::parent>().is_ok() && ahead.parse::<Token![:]>().is_ok()
552}
553
554fn merge_inferred_fields(attr: TokenStream2, fields: &[FieldPath]) -> Result<TokenStream2> {
555    let mut args = split_top_level_args(attr);
556    reject_skip_directives(&args)?;
557
558    // Function arguments often contain large or sensitive values. Always skip them so spans only
559    // contain fields explicitly declared by the caller or inferred from `miden_span_record!`.
560    args.push(quote! { skip_all });
561
562    if fields.is_empty() {
563        return Ok(quote! { #(#args),* });
564    }
565
566    let inferred_fields = quote! { #(#fields = ::miden_node_tracing::field::Empty),* };
567    let mut merged_existing_fields = false;
568    let args = args
569        .into_iter()
570        .map(|arg| {
571            if let Some(group) = fields_group(&arg) {
572                merged_existing_fields = true;
573                let existing_fields = group.stream();
574                let merged_fields = if existing_fields.is_empty() {
575                    inferred_fields.clone()
576                } else if ends_with_comma(&existing_fields) {
577                    quote! { #existing_fields #inferred_fields }
578                } else {
579                    quote! { #existing_fields, #inferred_fields }
580                };
581                let mut merged_group = Group::new(Delimiter::Parenthesis, merged_fields);
582                merged_group.set_span(group.span());
583                quote! { fields #merged_group }
584            } else {
585                arg
586            }
587        })
588        .collect::<Vec<_>>();
589
590    if merged_existing_fields {
591        Ok(quote! { #(#args),* })
592    } else {
593        Ok(quote! { #(#args,)* fields(#inferred_fields) })
594    }
595}
596
597fn reject_skip_directives(args: &[TokenStream2]) -> Result<()> {
598    for arg in args {
599        let Some(TokenTree::Ident(ident)) = arg.clone().into_iter().next() else {
600            continue;
601        };
602        if ident == "skip" || ident == "skip_all" {
603            return Err(syn::Error::new_spanned(
604                arg,
605                format!(
606                    "`{ident}` is not supported by `instrument`; function arguments are \
607                     always skipped, record fields explicitly with `fields(...)`"
608                ),
609            ));
610        }
611    }
612
613    Ok(())
614}
615
616fn rewrite_explicit_fields(attr: TokenStream2) -> Result<TokenStream2> {
617    let args = split_top_level_args(attr)
618        .into_iter()
619        .map(|arg| {
620            if let Some(group) = fields_group(&arg) {
621                let fields = syn::parse2::<InstrumentFields>(group.stream())?;
622                let fields = fields.fields.iter().map(RecordField::instrument_tokens);
623                let mut rewritten = Group::new(Delimiter::Parenthesis, quote! { #(#fields),* });
624                rewritten.set_span(group.span());
625                Ok(quote! { fields #rewritten })
626            } else {
627                Ok(arg)
628            }
629        })
630        .collect::<Result<Vec<_>>>()?;
631
632    Ok(quote! { #(#args),* })
633}
634
635fn reject_formatter(input: ParseStream<'_>) -> Result<()> {
636    let formatter = if input.peek(Token![%]) {
637        Some(input.parse::<Token![%]>()?.span)
638    } else if input.peek(Token![?]) {
639        Some(input.parse::<Token![?]>()?.span)
640    } else {
641        None
642    };
643
644    if let Some(span) = formatter {
645        Err(syn::Error::new(
646            span,
647            "tracing format specifiers are not supported; implement `RecordAttribute` to define \
648             the type's canonical encoding",
649        ))
650    } else {
651        Ok(())
652    }
653}
654
655impl RecordField {
656    fn instrument_tokens(&self) -> TokenStream2 {
657        let path = &self.path;
658        if let Some(value) = &self.value {
659            let value = value.value_tokens(&self.path.name(), self.path.is_count());
660            quote! { #path = #value }
661        } else {
662            quote! { #path }
663        }
664    }
665}
666
667fn split_top_level_args(tokens: TokenStream2) -> Vec<TokenStream2> {
668    let mut args = Vec::new();
669    let mut current = TokenStream2::new();
670
671    for token in tokens {
672        match &token {
673            TokenTree::Punct(punct) if punct.as_char() == ',' => {
674                args.push(current);
675                current = TokenStream2::new();
676            },
677            _ => current.extend([token]),
678        }
679    }
680
681    if !current.is_empty() {
682        args.push(current);
683    }
684
685    args
686}
687
688fn fields_group(arg: &TokenStream2) -> Option<Group> {
689    let mut tokens = arg.clone().into_iter();
690    let Some(TokenTree::Ident(ident)) = tokens.next() else {
691        return None;
692    };
693    if ident != "fields" {
694        return None;
695    }
696
697    let Some(TokenTree::Group(group)) = tokens.next() else {
698        return None;
699    };
700    if group.delimiter() != Delimiter::Parenthesis || tokens.next().is_some() {
701        return None;
702    }
703
704    Some(group)
705}
706
707fn ends_with_comma(tokens: &TokenStream2) -> bool {
708    matches!(
709        tokens.clone().into_iter().last(),
710        Some(TokenTree::Punct(punct)) if punct.as_char() == ','
711    )
712}
713
714/// Records canonical attributes on the current `instrument` span.
715///
716/// Field values must implement `RecordAttribute`, and their names must be registered for the value
717/// type. A field whose name ends in `.count` accepts any `usize` without registration. Append
718/// `#[nonstandard]` to any other field value to permit an unregistered name while retaining its
719/// canonical encoding.
720#[proc_macro]
721pub fn miden_span_record(input: TokenStream) -> TokenStream {
722    let records = parse_macro_input!(input as RecordFields);
723    let records = records.fields.into_iter().map(|field| {
724        let name = field.path.name();
725        let value = field
726            .value
727            .expect("record fields are parsed with required values")
728            .value_tokens(&name, field.path.is_count());
729
730        quote! {
731            ::miden_node_tracing::Span::current().record(#name, #value);
732        }
733    });
734
735    quote! {
736        __miden_span_record_must_be_used_within_instrument!();
737        #(#records)*
738    }
739    .into()
740}
741
742fn collect_recorded_fields(function: &ItemFn) -> Vec<FieldPath> {
743    let mut visitor = MacroVisitor::default();
744    visitor.visit_block(&function.block);
745
746    let mut names = BTreeSet::new();
747    visitor.fields.into_iter().filter(|field| names.insert(field.name())).collect()
748}
749
750#[derive(Default)]
751struct MacroVisitor {
752    fields: Vec<FieldPath>,
753}
754
755impl<'ast> Visit<'ast> for MacroVisitor {
756    fn visit_macro(&mut self, mac: &'ast Macro) {
757        if mac
758            .path
759            .segments
760            .last()
761            .is_some_and(|segment| segment.ident == "miden_span_record")
762        {
763            if let Ok(records) = syn::parse2::<RecordFields>(mac.tokens.clone()) {
764                self.fields.extend(records.fields.into_iter().map(|field| field.path));
765            }
766        }
767
768        syn::visit::visit_macro(self, mac);
769    }
770}
771
772type InstrumentFields = Fields<false>;
773type RecordFields = Fields<true>;
774
775struct Fields<const VALUE_REQUIRED: bool> {
776    fields: Punctuated<RecordField, Token![,]>,
777}
778
779impl<const VALUE_REQUIRED: bool> Parse for Fields<VALUE_REQUIRED> {
780    fn parse(input: ParseStream<'_>) -> Result<Self> {
781        Ok(Self {
782            fields: Punctuated::parse_terminated_with(input, |input| {
783                RecordField::parse(input, VALUE_REQUIRED)
784            })?,
785        })
786    }
787}
788
789struct RecordField {
790    path: FieldPath,
791    value: Option<RecordValue>,
792}
793
794impl RecordField {
795    fn parse(input: ParseStream<'_>, value_required: bool) -> Result<Self> {
796        reject_formatter(input)?;
797        let path = input.parse()?;
798        let value = if value_required || input.peek(Token![=]) {
799            input.parse::<Token![=]>()?;
800            reject_formatter(input)?;
801            Some(input.parse()?)
802        } else {
803            None
804        };
805
806        Ok(Self { path, value })
807    }
808}
809
810struct FieldPath {
811    first: Ident,
812    rest: Vec<(Dot, Ident)>,
813}
814
815impl FieldPath {
816    fn name(&self) -> String {
817        std::iter::once(&self.first)
818            .chain(self.rest.iter().map(|(_, ident)| ident))
819            .map(ToString::to_string)
820            .collect::<Vec<_>>()
821            .join(".")
822    }
823
824    fn is_count(&self) -> bool {
825        self.rest.last().is_some_and(|(_, ident)| ident == "count")
826    }
827}
828
829impl Parse for FieldPath {
830    fn parse(input: ParseStream<'_>) -> Result<Self> {
831        let first = input.parse()?;
832        let mut rest = Vec::new();
833
834        while input.peek(Token![.]) {
835            rest.push((input.parse()?, input.parse()?));
836        }
837
838        Ok(Self { first, rest })
839    }
840}
841
842impl ToTokens for FieldPath {
843    fn to_tokens(&self, tokens: &mut TokenStream2) {
844        self.first.to_tokens(tokens);
845        for (dot, ident) in &self.rest {
846            dot.to_tokens(tokens);
847            ident.to_tokens(tokens);
848        }
849    }
850}
851
852struct RecordValue {
853    expr: Expr,
854    nonstandard: bool,
855}
856
857impl RecordValue {
858    fn value_tokens(&self, field_name: &str, is_count: bool) -> TokenStream2 {
859        let expr = &self.expr;
860        let assert_field_name = (!self.nonstandard && !is_count).then(|| {
861            quote! {
862                fn __miden_assert_field_name<T>(_: &T)
863                where
864                    T: ::miden_node_tracing::RecordAttribute + ?Sized,
865                {
866                    const {
867                        assert!(
868                            ::miden_node_tracing::field_name_allowed(
869                                T::FIELD_NAMES,
870                                #field_name,
871                                T::PLURALIZE_FIELD_NAMES,
872                            ),
873                            concat!(
874                                "tracing field `",
875                                #field_name,
876                                "` is not allowed for this attribute type",
877                            ),
878                        );
879                    }
880                }
881
882                __miden_assert_field_name(value);
883            }
884        });
885        let assert_count = is_count.then(|| {
886            quote! {
887                fn __miden_assert_count(_: &usize) {}
888
889                __miden_assert_count(value);
890            }
891        });
892
893        quote! {
894            match &(#expr) {
895                value => {
896                    #assert_field_name
897                    #assert_count
898                    ::miden_node_tracing::record_attribute(value)
899                }
900            }
901        }
902    }
903}
904
905impl Parse for RecordValue {
906    fn parse(input: ParseStream<'_>) -> Result<Self> {
907        let expr = input.parse()?;
908        let attributes = input.call(Attribute::parse_outer)?;
909        let nonstandard = match attributes.as_slice() {
910            [] => false,
911            [attribute] if matches!(&attribute.meta, Meta::Path(path) if path.is_ident("nonstandard")) => {
912                true
913            },
914            [attribute, ..] => {
915                return Err(syn::Error::new_spanned(
916                    attribute,
917                    "only `#[nonstandard]` is supported after a tracing field value",
918                ));
919            },
920        };
921
922        Ok(Self { expr, nonstandard })
923    }
924}