Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

backport recent commits from master #2096

Merged
merged 4 commits into from Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 33 additions & 0 deletions tracing-attributes/src/attr.rs
Expand Up @@ -11,6 +11,8 @@ pub(crate) struct InstrumentArgs {
level: Option<Level>,
pub(crate) name: Option<LitStr>,
target: Option<LitStr>,
pub(crate) parent: Option<Expr>,
pub(crate) follows_from: Option<Expr>,
pub(crate) skips: HashSet<Ident>,
pub(crate) skip_all: bool,
pub(crate) fields: Option<Fields>,
Expand Down Expand Up @@ -123,6 +125,18 @@ impl Parse for InstrumentArgs {
}
let target = input.parse::<StrArg<kw::target>>()?.value;
args.target = Some(target);
} else if lookahead.peek(kw::parent) {
if args.target.is_some() {
return Err(input.error("expected only a single `parent` argument"));
}
let parent = input.parse::<ExprArg<kw::parent>>()?;
args.parent = Some(parent.value);
} else if lookahead.peek(kw::follows_from) {
if args.target.is_some() {
return Err(input.error("expected only a single `follows_from` argument"));
}
let follows_from = input.parse::<ExprArg<kw::follows_from>>()?;
args.follows_from = Some(follows_from.value);
} else if lookahead.peek(kw::level) {
if args.level.is_some() {
return Err(input.error("expected only a single `level` argument"));
Expand Down Expand Up @@ -193,6 +207,23 @@ impl<T: Parse> Parse for StrArg<T> {
}
}

struct ExprArg<T> {
value: Expr,
_p: std::marker::PhantomData<T>,
}

impl<T: Parse> Parse for ExprArg<T> {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let _ = input.parse::<T>()?;
let _ = input.parse::<Token![=]>()?;
let value = input.parse()?;
Ok(Self {
value,
_p: std::marker::PhantomData,
})
}
}

struct Skips(HashSet<Ident>);

