1use std::iter;
2
3use proc_macro2::TokenStream;
4use quote::{quote, quote_spanned, ToTokens};
5use syn::visit_mut::VisitMut;
6use 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
12use crate::{
13 attr::{Field, Fields, FormatMode, InstrumentArgs, Level},
14 MaybeItemFn, MaybeItemFnRef,
15};
16
17pub(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 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 (syn::parse_quote! { () }, ident.span())
59 };
60 let fake_return_edge = quote_spanned! {return_span=>
67 #[allow(
68 unknown_lints, unreachable_code, clippy::diverging_sub_expression,
69 clippy::let_unit_value, clippy::unreachable, clippy::let_with_type_underscore,
70 clippy::empty_loop
71 )]
72 if false {
73 let __tracing_attr_fake_return: #return_type = loop {};
74 return __tracing_attr_fake_return;
75 }
76 };
77 let block = quote! {
78 {
79 #fake_return_edge
80 #block
81 }
82 };
83
84 let body = gen_block(
85 &block,
86 params,
87 asyncness.is_some(),
88 args,
89 instrumented_function_name,
90 self_type,
91 );
92
93 quote!(
94 #(#outer_attrs) *
95 #vis #constness #asyncness #unsafety #abi fn #ident<#gen_params>(#params) #output
96 #where_clause
97 {
98 #(#inner_attrs) *
99 #warnings
100 #body
101 }
102 )
103}
104
105fn gen_block<B: ToTokens>(
107 block: &B,
108 params: &Punctuated<FnArg, Token![,]>,
109 async_context: bool,
110 mut args: InstrumentArgs,
111 instrumented_function_name: &str,
112 self_type: Option<&TypePath>,
113) -> proc_macro2::TokenStream {
114 let span_name = args
116 .name
118 .as_ref()
119 .map(|name| quote!(#name))
120 .unwrap_or_else(|| quote!(#instrumented_function_name));
121
122 let args_level = args.level();
123 let level = args_level.clone();
124
125 let follows_from = args.follows_from.iter();
126 let follows_from = quote! {
127 #(for cause in #follows_from {
128 __tracing_attr_span.follows_from(cause);
129 })*
130 };
131
132 let span = (|| {
134 let param_names: Vec<(Ident, (Ident, RecordType))> = params
137 .clone()
138 .into_iter()
139 .flat_map(|param| match param {
140 FnArg::Typed(PatType { pat, ty, .. }) => {
141 param_names(*pat, RecordType::parse_from_ty(&ty))
142 }
143 FnArg::Receiver(_) => Box::new(iter::once((
144 Ident::new("self", param.span()),
145 RecordType::Debug,
146 ))),
147 })
148 .map(|(x, record_type)| {
159 if self_type.is_some() && x == "_self" {
162 (Ident::new("self", x.span()), (x, record_type))
163 } else {
164 (x.clone(), (x, record_type))
165 }
166 })
167 .collect();
168
169 for skip in &args.skips {
170 if !param_names.iter().map(|(user, _)| user).any(|y| y == skip) {
171 return quote_spanned! {skip.span()=>
172 compile_error!("attempting to skip non-existent parameter")
173 };
174 }
175 }
176
177 let target = args.target();
178
179 let parent = args.parent.iter();
180
181 let quoted_fields: Vec<_> = param_names
183 .iter()
184 .filter(|(param, _)| {
185 if args.skip_all || args.skips.contains(param) {
186 return false;
187 }
188
189 if let Some(ref fields) = args.fields {
192 fields.0.iter().all(|Field { ref name, .. }| {
193 let first = name.first();
194 first != name.last() || !first.iter().any(|name| name == ¶m)
195 })
196 } else {
197 true
198 }
199 })
200 .map(|(user_name, (real_name, record_type))| match record_type {
201 RecordType::Value => quote!(#user_name = #real_name),
202 RecordType::Debug => quote!(#user_name = tracing::field::debug(&#real_name)),
203 })
204 .collect();
205
206 if let Some(Fields(ref mut fields)) = args.fields {
208 let mut replacer = IdentAndTypesRenamer {
209 idents: param_names.into_iter().map(|(a, (b, _))| (a, b)).collect(),
210 types: Vec::new(),
211 };
212
213 if let Some(self_type) = self_type {
216 replacer.types.push(("Self", self_type.clone()));
217 }
218
219 for e in fields.iter_mut().filter_map(|f| f.value.as_mut()) {
220 syn::visit_mut::visit_expr_mut(&mut replacer, e);
221 }
222 }
223
224 let custom_fields = &args.fields;
225
226 quote!(tracing::span!(
227 target: #target,
228 #(parent: #parent,)*
229 #level,
230 #span_name,
231 #(#quoted_fields,)*
232 #custom_fields
233
234 ))
235 })();
236
237 let target = args.target();
238
239 let err_event = match args.err_args {
240 Some(event_args) => {
241 let level_tokens = event_args.level(Level::Error);
242 match event_args.mode {
243 FormatMode::Default | FormatMode::Display => Some(quote!(
244 tracing::event!(target: #target, #level_tokens, error = %e)
245 )),
246 FormatMode::Debug => Some(quote!(
247 tracing::event!(target: #target, #level_tokens, error = ?e)
248 )),
249 }
250 }
251 _ => None,
252 };
253
254 let ret_event = match args.ret_args {
255 Some(event_args) => {
256 let level_tokens = event_args.level(args_level);
257 match event_args.mode {
258 FormatMode::Display => Some(quote!(
259 tracing::event!(target: #target, #level_tokens, return = %x)
260 )),
261 FormatMode::Default | FormatMode::Debug => Some(quote!(
262 tracing::event!(target: #target, #level_tokens, return = ?x)
263 )),
264 }
265 }
266 _ => None,
267 };
268
269 if async_context {
277 let mk_fut = match (err_event, ret_event) {
278 (Some(err_event), Some(ret_event)) => quote_spanned!(block.span()=>
279 async move {
280 let __match_scrutinee = async move #block.await;
281 match __match_scrutinee {
282 #[allow(clippy::unit_arg)]
283 Ok(x) => {
284 #ret_event;
285 Ok(x)
286 },
287 Err(e) => {
288 #err_event;
289 Err(e)
290 }
291 }
292 }
293 ),
294 (Some(err_event), None) => quote_spanned!(block.span()=>
295 async move {
296 match async move #block.await {
297 #[allow(clippy::unit_arg)]
298 Ok(x) => Ok(x),
299 Err(e) => {
300 #err_event;
301 Err(e)
302 }
303 }
304 }
305 ),
306 (None, Some(ret_event)) => quote_spanned!(block.span()=>
307 async move {
308 let x = async move #block.await;
309 #ret_event;
310 x
311 }
312 ),
313 (None, None) => quote_spanned!(block.span()=>
314 async move #block
315 ),
316 };
317
318 return quote!(
319 let __tracing_attr_span = #span;
320 let __tracing_instrument_future = #mk_fut;
321 if !__tracing_attr_span.is_disabled() {
322 #follows_from
323 tracing::Instrument::instrument(
324 __tracing_instrument_future,
325 __tracing_attr_span
326 )
327 .await
328 } else {
329 __tracing_instrument_future.await
330 }
331 );
332 }
333
334 let span = quote!(
335 let __tracing_attr_span;
346 let __tracing_attr_guard;
347 if tracing::level_enabled!(#level) || tracing::if_log_enabled!(#level, {true} else {false}) {
348 __tracing_attr_span = #span;
349 #follows_from
350 __tracing_attr_guard = __tracing_attr_span.enter();
351 }
352 );
353
354 match (err_event, ret_event) {
355 (Some(err_event), Some(ret_event)) => quote_spanned! {block.span()=>
356 #span
357 #[allow(clippy::redundant_closure_call)]
358 match (move || #block)() {
359 #[allow(clippy::unit_arg)]
360 Ok(x) => {
361 #ret_event;
362 Ok(x)
363 },
364 Err(e) => {
365 #err_event;
366 Err(e)
367 }
368 }
369 },
370 (Some(err_event), None) => quote_spanned!(block.span()=>
371 #span
372 #[allow(clippy::redundant_closure_call)]
373 match (move || #block)() {
374 #[allow(clippy::unit_arg)]
375 Ok(x) => Ok(x),
376 Err(e) => {
377 #err_event;
378 Err(e)
379 }
380 }
381 ),
382 (None, Some(ret_event)) => quote_spanned!(block.span()=>
383 #span
384 #[allow(clippy::redundant_closure_call)]
385 let x = (move || #block)();
386 #ret_event;
387 x
388 ),
389 (None, None) => quote_spanned!(block.span() =>
390 #[allow(clippy::suspicious_else_formatting)]
395 {
396 #span
397 #[warn(clippy::suspicious_else_formatting)]
399 #block
400 }
401 ),
402 }
403}
404
405enum RecordType {
407 Value,
409 Debug,
411}
412
413impl RecordType {
414 const TYPES_FOR_VALUE: &'static [&'static str] = &[
416 "bool",
417 "str",
418 "u8",
419 "i8",
420 "u16",
421 "i16",
422 "u32",
423 "i32",
424 "u64",
425 "i64",
426 "u128",
427 "i128",
428 "f32",
429 "f64",
430 "usize",
431 "isize",
432 "String",
433 "NonZeroU8",
434 "NonZeroI8",
435 "NonZeroU16",
436 "NonZeroI16",
437 "NonZeroU32",
438 "NonZeroI32",
439 "NonZeroU64",
440 "NonZeroI64",
441 "NonZeroU128",
442 "NonZeroI128",
443 "NonZeroUsize",
444 "NonZeroIsize",
445 "Wrapping",
446 ];
447
448 fn parse_from_ty(ty: &Type) -> Self {
451 match ty {
452 Type::Path(TypePath { path, .. })
453 if path
454 .segments
455 .iter()
456 .last()
457 .map(|path_segment| {
458 let ident = path_segment.ident.to_string();
459 Self::TYPES_FOR_VALUE.iter().any(|&t| t == ident)
460 })
461 .unwrap_or(false) =>
462 {
463 RecordType::Value
464 }
465 Type::Reference(syn::TypeReference { elem, .. }) => RecordType::parse_from_ty(elem),
466 _ => RecordType::Debug,
467 }
468 }
469}
470
471fn param_names(pat: Pat, record_type: RecordType) -> Box<dyn Iterator<Item = (Ident, RecordType)>> {
472 match pat {
473 Pat::Ident(PatIdent { ident, .. }) => Box::new(iter::once((ident, record_type))),
474 Pat::Reference(PatReference { pat, .. }) => param_names(*pat, record_type),
475 Pat::Struct(PatStruct { fields, .. }) => Box::new(
480 fields
481 .into_iter()
482 .flat_map(|FieldPat { pat, .. }| param_names(*pat, RecordType::Debug)),
483 ),
484 Pat::Tuple(PatTuple { elems, .. }) => Box::new(
485 elems
486 .into_iter()
487 .flat_map(|p| param_names(p, RecordType::Debug)),
488 ),
489 Pat::TupleStruct(PatTupleStruct { elems, .. }) => Box::new(
490 elems
491 .into_iter()
492 .flat_map(|p| param_names(p, RecordType::Debug)),
493 ),
494
495 _ => Box::new(iter::empty()),
500 }
501}
502
503enum AsyncKind<'a> {
505 Function(&'a ItemFn),
508 Async {
512 async_expr: &'a ExprAsync,
513 pinned_box: bool,
514 },
515}
516
517pub(crate) struct AsyncInfo<'block> {
518 source_stmt: &'block Stmt,
520 kind: AsyncKind<'block>,
521 self_type: Option<TypePath>,
522 input: &'block ItemFn,
523}
524
525impl<'block> AsyncInfo<'block> {
526 pub(crate) fn from_fn(input: &'block ItemFn) -> Option<Self> {
552 if input.sig.asyncness.is_some() {
554 return None;
555 }
556
557 let block = &input.block;
558
559 let inside_funs = block.stmts.iter().filter_map(|stmt| {
561 if let Stmt::Item(Item::Fn(fun)) = &stmt {
562 if fun.sig.asyncness.is_some() {
564 return Some((stmt, fun));
565 }
566 }
567 None
568 });
569
570 let (last_expr_stmt, last_expr) = block.stmts.iter().rev().find_map(|stmt| {
573 if let Stmt::Expr(expr, _semi) = stmt {
574 Some((stmt, expr))
575 } else {
576 None
577 }
578 })?;
579
580 if let Expr::Async(async_expr) = last_expr {
582 return Some(AsyncInfo {
583 source_stmt: last_expr_stmt,
584 kind: AsyncKind::Async {
585 async_expr,
586 pinned_box: false,
587 },
588 self_type: None,
589 input,
590 });
591 }
592
593 let (outside_func, outside_args) = match last_expr {
595 Expr::Call(ExprCall { func, args, .. }) => (func, args),
596 _ => return None,
597 };
598
599 let path = match outside_func.as_ref() {
601 Expr::Path(path) => &path.path,
602 _ => return None,
603 };
604 if !path_to_string(path).ends_with("Box::pin") {
605 return None;
606 }
607
608 if outside_args.is_empty() {
612 return None;
613 }
614
615 if let Expr::Async(async_expr) = &outside_args[0] {
618 return Some(AsyncInfo {
619 source_stmt: last_expr_stmt,
620 kind: AsyncKind::Async {
621 async_expr,
622 pinned_box: true,
623 },
624 self_type: None,
625 input,
626 });
627 }
628
629 let func = match &outside_args[0] {
631 Expr::Call(ExprCall { func, .. }) => func,
632 _ => return None,
633 };
634
635 let func_name = match **func {
637 Expr::Path(ref func_path) => path_to_string(&func_path.path),
638 _ => return None,
639 };
640
641 let (stmt_func_declaration, func) = inside_funs
644 .into_iter()
645 .find(|(_, fun)| fun.sig.ident == func_name)?;
646
647 let mut self_type = None;
650 for arg in &func.sig.inputs {
651 if let FnArg::Typed(ty) = arg {
652 if let Pat::Ident(PatIdent { ref ident, .. }) = *ty.pat {
653 if ident == "_self" {
654 let mut ty = *ty.ty.clone();
655 if let Type::Reference(syn::TypeReference { elem, .. }) = ty {
657 ty = *elem;
658 }
659
660 if let Type::Path(tp) = ty {
661 self_type = Some(tp);
662 break;
663 }
664 }
665 }
666 }
667 }
668
669 Some(AsyncInfo {
670 source_stmt: stmt_func_declaration,
671 kind: AsyncKind::Function(func),
672 self_type,
673 input,
674 })
675 }
676
677 pub(crate) fn gen_async(
678 self,
679 args: InstrumentArgs,
680 instrumented_function_name: &str,
681 ) -> Result<proc_macro::TokenStream, syn::Error> {
682 let mut out_stmts: Vec<TokenStream> = self
684 .input
685 .block
686 .stmts
687 .iter()
688 .map(|stmt| stmt.to_token_stream())
689 .collect();
690
691 if let Some((iter, _stmt)) = self
692 .input
693 .block
694 .stmts
695 .iter()
696 .enumerate()
697 .find(|(_iter, stmt)| *stmt == self.source_stmt)
698 {
699 out_stmts[iter] = match self.kind {
701 AsyncKind::Function(fun) => {
703 let fun = MaybeItemFn::from(fun.clone());
704 gen_function(
705 fun.as_ref(),
706 args,
707 instrumented_function_name,
708 self.self_type.as_ref(),
709 )
710 }
711 AsyncKind::Async {
713 async_expr,
714 pinned_box,
715 } => {
716 let instrumented_block = gen_block(
717 &async_expr.block,
718 &self.input.sig.inputs,
719 true,
720 args,
721 instrumented_function_name,
722 None,
723 );
724 let async_attrs = &async_expr.attrs;
725 if pinned_box {
726 quote! {
727 Box::pin(#(#async_attrs) * async move { #instrumented_block })
728 }
729 } else {
730 quote! {
731 #(#async_attrs) * async move { #instrumented_block }
732 }
733 }
734 }
735 };
736 }
737
738 let vis = &self.input.vis;
739 let sig = &self.input.sig;
740 let attrs = &self.input.attrs;
741 Ok(quote!(
742 #(#attrs) *
743 #vis #sig {
744 #(#out_stmts) *
745 }
746 )
747 .into())
748 }
749}
750
751fn path_to_string(path: &Path) -> String {
753 use std::fmt::Write;
754 let mut res = String::with_capacity(path.segments.len() * 5);
756 for i in 0..path.segments.len() {
757 write!(&mut res, "{}", path.segments[i].ident)
758 .expect("writing to a String should never fail");
759 if i < path.segments.len() - 1 {
760 res.push_str("::");
761 }
762 }
763 res
764}
765
766struct IdentAndTypesRenamer<'a> {
771 types: Vec<(&'a str, TypePath)>,
772 idents: Vec<(Ident, Ident)>,
773}
774
775impl<'a> VisitMut for IdentAndTypesRenamer<'a> {
776 #[allow(clippy::cmp_owned)]
779 fn visit_ident_mut(&mut self, id: &mut Ident) {
780 for (old_ident, new_ident) in &self.idents {
781 if id.to_string() == old_ident.to_string() {
782 *id = new_ident.clone();
783 }
784 }
785 }
786
787 fn visit_type_mut(&mut self, ty: &mut Type) {
788 for (type_name, new_type) in &self.types {
789 if let Type::Path(TypePath { path, .. }) = ty {
790 if path_to_string(path) == *type_name {
791 *ty = Type::Path(new_type.clone());
792 }
793 }
794 }
795 }
796}
797
798struct AsyncTraitBlockReplacer<'a> {
800 block: &'a Block,
801 patched_block: Block,
802}
803
804impl<'a> VisitMut for AsyncTraitBlockReplacer<'a> {
805 fn visit_block_mut(&mut self, i: &mut Block) {
806 if i == self.block {
807 *i = self.patched_block.clone();
808 }
809 }
810}
811
812struct ImplTraitEraser;
815
816impl VisitMut for ImplTraitEraser {
817 fn visit_type_mut(&mut self, t: &mut Type) {
818 if let Type::ImplTrait(..) = t {
819 *t = syn::TypeInfer {
820 underscore_token: Token),
821 }
822 .into();
823 } else {
824 syn::visit_mut::visit_type_mut(self, t);
825 }
826 }
827}
828
829fn erase_impl_trait(ty: &Type) -> Type {
830 let mut ty = ty.clone();
831 ImplTraitEraser.visit_type_mut(&mut ty);
832 ty
833}