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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
#![recursion_limit = "256"]
extern crate proc_macro;
#[macro_use]
extern crate proc_macro_error;
use proc_macro2::TokenStream;
use proc_macro2::{Span, TokenTree};
use quote::{format_ident, quote_spanned};
use syn::spanned::Spanned;
use syn::{punctuated::Punctuated, visit_mut::VisitMut, *};
struct Args {
event: String,
enter_on_poll: bool,
}
impl Args {
fn parse(input: AttributeArgs) -> Args {
let name = match input.get(0) {
Some(arg0) => match arg0 {
NestedMeta::Lit(Lit::Str(name)) => name.value(),
_ => abort!(arg0.span(), "expected string literal"),
},
None => abort_call_site!("expected at least one string literal"),
};
let enter_on_poll = match input.get(1) {
Some(arg1) => match arg1 {
NestedMeta::Meta(Meta::NameValue(MetaNameValue {
path,
lit: Lit::Bool(b),
..
})) if path.is_ident("enter_on_poll") => b.value(),
_ => abort!(arg1.span(), "expected `enter_on_poll = <bool>`"),
},
None => false,
};
if input.len() > 2 {
abort_call_site!("too many arguments");
}
Args {
event: name,
enter_on_poll,
}
}
}
#[proc_macro_attribute]
#[proc_macro_error]
pub fn trace(
args: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(item as ItemFn);
let args = Args::parse(syn::parse_macro_input!(args as AttributeArgs));
let func_body = if let Some(internal_fun) =
get_async_trait_info(&input.block, input.sig.asyncness.is_some())
{
match internal_fun.kind {
AsyncTraitKind::Function(_) => {
unimplemented!("Please upgrade crate `async-trait` to a version higher than 0.1.44")
}
AsyncTraitKind::Async(async_expr) => {
let instrumented_block = gen_block(&async_expr.block, true, args);
let async_attrs = &async_expr.attrs;
quote! {
Box::pin(#(#async_attrs) * { #instrumented_block })
}
}
}
} else {
gen_block(&input.block, input.sig.asyncness.is_some(), args)
};
let ItemFn {
attrs,
vis,
mut sig,
..
} = input;
if sig.asyncness.is_some() {
let has_self = has_self_in_sig(&mut sig);
transform_sig(&mut sig, has_self, true);
}
let Signature {
output: return_type,
inputs: params,
unsafety,
constness,
abi,
ident,
generics:
Generics {
params: gen_params,
where_clause,
..
},
..
} = sig;
quote::quote!(
#(#attrs) *
#vis #constness #unsafety #abi fn #ident<#gen_params>(#params) #return_type
#where_clause
{
#func_body
}
)
.into()
}
fn gen_block(block: &Block, async_context: bool, args: Args) -> proc_macro2::TokenStream {
let event = args.event;
if async_context {
if args.enter_on_poll {
quote_spanned!(block.span()=>
minitrace::future::FutureExt::enter_on_poll(
async move { #block },
#event
)
)
} else {
quote_spanned!(block.span()=>
minitrace::future::FutureExt::in_span(
async move { #block },
minitrace::Span::enter_with_local_parent( #event )
)
)
}
} else {
if args.enter_on_poll {
abort_call_site!("`enter_on_poll` can not be applied on non-async function");
}
quote_spanned!(block.span()=>
let __guard = minitrace::local::LocalSpan::enter_with_local_parent( #event );
#block
)
}
}
fn transform_sig(sig: &mut Signature, has_self: bool, is_local: bool) {
sig.fn_token.span = sig.asyncness.take().unwrap().span;
let ret = match &sig.output {
ReturnType::Default => quote!(()),
ReturnType::Type(_, ret) => quote!(#ret),
};
let default_span = sig
.ident
.span()
.join(sig.paren_token.span)
.unwrap_or_else(|| sig.ident.span());
let mut lifetimes = CollectLifetimes::new("'life", default_span);
for arg in sig.inputs.iter_mut() {
match arg {
FnArg::Receiver(arg) => lifetimes.visit_receiver_mut(arg),
FnArg::Typed(arg) => lifetimes.visit_type_mut(&mut arg.ty),
}
}
for param in sig.generics.params.iter() {
match param {
GenericParam::Type(param) => {
let param = ¶m.ident;
let span = param.span();
where_clause_or_default(&mut sig.generics.where_clause)
.predicates
.push(parse_quote_spanned!(span=> #param: 'minitrace));
}
GenericParam::Lifetime(param) => {
let param = ¶m.lifetime;
let span = param.span();
where_clause_or_default(&mut sig.generics.where_clause)
.predicates
.push(parse_quote_spanned!(span=> #param: 'minitrace));
}
GenericParam::Const(_) => {}
}
}
if sig.generics.lt_token.is_none() {
sig.generics.lt_token = Some(Token));
}
if sig.generics.gt_token.is_none() {
sig.generics.gt_token = Some(Token);
}
for elided in lifetimes.elided {
sig.generics.params.push(parse_quote!(#elided));
where_clause_or_default(&mut sig.generics.where_clause)
.predicates
.push(parse_quote_spanned!(elided.span()=> #elided: 'minitrace));
}
sig.generics
.params
.push(parse_quote_spanned!(default_span=> 'minitrace));
if has_self {
let bound_span = sig.ident.span();
let bound = match sig.inputs.iter().next() {
Some(FnArg::Receiver(Receiver {
reference: Some(_),
mutability: None,
..
})) => Ident::new("Sync", bound_span),
Some(FnArg::Typed(arg))
if match (arg.pat.as_ref(), arg.ty.as_ref()) {
(Pat::Ident(pat), Type::Reference(ty)) => {
pat.ident == "self" && ty.mutability.is_none()
}
_ => false,
} =>
{
Ident::new("Sync", bound_span)
}
_ => Ident::new("Send", bound_span),
};
let where_clause = where_clause_or_default(&mut sig.generics.where_clause);
where_clause.predicates.push(if is_local {
parse_quote_spanned!(bound_span=> Self: 'minitrace)
} else {
parse_quote_spanned!(bound_span=> Self: ::core::marker::#bound + 'minitrace)
});
}
for (i, arg) in sig.inputs.iter_mut().enumerate() {
match arg {
FnArg::Receiver(Receiver {
reference: Some(_), ..
}) => {}
FnArg::Receiver(arg) => arg.mutability = None,
FnArg::Typed(arg) => {
if let Pat::Ident(ident) = &mut *arg.pat {
ident.by_ref = None;
ident.mutability = None;
} else {
let positional = positional_arg(i, &arg.pat);
let m = mut_pat(&mut arg.pat);
arg.pat = parse_quote!(#m #positional);
}
}
}
}
let ret_span = sig.ident.span();
let bounds = if is_local {
quote_spanned!(ret_span=> 'minitrace)
} else {
quote_spanned!(ret_span=> ::core::marker::Send + 'minitrace)
};
sig.output = parse_quote_spanned! {ret_span=>
-> impl ::core::future::Future<Output = #ret> + #bounds
};
}
struct CollectLifetimes {
pub elided: Vec<Lifetime>,
pub explicit: Vec<Lifetime>,
pub name: &'static str,
pub default_span: Span,
}
impl CollectLifetimes {
pub fn new(name: &'static str, default_span: Span) -> Self {
CollectLifetimes {
elided: Vec::new(),
explicit: Vec::new(),
name,
default_span,
}
}
fn visit_opt_lifetime(&mut self, lifetime: &mut Option<Lifetime>) {
match lifetime {
None => *lifetime = Some(self.next_lifetime(None)),
Some(lifetime) => self.visit_lifetime(lifetime),
}
}
fn visit_lifetime(&mut self, lifetime: &mut Lifetime) {
if lifetime.ident == "_" {
*lifetime = self.next_lifetime(lifetime.span());
} else {
self.explicit.push(lifetime.clone());
}
}
fn next_lifetime<S: Into<Option<Span>>>(&mut self, span: S) -> Lifetime {
let name = format!("{}{}", self.name, self.elided.len());
let span = span.into().unwrap_or(self.default_span);
let life = Lifetime::new(&name, span);
self.elided.push(life.clone());
life
}
}
impl VisitMut for CollectLifetimes {
fn visit_receiver_mut(&mut self, arg: &mut Receiver) {
if let Some((_, lifetime)) = &mut arg.reference {
self.visit_opt_lifetime(lifetime);
}
}
fn visit_type_reference_mut(&mut self, ty: &mut TypeReference) {
self.visit_opt_lifetime(&mut ty.lifetime);
visit_mut::visit_type_reference_mut(self, ty);
}
fn visit_generic_argument_mut(&mut self, gen: &mut GenericArgument) {
if let GenericArgument::Lifetime(lifetime) = gen {
self.visit_lifetime(lifetime);
}
visit_mut::visit_generic_argument_mut(self, gen);
}
}
fn positional_arg(i: usize, pat: &Pat) -> Ident {
format_ident!("__arg{}", i, span = pat.span())
}
fn mut_pat(pat: &mut Pat) -> Option<Token![mut]> {
let mut visitor = HasMutPat(None);
visitor.visit_pat_mut(pat);
visitor.0
}
fn has_self_in_sig(sig: &mut Signature) -> bool {
let mut visitor = HasSelf(false);
visitor.visit_signature_mut(sig);
visitor.0
}
fn has_self_in_token_stream(tokens: TokenStream) -> bool {
tokens.into_iter().any(|tt| match tt {
TokenTree::Ident(ident) => ident == "Self",
TokenTree::Group(group) => has_self_in_token_stream(group.stream()),
_ => false,
})
}
struct HasMutPat(Option<Token![mut]>);
impl VisitMut for HasMutPat {
fn visit_pat_ident_mut(&mut self, i: &mut PatIdent) {
if let Some(m) = i.mutability {
self.0 = Some(m);
} else {
visit_mut::visit_pat_ident_mut(self, i);
}
}
}
struct HasSelf(bool);
impl VisitMut for HasSelf {
fn visit_expr_path_mut(&mut self, expr: &mut ExprPath) {
self.0 |= expr.path.segments[0].ident == "Self";
visit_mut::visit_expr_path_mut(self, expr);
}
fn visit_pat_path_mut(&mut self, pat: &mut PatPath) {
self.0 |= pat.path.segments[0].ident == "Self";
visit_mut::visit_pat_path_mut(self, pat);
}
fn visit_type_path_mut(&mut self, ty: &mut TypePath) {
self.0 |= ty.path.segments[0].ident == "Self";
visit_mut::visit_type_path_mut(self, ty);
}
fn visit_receiver_mut(&mut self, _arg: &mut Receiver) {
self.0 = true;
}
fn visit_item_mut(&mut self, _: &mut Item) {
}
fn visit_macro_mut(&mut self, mac: &mut Macro) {
if !contains_fn(mac.tokens.clone()) {
self.0 |= has_self_in_token_stream(mac.tokens.clone());
}
}
}
fn contains_fn(tokens: TokenStream) -> bool {
tokens.into_iter().any(|tt| match tt {
TokenTree::Ident(ident) => ident == "fn",
TokenTree::Group(group) => contains_fn(group.stream()),
_ => false,
})
}
fn where_clause_or_default(clause: &mut Option<WhereClause>) -> &mut WhereClause {
clause.get_or_insert_with(|| WhereClause {
where_token: Default::default(),
predicates: Punctuated::new(),
})
}
enum AsyncTraitKind<'a> {
Function(&'a ItemFn),
Async(&'a ExprAsync),
}
struct AsyncTraitInfo<'a> {
_source_stmt: &'a Stmt,
kind: AsyncTraitKind<'a>,
}
fn get_async_trait_info(block: &Block, block_is_async: bool) -> Option<AsyncTraitInfo<'_>> {
if block_is_async {
return None;
}
let inside_funs = block.stmts.iter().filter_map(|stmt| {
if let Stmt::Item(Item::Fn(fun)) = &stmt {
if fun.sig.asyncness.is_some() {
return Some((stmt, fun));
}
}
None
});
let (last_expr_stmt, last_expr) = block.stmts.iter().rev().find_map(|stmt| {
if let Stmt::Expr(expr) = stmt {
Some((stmt, expr))
} else {
None
}
})?;
let (outside_func, outside_args) = match last_expr {
Expr::Call(ExprCall { func, args, .. }) => (func, args),
_ => return None,
};
let path = match outside_func.as_ref() {
Expr::Path(path) => &path.path,
_ => return None,
};
if !path_to_string(path).ends_with("Box::pin") {
return None;
}
if outside_args.is_empty() {
return None;
}
if let Expr::Async(async_expr) = &outside_args[0] {
async_expr.capture?;
return Some(AsyncTraitInfo {
_source_stmt: last_expr_stmt,
kind: AsyncTraitKind::Async(async_expr),
});
}
let func = match &outside_args[0] {
Expr::Call(ExprCall { func, .. }) => func,
_ => return None,
};
let func_name = match **func {
Expr::Path(ref func_path) => path_to_string(&func_path.path),
_ => return None,
};
let (stmt_func_declaration, func) = inside_funs
.into_iter()
.find(|(_, fun)| fun.sig.ident == func_name)?;
Some(AsyncTraitInfo {
_source_stmt: stmt_func_declaration,
kind: AsyncTraitKind::Function(func),
})
}
fn path_to_string(path: &Path) -> String {
use std::fmt::Write;
let mut res = String::with_capacity(path.segments.len() * 5);
for i in 0..path.segments.len() {
write!(&mut res, "{}", path.segments[i].ident)
.expect("writing to a String should never fail");
if i < path.segments.len() - 1 {
res.push_str("::");
}
}
res
}