impl Parse for Skips {
Expand Down Expand Up @@ -374,6 +405,8 @@ mod kw {
syn::custom_keyword!(skip_all);
syn::custom_keyword!(level);
syn::custom_keyword!(target);
syn::custom_keyword!(parent);
syn::custom_keyword!(follows_from);
syn::custom_keyword!(name);
syn::custom_keyword!(err);
syn::custom_keyword!(ret);
Expand Down
20 changes: 16 additions & 4 deletions tracing-attributes/src/expand.rs
Expand Up @@ -88,6 +88,13 @@ fn gen_block<B: ToTokens>(

let level = args.level();

let follows_from = args.follows_from.iter();
let follows_from = quote! {
#(for cause in #follows_from {
__tracing_attr_span.follows_from(cause);
})*
};

// generate this inside a closure, so we can return early on errors.
let span = (|| {
// Pull out the arguments-to-be-skipped first, so we can filter results
Expand Down Expand Up @@ -135,6 +142,8 @@ fn gen_block<B: ToTokens>(

let target = args.target();

let parent = args.parent.iter();

// filter out skipped fields
let quoted_fields: Vec<_> = param_names
.iter()
Expand Down Expand Up @@ -182,6 +191,7 @@ fn gen_block<B: ToTokens>(

quote!(tracing::span!(
target: #target,
#(parent: #parent,)*
#level,
#span_name,
#(#quoted_fields,)*
Expand Down Expand Up @@ -217,7 +227,7 @@ fn gen_block<B: ToTokens>(
let mk_fut = match (err_event, ret_event) {
(Some(err_event), Some(ret_event)) => quote_spanned!(block.span()=>
async move {
match async move { #block }.await {
match async move #block.await {
#[allow(clippy::unit_arg)]
Ok(x) => {
#ret_event;
Expand All @@ -232,7 +242,7 @@ fn gen_block<B: ToTokens>(
),
(Some(err_event), None) => quote_spanned!(block.span()=>
async move {
match async move { #block }.await {
match async move #block.await {
#[allow(clippy::unit_arg)]
Ok(x) => Ok(x),
Err(e) => {
Expand All @@ -244,20 +254,21 @@ fn gen_block<B: ToTokens>(
),
(None, Some(ret_event)) => quote_spanned!(block.span()=>
async move {
let x = async move { #block }.await;
let x = async move #block.await;
#ret_event;
x
}
),
(None, None) => quote_spanned!(block.span()=>
async move { #block }
async move #block
),
};

return quote!(
let __tracing_attr_span = #span;
let __tracing_instrument_future = #mk_fut;
if !__tracing_attr_span.is_disabled() {
#follows_from
tracing::Instrument::instrument(
__tracing_instrument_future,
__tracing_attr_span
Expand All @@ -284,6 +295,7 @@ fn gen_block<B: ToTokens>(
let __tracing_attr_guard;
if tracing::level_enabled!(#level) {
__tracing_attr_span = #span;
#follows_from
__tracing_attr_guard = __tracing_attr_span.enter();
}
);
Expand Down
43 changes: 43 additions & 0 deletions tracing-attributes/src/lib.rs
Expand Up @@ -345,6 +345,47 @@ mod expand;
/// // ...
/// }
/// ```
/// Overriding the generated span's parent:
/// ```
/// # use tracing_attributes::instrument;
/// #[instrument(parent = None)]
/// pub fn my_function() {
/// // ...
/// }
/// ```
/// ```
/// # use tracing_attributes::instrument;
/// // A struct which owns a span handle.
/// struct MyStruct
/// {
/// span: tracing::Span
/// }
///
/// impl MyStruct
/// {
/// // Use the struct's `span` field as the parent span
/// #[instrument(parent = &self.span, skip(self))]
/// fn my_method(&self) {}
/// }
/// ```
/// Specifying [`follows_from`] relationships:
/// ```
/// # use tracing_attributes::instrument;
/// #[instrument(follows_from = causes)]
/// pub fn my_function(causes: &[tracing::Id]) {
/// // ...
/// }
/// ```
/// Any expression of type `impl IntoIterator<Item = impl Into<Option<Id>>>`
/// may be provided to `follows_from`; e.g.:
/// ```
/// # use tracing_attributes::instrument;
/// #[instrument(follows_from = [cause])]
/// pub fn my_function(cause: &tracing::span::EnteredSpan) {
/// // ...
/// }
/// ```
///
///
/// To skip recording an argument, pass the argument's name to the `skip`:
///
Expand Down Expand Up @@ -501,6 +542,8 @@ mod expand;
/// [`INFO`]: https://docs.rs/tracing/latest/tracing/struct.Level.html#associatedconstant.INFO
/// [empty field]: https://docs.rs/tracing/latest/tracing/field/struct.Empty.html
/// [field syntax]: https://docs.rs/tracing/latest/tracing/#recording-fields
/// [`follows_from`]: https://docs.rs/tracing/latest/tracing/struct.Span.html#method.follows_from
/// [`tracing`]: https://github.com/tokio-rs/tracing
/// [`fmt::Debug`]: std::fmt::Debug
#[proc_macro_attribute]
pub fn instrument(
Expand Down
17 changes: 17 additions & 0 deletions tracing-attributes/tests/async_fn.rs
@@ -1,5 +1,6 @@
use tracing_mock::*;

use std::convert::Infallible;
use std::{future::Future, pin::Pin, sync::Arc};
use tracing::subscriber::with_default;
use tracing_attributes::instrument;
Expand Down Expand Up @@ -51,6 +52,22 @@ async fn repro_1613_2() {
// else
}

// Reproduces https://github.com/tokio-rs/tracing/issues/1831
#[instrument]
#[deny(unused_braces)]
fn repro_1831() -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async move {})
}

// This replicates the pattern used to implement async trait methods on nightly using the
// `type_alias_impl_trait` feature
#[instrument(ret, err)]
#[deny(unused_braces)]
#[allow(clippy::manual_async_fn)]
fn repro_1831_2() -> impl Future<Output = Result<(), Infallible>> {
async { Ok(()) }
}

#[test]
fn async_fn_only_enters_for_polls() {
let (subscriber, handle) = subscriber::mock()
Expand Down
99 changes: 99 additions & 0 deletions tracing-attributes/tests/follows_from.rs
@@ -0,0 +1,99 @@
use tracing::{subscriber::with_default, Id, Level, Span};
use tracing_attributes::instrument;
use tracing_mock::*;

#[instrument(follows_from = causes, skip(causes))]
fn with_follows_from_sync(causes: impl IntoIterator<Item = impl Into<Option<Id>>>) {}

#[instrument(follows_from = causes, skip(causes))]
async fn with_follows_from_async(causes: impl IntoIterator<Item = impl Into<Option<Id>>>) {}

#[instrument(follows_from = [&Span::current()])]
fn follows_from_current() {}

#[test]
fn follows_from_sync_test() {
let cause_a = span::mock().named("cause_a");
let cause_b = span::mock().named("cause_b");
let cause_c = span::mock().named("cause_c");
let consequence = span::mock().named("with_follows_from_sync");

let (subscriber, handle) = subscriber::mock()
.new_span(cause_a.clone())
.new_span(cause_b.clone())
.new_span(cause_c.clone())
.new_span(consequence.clone())
.follows_from(consequence.clone(), cause_a)
.follows_from(consequence.clone(), cause_b)
.follows_from(consequence.clone(), cause_c)
.enter(consequence.clone())
.exit(consequence)
.done()
.run_with_handle();

with_default(subscriber, || {
let cause_a = tracing::span!(Level::TRACE, "cause_a");
let cause_b = tracing::span!(Level::TRACE, "cause_b");
let cause_c = tracing::span!(Level::TRACE, "cause_c");

with_follows_from_sync(&[cause_a, cause_b, cause_c])
});

handle.assert_finished();
}

#[test]
fn follows_from_async_test() {
let cause_a = span::mock().named("cause_a");
let cause_b = span::mock().named("cause_b");
let cause_c = span::mock().named("cause_c");
let consequence = span::mock().named("with_follows_from_async");

let (subscriber, handle) = subscriber::mock()
.new_span(cause_a.clone())
.new_span(cause_b.clone())
.new_span(cause_c.clone())
.new_span(consequence.clone())
.follows_from(consequence.clone(), cause_a)
.follows_from(consequence.clone(), cause_b)
.follows_from(consequence.clone(), cause_c)
.enter(consequence.clone())
.exit(consequence)
.done()
.run_with_handle();

with_default(subscriber, || {
block_on_future(async {
let cause_a = tracing::span!(Level::TRACE, "cause_a");
let cause_b = tracing::span!(Level::TRACE, "cause_b");
let cause_c = tracing::span!(Level::TRACE, "cause_c");

with_follows_from_async(&[cause_a, cause_b, cause_c]).await
})
});

handle.assert_finished();
}

#[test]
fn follows_from_current_test() {
let cause = span::mock().named("cause");
let consequence = span::mock().named("follows_from_current");

let (subscriber, handle) = subscriber::mock()
.new_span(cause.clone())
.enter(cause.clone())
.new_span(consequence.clone())
.follows_from(consequence.clone(), cause.clone())
.enter(consequence.clone())
.exit(consequence)
.exit(cause)
.done()
.run_with_handle();

with_default(subscriber, || {
tracing::span!(Level::TRACE, "cause").in_scope(follows_from_current)
});

handle.assert_finished();
}