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
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! Attribute macro for extending functions and futures with the `Observe` trait.

#![deny(missing_docs, warnings)]

use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    spanned::Spanned,
    Attribute, Signature, Visibility,
};

/// Attribute macro for extending functions and futures with the `Observe` trait.
///
/// This instruments the function or future with a `tracing` span with the `trace_tools::observe` target, so that
/// it can be filtered by subscribers. It also records the location of the calling code to the span as
/// fields. This is assigned to `loc.file`, `loc.line` and `loc.col` fields, similar to how `tokio` instruments
/// tasks internally.
///
/// As such, `tokio` tasks, any functions or futures instrumented with `tracing`, and any functions or futures
/// instrumented with the `Observe` trait or macro will be wrapped in spans that contain similarly structured
/// information for diagnostics. The only difference should be the span target and the span name (if
/// available).
///
/// # Examples
///
/// A future or function can be wrapped in a `tracing` span with the following:
/// ```ignore
/// use trace_tools::observe;
///
/// #[observe]
/// pub async fn say_hello() {
///     println!("hello");
/// }
/// ```
///
/// This will generate a span equivalent to the following:
/// ```ignore
/// // Location of the function signature.
/// let location = std::panic::Location::caller();
///
/// tracing::trace_span!(
///     "trace_tools::observe",
///     "observed",
///     observed.name = "say_hello",
///     loc.file = location.file(),
///     loc.line = location.line(),
///     loc.col = location.column(),
/// );
/// ```
///
/// The future or function will then run inside the context of the generated span:
/// ```ignore
/// let _guard = span.enter();
///
/// async move {
///     println!("hello");
/// }
/// .await;
/// ```
#[proc_macro_attribute]
pub fn observe(
    _args: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let observe_impl = parse_macro_input!(input as ObserveImpl);
    observe_impl.gen_tokens().into()
}

#[derive(Debug)]
struct ObserveImpl {
    attributes: Vec<Attribute>,
    visibility: Visibility,
    signature: Signature,
    block: TokenStream,
}

impl Parse for ObserveImpl {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let attributes = input.call(Attribute::parse_outer)?;
        let visibility = input.parse()?;
        let signature = input.parse()?;
        let block = input.parse()?;

        Ok(Self {
            attributes,
            visibility,
            signature,
            block,
        })
    }
}

impl ObserveImpl {
    fn gen_tokens(self) -> TokenStream {
        let ObserveImpl {
            attributes,
            visibility,
            signature,
            block,
        } = self;

        let fn_name = signature.ident.to_string();

        let block = match &signature.asyncness {
            Some(_) => Self::gen_async_block(fn_name, &block),
            None => Self::gen_block(fn_name, &block),
        };

        quote! {
            #(#attributes)*
            #visibility #signature
            {
                #block
            }
        }
    }

    fn gen_block(fn_name: String, block: &TokenStream) -> TokenStream {
        let span = quote! {
            {
                let location = std::panic::Location::caller();

                tracing::trace_span!(
                    target: "trace_tools::observe",
                    "observed",
                    observed.name = #fn_name,
                    loc.file = location.file(),
                    loc.line = location.line(),
                    loc.col = location.column(),
                )
            }
        };

        quote_spanned! {
            block.span() => {
                let span = #span;
                let _guard = span.enter();
                #block
            }
        }
    }

    fn gen_async_block(fn_name: String, block: &TokenStream) -> TokenStream {
        let observed_future = quote_spanned! {
            block.span() => async move #block
        };

        quote! {
            trace_tools::Observe::observe(#observed_future, #fn_name).await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{quote, ObserveImpl, TokenStream};

    #[test]
    fn observe_async() {
        let input: TokenStream = quote! {
            async fn test_observe_fn() {
                println!("observing this function");
            }
        };

        let observe_impl = syn::parse2::<ObserveImpl>(input);
        assert!(observe_impl.is_ok());

        let output_tokens = observe_impl.unwrap().gen_tokens();
        let expected_tokens: TokenStream = quote! {
            async fn test_observe_fn() {
                trace_tools::Observe::observe(
                    async move {
                        println!("observing this function");
                    },
                    "test_observe_fn"
                ).await
            }
        };

        assert_eq!(output_tokens.to_string(), expected_tokens.to_string());
    }

    #[test]
    fn observe() {
        let input: TokenStream = quote! {
            fn test_observe_fn() {
                println!("observing this function");
            }
        };

        let observe_impl = syn::parse2::<ObserveImpl>(input);
        assert!(observe_impl.is_ok());

        let output_tokens = observe_impl.unwrap().gen_tokens();
        let expected_tokens: TokenStream = quote! {
            fn test_observe_fn() {
                {
                    let span = {
                        let location = std::panic::Location::caller();

                        tracing::trace_span!(
                            target: "trace_tools::observe",
                            "observed",
                            observed.name = "test_observe_fn",
                            loc.file = location.file(),
                            loc.line = location.line(),
                            loc.col = location.column(),
                        )
                    };

                    let _guard = span.enter();
                    {
                        println!("observing this function");
                    }
                }
            }
        };

        assert_eq!(output_tokens.to_string(), expected_tokens.to_string());
    }
}