| 1 |
use std::iter; |
| 2 |
|
| 3 |
use proc_macro2::TokenStream; |
| 4 |
use quote::{quote, quote_spanned, ToTokens}; |
| 5 |
use syn::visit_mut::VisitMut; |
| 6 |
use syn::{ |
| 7 |
punctuated::Punctuated, spanned::Spanned, Block, Expr, ExprAsync, ExprCall, FieldPat, FnArg, |
| 8 |
Ident, Item, ItemFn, Pat, PatIdent, PatReference, PatStruct, PatTuple, PatTupleStruct, PatType, |
| 9 |
Path, ReturnType, Signature, Stmt, Token, Type, TypePath, |
| 10 |
}; |
| 11 |
|
| 12 |
use crate::{ |
| 13 |
attr::{Field, Fields, FormatMode, InstrumentArgs, Level}, |
| 14 |
MaybeItemFn, MaybeItemFnRef, |
| 15 |
}; |
| 16 |
|
| 17 |
/// Given an existing function, generate an instrumented version of that function |
| 18 |
pub(crate) fn gen_function<'a, B: ToTokens + 'a>( |
| 19 |
input: MaybeItemFnRef<'a, B>, |
| 20 |
args: InstrumentArgs, |
| 21 |
instrumented_function_name: &str, |
| 22 |
self_type: Option<&TypePath>, |
| 23 |
) -> proc_macro2::TokenStream { |
| 24 |
// these are needed ahead of time, as ItemFn contains the function body _and_ |
| 25 |
// isn't representable inside a quote!/quote_spanned! macro |
| 26 |
// (Syn's ToTokens isn't implemented for ItemFn) |
| 27 |
let MaybeItemFnRef { |
| 28 |
outer_attrs, |
| 29 |
inner_attrs, |
| 30 |
vis, |
| 31 |
sig, |
| 32 |
block, |
| 33 |
} = input; |
| 34 |
|
| 35 |
let Signature { |
| 36 |
output, |
| 37 |
inputs: params, |
| 38 |
unsafety, |
| 39 |
asyncness, |
| 40 |
constness, |
| 41 |
abi, |
| 42 |
ident, |
| 43 |
generics: |
| 44 |
syn::Generics { |
| 45 |
params: gen_params, |
| 46 |
where_clause, |
| 47 |
.. |
| 48 |
}, |
| 49 |
.. |
| 50 |
} = sig; |
| 51 |
|
| 52 |
let warnings = args.warnings(); |
| 53 |
|
| 54 |
let (return_type, return_span) = if let ReturnType::Type(_, return_type) = &output { |
| 55 |
(erase_impl_trait(return_type), return_type.span()) |
| 56 |
} else { |
| 57 |
// Point at function name if we don't have an explicit return type |
| 58 |
(syn::parse_quote! { () }, ident.span()) |
| 59 |
}; |
| 60 |
// Install a fake return statement as the first thing in the function |
| 61 |
// body, so that we eagerly infer that the return type is what we |
| 62 |
// declared in the async fn signature. |
| 63 |
// The `#[allow(..)]` is given because the return statement is |
| 64 |
// unreachable, but does affect inference, so it needs to be written |
| 65 |
// exactly that way for it to do its magic. |
| 66 |
let fake_return_edge = quote_spanned! {return_span=> |
| 67 |
#[allow(unreachable_code, clippy::diverging_sub_expression, clippy::let_unit_value, clippy::unreachable)] |
| 68 |
if false { |
| 69 |
let __tracing_attr_fake_return: #return_type = |
| 70 |
unreachable!("this is just for type inference, and is unreachable code"); |
| 71 |
return __tracing_attr_fake_return; |
| 72 |
} |
| 73 |
}; |
| 74 |
let block = quote! { |
| 75 |
{ |
| 76 |
#fake_return_edge |
| 77 |
#block |
| 78 |
} |
| 79 |
}; |
| 80 |
|
| 81 |
let body = gen_block( |
| 82 |
&block, |
| 83 |
params, |
| 84 |
asyncness.is_some(), |
| 85 |
args, |
| 86 |
instrumented_function_name, |
| 87 |
self_type, |
| 88 |
); |
| 89 |
|
| 90 |
quote!( |
| 91 |
#(#outer_attrs) * |
| 92 |
#vis #constness #unsafety #asyncness #abi fn #ident<#gen_params>(#params) #output |
| 93 |
#where_clause |
| 94 |
{ |
| 95 |
#(#inner_attrs) * |
| 96 |
#warnings |
| 97 |
#body |
| 98 |
} |
| 99 |
) |
| 100 |
} |
| 101 |
|
| 102 |
/// Instrument a block |
| 103 |
fn gen_block<B: ToTokens>( |
| 104 |
block: &B, |
| 105 |
params: &Punctuated<FnArg, Token![,]>, |
| 106 |
async_context: bool, |
| 107 |
mut args: InstrumentArgs, |
| 108 |
instrumented_function_name: &str, |
| 109 |
self_type: Option<&TypePath>, |
| 110 |
) -> proc_macro2::TokenStream { |
| 111 |
// generate the span's name |
| 112 |
let span_name = args |
| 113 |
// did the user override the span's name? |
| 114 |
.name |
| 115 |
.as_ref() |
| 116 |
.map(|name| quote!(#name)) |
| 117 |
.unwrap_or_else(|| quote!(#instrumented_function_name)); |
| 118 |
|
| 119 |
let args_level = args.level(); |
| 120 |
let level = args_level.clone(); |
| 121 |
|
| 122 |
let follows_from = args.follows_from.iter(); |
| 123 |
let follows_from = quote! { |
| 124 |
#(for cause in #follows_from { |
| 125 |
__tracing_attr_span.follows_from(cause); |
| 126 |
})* |
| 127 |
}; |
| 128 |
|
| 129 |
// generate this inside a closure, so we can return early on errors. |
| 130 |
let span = (|| { |
| 131 |
// Pull out the arguments-to-be-skipped first, so we can filter results |
| 132 |
// below. |
| 133 |
let param_names: Vec<(Ident, (Ident, RecordType))> = params |
| 134 |
.clone() |
| 135 |
.into_iter() |
| 136 |
.flat_map(|param| match param { |
| 137 |
FnArg::Typed(PatType { pat, ty, .. }) => { |
| 138 |
param_names(*pat, RecordType::parse_from_ty(&ty)) |
| 139 |
} |
| 140 |
FnArg::Receiver(_) => Box::new(iter::once(( |
| 141 |
Ident::new("self", param.span()), |
| 142 |
RecordType::Debug, |
| 143 |
))), |
| 144 |
}) |
| 145 |
// Little dance with new (user-exposed) names and old (internal) |
| 146 |
// names of identifiers. That way, we could do the following |
| 147 |
// even though async_trait (<=0.1.43) rewrites "self" as "_self": |
| 148 |
// ``` |
| 149 |
// #[async_trait] |
| 150 |
// impl Foo for FooImpl { |
| 151 |
// #[instrument(skip(self))] |
| 152 |
// async fn foo(&self, v: usize) {} |
| 153 |
// } |
| 154 |
// ``` |
| 155 |
.map(|(x, record_type)| { |
| 156 |
// if we are inside a function generated by async-trait <=0.1.43, we need to |
| 157 |
// take care to rewrite "_self" as "self" for 'user convenience' |
| 158 |
if self_type.is_some() && x == "_self" { |
| 159 |
(Ident::new("self", x.span()), (x, record_type)) |
| 160 |
} else { |
| 161 |
(x.clone(), (x, record_type)) |
| 162 |
} |
| 163 |
}) |
| 164 |
.collect(); |
| 165 |
|
| 166 |
for skip in &args.skips { |
| 167 |
if !param_names.iter().map(|(user, _)| user).any(|y| y == skip) { |
| 168 |
return quote_spanned! {skip.span()=> |
| 169 |
compile_error!("attempting to skip non-existent parameter") |
| 170 |
}; |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
let target = args.target(); |
| 175 |
|
| 176 |
let parent = args.parent.iter(); |
| 177 |
|
| 178 |
// filter out skipped fields |
| 179 |
let quoted_fields: Vec<_> = param_names |
| 180 |
.iter() |
| 181 |
.filter(|(param, _)| { |
| 182 |
if args.skip_all || args.skips.contains(param) { |
| 183 |
return false; |
| 184 |
} |
| 185 |
|
| 186 |
// If any parameters have the same name as a custom field, skip |
| 187 |
// and allow them to be formatted by the custom field. |
| 188 |
if let Some(ref fields) = args.fields { |
| 189 |
fields.0.iter().all(|Field { ref name, .. }| { |
| 190 |
let first = name.first(); |
| 191 |
first != name.last() || !first.iter().any(|name| name == ¶m) |
| 192 |
}) |
| 193 |
} else { |
| 194 |
true |
| 195 |
} |
| 196 |
}) |
| 197 |
.map(|(user_name, (real_name, record_type))| match record_type { |
| 198 |
RecordType::Value => quote!(#user_name = #real_name), |
| 199 |
RecordType::Debug => quote!(#user_name = tracing::field::debug(&#real_name)), |
| 200 |
}) |
| 201 |
.collect(); |
| 202 |
|
| 203 |
// replace every use of a variable with its original name |
| 204 |
if let Some(Fields(ref mut fields)) = args.fields { |
| 205 |
let mut replacer = IdentAndTypesRenamer { |
| 206 |
idents: param_names.into_iter().map(|(a, (b, _))| (a, b)).collect(), |
| 207 |
types: Vec::new(), |
| 208 |
}; |
| 209 |
|
| 210 |
// when async-trait <=0.1.43 is in use, replace instances |
| 211 |
// of the "Self" type inside the fields values |
| 212 |
if let Some(self_type) = self_type { |
| 213 |
replacer.types.push(("Self", self_type.clone())); |
| 214 |
} |
| 215 |
|
| 216 |
for e in fields.iter_mut().filter_map(|f| f.value.as_mut()) { |
| 217 |
syn::visit_mut::visit_expr_mut(&mut replacer, e); |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
let custom_fields = &args.fields; |
| 222 |
|
| 223 |
quote!(tracing::span!( |
| 224 |
target: #target, |
| 225 |
#(parent: #parent,)* |
| 226 |
#level, |
| 227 |
#span_name, |
| 228 |
#(#quoted_fields,)* |
| 229 |
#custom_fields |
| 230 |
|
| 231 |
)) |
| 232 |
})(); |
| 233 |
|
| 234 |
let target = args.target(); |
| 235 |
|
| 236 |
let err_event = match args.err_args { |
| 237 |
Some(event_args) => { |
| 238 |
let level_tokens = event_args.level(Level::Error); |
| 239 |
match event_args.mode { |
| 240 |
FormatMode::Default | FormatMode::Display => Some(quote!( |
| 241 |
tracing::event!(target: #target, #level_tokens, error = %e) |
| 242 |
)), |
| 243 |
FormatMode::Debug => Some(quote!( |
| 244 |
tracing::event!(target: #target, #level_tokens, error = ?e) |
| 245 |
)), |
| 246 |
} |
| 247 |
} |
| 248 |
_ => None, |
| 249 |
}; |
| 250 |
|
| 251 |
let ret_event = match args.ret_args { |
| 252 |
Some(event_args) => { |
| 253 |
let level_tokens = event_args.level(args_level); |
| 254 |
match event_args.mode { |
| 255 |
FormatMode::Display => Some(quote!( |
| 256 |
tracing::event!(target: #target, #level_tokens, return = %x) |
| 257 |
)), |
| 258 |
FormatMode::Default | FormatMode::Debug => Some(quote!( |
| 259 |
tracing::event!(target: #target, #level_tokens, return = ?x) |
| 260 |
)), |
| 261 |
} |
| 262 |
} |
| 263 |
_ => None, |
| 264 |
}; |
| 265 |
|
| 266 |
// Generate the instrumented function body. |
| 267 |
// If the function is an `async fn`, this will wrap it in an async block, |
| 268 |
// which is `instrument`ed using `tracing-futures`. Otherwise, this will |
| 269 |
// enter the span and then perform the rest of the body. |
| 270 |
// If `err` is in args, instrument any resulting `Err`s. |
| 271 |
// If `ret` is in args, instrument any resulting `Ok`s when the function |
| 272 |
// returns `Result`s, otherwise instrument any resulting values. |
| 273 |
if async_context { |
| 274 |
let mk_fut = match (err_event, ret_event) { |
| 275 |
(Some(err_event), Some(ret_event)) => quote_spanned!(block.span()=> |
| 276 |
async move { |
| 277 |
match async move #block.await { |
| 278 |
#[allow(clippy::unit_arg)] |
| 279 |
Ok(x) => { |
| 280 |
#ret_event; |
| 281 |
Ok(x) |
| 282 |
}, |
| 283 |
Err(e) => { |
| 284 |
#err_event; |
| 285 |
Err(e) |
| 286 |
} |
| 287 |
} |
| 288 |
} |
| 289 |
), |
| 290 |
(Some(err_event), None) => quote_spanned!(block.span()=> |
| 291 |
async move { |
| 292 |
match async move #block.await { |
| 293 |
#[allow(clippy::unit_arg)] |
| 294 |
Ok(x) => Ok(x), |
| 295 |
Err(e) => { |
| 296 |
#err_event; |
| 297 |
Err(e) |
| 298 |
} |
| 299 |
} |
| 300 |
} |
| 301 |
), |
| 302 |
(None, Some(ret_event)) => quote_spanned!(block.span()=> |
| 303 |
async move { |
| 304 |
let x = async move #block.await; |
| 305 |
#ret_event; |
| 306 |
x |
| 307 |
} |
| 308 |
), |
| 309 |
(None, None) => quote_spanned!(block.span()=> |
| 310 |
async move #block |
| 311 |
), |
| 312 |
}; |
| 313 |
|
| 314 |
return quote!( |
| 315 |
let __tracing_attr_span = #span; |
| 316 |
let __tracing_instrument_future = #mk_fut; |
| 317 |
if !__tracing_attr_span.is_disabled() { |
| 318 |
#follows_from |
| 319 |
tracing::Instrument::instrument( |
| 320 |
__tracing_instrument_future, |
| 321 |
__tracing_attr_span |
| 322 |
) |
| 323 |
.await |
| 324 |
} else { |
| 325 |
__tracing_instrument_future.await |
| 326 |
} |
| 327 |
); |
| 328 |
} |
| 329 |
|
| 330 |
let span = quote!( |
| 331 |
// These variables are left uninitialized and initialized only |
| 332 |
// if the tracing level is statically enabled at this point. |
| 333 |
// While the tracing level is also checked at span creation |
| 334 |
// time, that will still create a dummy span, and a dummy guard |
| 335 |
// and drop the dummy guard later. By lazily initializing these |
| 336 |
// variables, Rust will generate a drop flag for them and thus |
| 337 |
// only drop the guard if it was created. This creates code that |
| 338 |
// is very straightforward for LLVM to optimize out if the tracing |
| 339 |
// level is statically disabled, while not causing any performance |
| 340 |
// regression in case the level is enabled. |
| 341 |
let __tracing_attr_span; |
| 342 |
let __tracing_attr_guard; |
| 343 |
if tracing::level_enabled!(#level) { |
| 344 |
__tracing_attr_span = #span; |
| 345 |
#follows_from |
| 346 |
__tracing_attr_guard = __tracing_attr_span.enter(); |
| 347 |
} |
| 348 |
); |
| 349 |
|
| 350 |
match (err_event, ret_event) { |
| 351 |
(Some(err_event), Some(ret_event)) => quote_spanned! {block.span()=> |
| 352 |
#span |
| 353 |
#[allow(clippy::redundant_closure_call)] |
| 354 |
match (move || #block)() { |
| 355 |
#[allow(clippy::unit_arg)] |
| 356 |
Ok(x) => { |
| 357 |
#ret_event; |
| 358 |
Ok(x) |
| 359 |
}, |
| 360 |
Err(e) => { |
| 361 |
#err_event; |
| 362 |
Err(e) |
| 363 |
} |
| 364 |
} |
| 365 |
}, |
| 366 |
(Some(err_event), None) => quote_spanned!(block.span()=> |
| 367 |
#span |
| 368 |
#[allow(clippy::redundant_closure_call)] |
| 369 |
match (move || #block)() { |
| 370 |
#[allow(clippy::unit_arg)] |
| 371 |
Ok(x) => Ok(x), |
| 372 |
Err(e) => { |
| 373 |
#err_event; |
| 374 |
Err(e) |
| 375 |
} |
| 376 |
} |
| 377 |
), |
| 378 |
(None, Some(ret_event)) => quote_spanned!(block.span()=> |
| 379 |
#span |
| 380 |
#[allow(clippy::redundant_closure_call)] |
| 381 |
let x = (move || #block)(); |
| 382 |
#ret_event; |
| 383 |
x |
| 384 |
), |
| 385 |
(None, None) => quote_spanned!(block.span() => |
| 386 |
// Because `quote` produces a stream of tokens _without_ whitespace, the |
| 387 |
// `if` and the block will appear directly next to each other. This |
| 388 |
// generates a clippy lint about suspicious `if/else` formatting. |
| 389 |
// Therefore, suppress the lint inside the generated code... |
| 390 |
#[allow(clippy::suspicious_else_formatting)] |
| 391 |
{ |
| 392 |
#span |
| 393 |
// ...but turn the lint back on inside the function body. |
| 394 |
#[warn(clippy::suspicious_else_formatting)] |
| 395 |
#block |
| 396 |
} |
| 397 |
), |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
/// Indicates whether a field should be recorded as `Value` or `Debug`. |
| 402 |
enum RecordType { |
| 403 |
/// The field should be recorded using its `Value` implementation. |
| 404 |
Value, |
| 405 |
/// The field should be recorded using `tracing::field::debug()`. |
| 406 |
Debug, |
| 407 |
} |
| 408 |
|
| 409 |
impl RecordType { |
| 410 |
/// Array of primitive types which should be recorded as [RecordType::Value]. |
| 411 |
const TYPES_FOR_VALUE: &'static [&'static str] = &[ |
| 412 |
"bool", |
| 413 |
"str", |
| 414 |
"u8", |
| 415 |
"i8", |
| 416 |
"u16", |
| 417 |
"i16", |
| 418 |
"u32", |
| 419 |
"i32", |
| 420 |
"u64", |
| 421 |
"i64", |
| 422 |
"f32", |
| 423 |
"f64", |
| 424 |
"usize", |
| 425 |
"isize", |
| 426 |
"NonZeroU8", |
| 427 |
"NonZeroI8", |
| 428 |
"NonZeroU16", |
| 429 |
"NonZeroI16", |
| 430 |
"NonZeroU32", |
| 431 |
"NonZeroI32", |
| 432 |
"NonZeroU64", |
| 433 |
"NonZeroI64", |
| 434 |
"NonZeroUsize", |
| 435 |
"NonZeroIsize", |
| 436 |
"Wrapping", |
| 437 |
]; |
| 438 |
|
| 439 |
/// Parse `RecordType` from [Type] by looking up |
| 440 |
/// the [RecordType::TYPES_FOR_VALUE] array. |
| 441 |
fn parse_from_ty(ty: &Type) -> Self { |
| 442 |
match ty { |
| 443 |
Type::Path(TypePath { path, .. }) |
| 444 |
if path |
| 445 |
.segments |
| 446 |
.iter() |
| 447 |
.last() |
| 448 |
.map(|path_segment| { |
| 449 |
let ident = path_segment.ident.to_string(); |
| 450 |
Self::TYPES_FOR_VALUE.iter().any(|&t| t == ident) |
| 451 |
}) |
| 452 |
.unwrap_or(false) => |
| 453 |
{ |
| 454 |
RecordType::Value |
| 455 |
} |
| 456 |
Type::Reference(syn::TypeReference { elem, .. }) => RecordType::parse_from_ty(elem), |
| 457 |
_ => RecordType::Debug, |
| 458 |
} |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
fn param_names(pat: Pat, record_type: RecordType) -> Box<dyn Iterator<Item = (Ident, RecordType)>> { |
| 463 |
match pat { |
| 464 |
Pat::Ident(PatIdent { ident, .. }) => Box::new(iter::once((ident, record_type))), |
| 465 |
Pat::Reference(PatReference { pat, .. }) => param_names(*pat, record_type), |
| 466 |
// We can't get the concrete type of fields in the struct/tuple |
| 467 |
// patterns by using `syn`. e.g. `fn foo(Foo { x, y }: Foo) {}`. |
| 468 |
// Therefore, the struct/tuple patterns in the arguments will just |
| 469 |
// always be recorded as `RecordType::Debug`. |
| 470 |
Pat::Struct(PatStruct { fields, .. }) => Box::new( |
| 471 |
fields |
| 472 |
.into_iter() |
| 473 |
.flat_map(|FieldPat { pat, .. }| param_names(*pat, RecordType::Debug)), |
| 474 |
), |
| 475 |
Pat::Tuple(PatTuple { elems, .. }) => Box::new( |
| 476 |
elems |
| 477 |
.into_iter() |
| 478 |
.flat_map(|p| param_names(p, RecordType::Debug)), |
| 479 |
), |
| 480 |
Pat::TupleStruct(PatTupleStruct { elems, .. }) => Box::new( |
| 481 |
elems |
| 482 |
.into_iter() |
| 483 |
.flat_map(|p| param_names(p, RecordType::Debug)), |
| 484 |
), |
| 485 |
|
| 486 |
// The above *should* cover all cases of irrefutable patterns, |
| 487 |
// but we purposefully don't do any funny business here |
| 488 |
// (such as panicking) because that would obscure rustc's |
| 489 |
// much more informative error message. |
| 490 |
_ => Box::new(iter::empty()), |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
/// The specific async code pattern that was detected |
| 495 |
enum AsyncKind<'a> { |
| 496 |
/// Immediately-invoked async fn, as generated by `async-trait <= 0.1.43`: |
| 497 |
/// `async fn foo<...>(...) {...}; Box::pin(foo<...>(...))` |
| 498 |
Function(&'a ItemFn), |
| 499 |
/// A function returning an async (move) block, optionally `Box::pin`-ed, |
| 500 |
/// as generated by `async-trait >= 0.1.44`: |
| 501 |
/// `Box::pin(async move { ... })` |
| 502 |
Async { |
| 503 |
async_expr: &'a ExprAsync, |
| 504 |
pinned_box: bool, |
| 505 |
}, |
| 506 |
} |
| 507 |
|
| 508 |
pub(crate) struct AsyncInfo<'block> { |
| 509 |
// statement that must be patched |
| 510 |
source_stmt: &'block Stmt, |
| 511 |
kind: AsyncKind<'block>, |
| 512 |
self_type: Option<TypePath>, |
| 513 |
input: &'block ItemFn, |
| 514 |
} |
| 515 |
|
| 516 |
impl<'block> AsyncInfo<'block> { |
| 517 |
/// Get the AST of the inner function we need to hook, if it looks like a |
| 518 |
/// manual future implementation. |
| 519 |
/// |
| 520 |
/// When we are given a function that returns a (pinned) future containing the |
| 521 |
/// user logic, it is that (pinned) future that needs to be instrumented. |
| 522 |
/// Were we to instrument its parent, we would only collect information |
| 523 |
/// regarding the allocation of that future, and not its own span of execution. |
| 524 |
/// |
| 525 |
/// We inspect the block of the function to find if it matches any of the |
| 526 |
/// following patterns: |
| 527 |
/// |
| 528 |
/// - Immediately-invoked async fn, as generated by `async-trait <= 0.1.43`: |
| 529 |
/// `async fn foo<...>(...) {...}; Box::pin(foo<...>(...))` |
| 530 |
/// |
| 531 |
/// - A function returning an async (move) block, optionally `Box::pin`-ed, |
| 532 |
/// as generated by `async-trait >= 0.1.44`: |
| 533 |
/// `Box::pin(async move { ... })` |
| 534 |
/// |
| 535 |
/// We the return the statement that must be instrumented, along with some |
| 536 |
/// other information. |
| 537 |
/// 'gen_body' will then be able to use that information to instrument the |
| 538 |
/// proper function/future. |
| 539 |
/// |
| 540 |
/// (this follows the approach suggested in |
| 541 |
/// https://github.com/dtolnay/async-trait/issues/45#issuecomment-571245673) |
| 542 |
pub(crate) fn from_fn(input: &'block ItemFn) -> Option<Self> { |
| 543 |
// are we in an async context? If yes, this isn't a manual async-like pattern |
| 544 |
if input.sig.asyncness.is_some() { |
| 545 |
return None; |
| 546 |
} |
| 547 |
|
| 548 |
let block = &input.block; |
| 549 |
|
| 550 |
// list of async functions declared inside the block |
| 551 |
let inside_funs = block.stmts.iter().filter_map(|stmt| { |
| 552 |
if let Stmt::Item(Item::Fn(fun)) = &stmt { |
| 553 |
// If the function is async, this is a candidate |
| 554 |
if fun.sig.asyncness.is_some() { |
| 555 |
return Some((stmt, fun)); |
| 556 |
} |
| 557 |
} |
| 558 |
None |
| 559 |
}); |
| 560 |
|
| 561 |
// last expression of the block: it determines the return value of the |
| 562 |
// block, this is quite likely a `Box::pin` statement or an async block |
| 563 |
let (last_expr_stmt, last_expr) = block.stmts.iter().rev().find_map(|stmt| { |
| 564 |
if let Stmt::Expr(expr, _semi) = stmt { |
| 565 |
Some((stmt, expr)) |
| 566 |
} else { |
| 567 |
None |
| 568 |
} |
| 569 |
})?; |
| 570 |
|
| 571 |
// is the last expression an async block? |
| 572 |
if let Expr::Async(async_expr) = last_expr { |
| 573 |
return Some(AsyncInfo { |
| 574 |
source_stmt: last_expr_stmt, |
| 575 |
kind: AsyncKind::Async { |
| 576 |
async_expr, |
| 577 |
pinned_box: false, |
| 578 |
}, |
| 579 |
self_type: None, |
| 580 |
input, |
| 581 |
}); |
| 582 |
} |
| 583 |
|
| 584 |
// is the last expression a function call? |
| 585 |
let (outside_func, outside_args) = match last_expr { |
| 586 |
Expr::Call(ExprCall { func, args, .. }) => (func, args), |
| 587 |
_ => return None, |
| 588 |
}; |
| 589 |
|
| 590 |
// is it a call to `Box::pin()`? |
| 591 |
let path = match outside_func.as_ref() { |
| 592 |
Expr::Path(path) => &path.path, |
| 593 |
_ => return None, |
| 594 |
}; |
| 595 |
if !path_to_string(path).ends_with("Box::pin") { |
| 596 |
return None; |
| 597 |
} |
| 598 |
|
| 599 |
// Does the call take an argument? If it doesn't, |
| 600 |
// it's not gonna compile anyway, but that's no reason |
| 601 |
// to (try to) perform an out of bounds access |
| 602 |
if outside_args.is_empty() { |
| 603 |
return None; |
| 604 |
} |
| 605 |
|
| 606 |
// Is the argument to Box::pin an async block that |
| 607 |
// captures its arguments? |
| 608 |
if let Expr::Async(async_expr) = &outside_args[0] { |
| 609 |
return Some(AsyncInfo { |
| 610 |
source_stmt: last_expr_stmt, |
| 611 |
kind: AsyncKind::Async { |
| 612 |
async_expr, |
| 613 |
pinned_box: true, |
| 614 |
}, |
| 615 |
self_type: None, |
| 616 |
input, |
| 617 |
}); |
| 618 |
} |
| 619 |
|
| 620 |
// Is the argument to Box::pin a function call itself? |
| 621 |
let func = match &outside_args[0] { |
| 622 |
Expr::Call(ExprCall { func, .. }) => func, |
| 623 |
_ => return None, |
| 624 |
}; |
| 625 |
|
| 626 |
// "stringify" the path of the function called |
| 627 |
let func_name = match **func { |
| 628 |
Expr::Path(ref func_path) => path_to_string(&func_path.path), |
| 629 |
_ => return None, |
| 630 |
}; |
| 631 |
|
| 632 |
// Was that function defined inside of the current block? |
| 633 |
// If so, retrieve the statement where it was declared and the function itself |
| 634 |
let (stmt_func_declaration, func) = inside_funs |
| 635 |
.into_iter() |
| 636 |
.find(|(_, fun)| fun.sig.ident == func_name)?; |
| 637 |
|
| 638 |
// If "_self" is present as an argument, we store its type to be able to rewrite "Self" (the |
| 639 |
// parameter type) with the type of "_self" |
| 640 |
let mut self_type = None; |
| 641 |
for arg in &func.sig.inputs { |
| 642 |
if let FnArg::Typed(ty) = arg { |
| 643 |
if let Pat::Ident(PatIdent { ref ident, .. }) = *ty.pat { |
| 644 |
if ident == "_self" { |
| 645 |
let mut ty = *ty.ty.clone(); |
| 646 |
// extract the inner type if the argument is "&self" or "&mut self" |
| 647 |
if let Type::Reference(syn::TypeReference { elem, .. }) = ty { |
| 648 |
ty = *elem; |
| 649 |
} |
| 650 |
|
| 651 |
if let Type::Path(tp) = ty { |
| 652 |
self_type = Some(tp); |
| 653 |
break; |
| 654 |
} |
| 655 |
} |
| 656 |
} |
| 657 |
} |
| 658 |
} |
| 659 |
|
| 660 |
Some(AsyncInfo { |
| 661 |
source_stmt: stmt_func_declaration, |
| 662 |
kind: AsyncKind::Function(func), |
| 663 |
self_type, |
| 664 |
input, |
| 665 |
}) |
| 666 |
} |
| 667 |
|
| 668 |
pub(crate) fn gen_async( |
| 669 |
self, |
| 670 |
args: InstrumentArgs, |
| 671 |
instrumented_function_name: &str, |
| 672 |
) -> Result<proc_macro::TokenStream, syn::Error> { |
| 673 |
// let's rewrite some statements! |
| 674 |
let mut out_stmts: Vec<TokenStream> = self |
| 675 |
.input |
| 676 |
.block |
| 677 |
.stmts |
| 678 |
.iter() |
| 679 |
.map(|stmt| stmt.to_token_stream()) |
| 680 |
.collect(); |
| 681 |
|
| 682 |
if let Some((iter, _stmt)) = self |
| 683 |
.input |
| 684 |
.block |
| 685 |
.stmts |
| 686 |
.iter() |
| 687 |
.enumerate() |
| 688 |
.find(|(_iter, stmt)| *stmt == self.source_stmt) |
| 689 |
{ |
| 690 |
// instrument the future by rewriting the corresponding statement |
| 691 |
out_stmts[iter] = match self.kind { |
| 692 |
// `Box::pin(immediately_invoked_async_fn())` |
| 693 |
AsyncKind::Function(fun) => { |
| 694 |
let fun = MaybeItemFn::from(fun.clone()); |
| 695 |
gen_function( |
| 696 |
fun.as_ref(), |
| 697 |
args, |
| 698 |
instrumented_function_name, |
| 699 |
self.self_type.as_ref(), |
| 700 |
) |
| 701 |
} |
| 702 |
// `async move { ... }`, optionally pinned |
| 703 |
AsyncKind::Async { |
| 704 |
async_expr, |
| 705 |
pinned_box, |
| 706 |
} => { |
| 707 |
let instrumented_block = gen_block( |
| 708 |
&async_expr.block, |
| 709 |
&self.input.sig.inputs, |
| 710 |
true, |
| 711 |
args, |
| 712 |
instrumented_function_name, |
| 713 |
None, |
| 714 |
); |
| 715 |
let async_attrs = &async_expr.attrs; |
| 716 |
if pinned_box { |
| 717 |
quote! { |
| 718 |
Box::pin(#(#async_attrs) * async move { #instrumented_block }) |
| 719 |
} |
| 720 |
} else { |
| 721 |
quote! { |
| 722 |
#(#async_attrs) * async move { #instrumented_block } |
| 723 |
} |
| 724 |
} |
| 725 |
} |
| 726 |
}; |
| 727 |
} |
| 728 |
|
| 729 |
let vis = &self.input.vis; |
| 730 |
let sig = &self.input.sig; |
| 731 |
let attrs = &self.input.attrs; |
| 732 |
Ok(quote!( |
| 733 |
#(#attrs) * |
| 734 |
#vis #sig { |
| 735 |
#(#out_stmts) * |
| 736 |
} |
| 737 |
) |
| 738 |
.into()) |
| 739 |
} |
| 740 |
} |
| 741 |
|
| 742 |
// Return a path as a String |
| 743 |
fn path_to_string(path: &Path) -> String { |
| 744 |
use std::fmt::Write; |
| 745 |
// some heuristic to prevent too many allocations |
| 746 |
let mut res = String::with_capacity(path.segments.len() * 5); |
| 747 |
for i in 0..path.segments.len() { |
| 748 |
write!(&mut res, "{}", path.segments[i].ident) |
| 749 |
.expect("writing to a String should never fail"); |
| 750 |
if i < path.segments.len() - 1 { |
| 751 |
res.push_str("::"); |
| 752 |
} |
| 753 |
} |
| 754 |
res |
| 755 |
} |
| 756 |
|
| 757 |
/// A visitor struct to replace idents and types in some piece |
| 758 |
/// of code (e.g. the "self" and "Self" tokens in user-supplied |
| 759 |
/// fields expressions when the function is generated by an old |
| 760 |
/// version of async-trait). |
| 761 |
struct IdentAndTypesRenamer<'a> { |
| 762 |
types: Vec<(&'a str, TypePath)>, |
| 763 |
idents: Vec<(Ident, Ident)>, |
| 764 |
} |
| 765 |
|
| 766 |
impl<'a> VisitMut for IdentAndTypesRenamer<'a> { |
| 767 |
// we deliberately compare strings because we want to ignore the spans |
| 768 |
// If we apply clippy's lint, the behavior changes |
| 769 |
#[allow(clippy::cmp_owned)] |
| 770 |
fn visit_ident_mut(&mut self, id: &mut Ident) { |
| 771 |
for (old_ident, new_ident) in &self.idents { |
| 772 |
if id.to_string() == old_ident.to_string() { |
| 773 |
*id = new_ident.clone(); |
| 774 |
} |
| 775 |
} |
| 776 |
} |
| 777 |
|
| 778 |
fn visit_type_mut(&mut self, ty: &mut Type) { |
| 779 |
for (type_name, new_type) in &self.types { |
| 780 |
if let Type::Path(TypePath { path, .. }) = ty { |
| 781 |
if path_to_string(path) == *type_name { |
| 782 |
*ty = Type::Path(new_type.clone()); |
| 783 |
} |
| 784 |
} |
| 785 |
} |
| 786 |
} |
| 787 |
} |
| 788 |
|
| 789 |
// A visitor struct that replace an async block by its patched version |
| 790 |
struct AsyncTraitBlockReplacer<'a> { |
| 791 |
block: &'a Block, |
| 792 |
patched_block: Block, |
| 793 |
} |
| 794 |
|
| 795 |
impl<'a> VisitMut for AsyncTraitBlockReplacer<'a> { |
| 796 |
fn visit_block_mut(&mut self, i: &mut Block) { |
| 797 |
if i == self.block { |
| 798 |
*i = self.patched_block.clone(); |
| 799 |
} |
| 800 |
} |
| 801 |
} |
| 802 |
|
| 803 |
// Replaces any `impl Trait` with `_` so it can be used as the type in |
| 804 |
// a `let` statement's LHS. |
| 805 |
struct ImplTraitEraser; |
| 806 |
|
| 807 |
impl VisitMut for ImplTraitEraser { |
| 808 |
fn visit_type_mut(&mut self, t: &mut Type) { |
| 809 |
if let Type::ImplTrait(..) = t { |
| 810 |
*t = syn::TypeInfer { |
| 811 |
underscore_token: Token), |
| 812 |
} |
| 813 |
.into(); |
| 814 |
} else { |
| 815 |
syn::visit_mut::visit_type_mut(self, t); |
| 816 |
} |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
fn erase_impl_trait(ty: &Type) -> Type { |
| 821 |
let mut ty = ty.clone(); |
| 822 |
ImplTraitEraser.visit_type_mut(&mut ty); |
| 823 |
ty |
| 824 |
} |