Skip to content

Commit c3673c4

Browse files
Stjepan Glavinayoshuawuyts
Stjepan Glavina
authored andcommitted
Named arguments (#1)
Signed-off-by: Yoshua Wuyts <yoshuawuyts@gmail.com>
1 parent 3f56908 commit c3673c4

File tree

2 files changed

+23
-20
lines changed

2 files changed

+23
-20
lines changed

async-log-attributes/src/lib.rs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
extern crate proc_macro;
88

99
use proc_macro::TokenStream;
10-
use quote::quote;
10+
use quote::{quote, quote_spanned};
11+
use syn::spanned::Spanned;
1112

1213
/// Defines the `instrument` function.
1314
#[proc_macro_attribute]
@@ -27,23 +28,25 @@ pub fn instrument(_attr: TokenStream, item: TokenStream) -> TokenStream {
2728
let output = &input.decl.output;
2829
let body = &input.block.stmts;
2930

30-
let args: Vec<syn::Pat> = inputs
31-
.pairs()
32-
.filter_map(|pair| match pair.into_value() {
33-
syn::FnArg::Captured(arg) => Some(arg.pat.clone()),
34-
_ => return None,
35-
})
36-
.collect();
37-
38-
let names: String = args
39-
.iter()
40-
.enumerate()
41-
.map(|(i, _arg)| {
42-
let mut string = format!(", arg_{:?}", i);
43-
string.push_str("={:?}");
44-
string
45-
})
46-
.collect();
31+
let mut names = String::new();
32+
let mut args = Vec::<syn::Pat>::new();
33+
34+
for fn_arg in inputs {
35+
if let syn::FnArg::Captured(arg) = fn_arg {
36+
let pat = arg.pat.clone();
37+
38+
if let syn::Pat::Ident(pat_ident) = &pat {
39+
names.push_str(&format!(", {}={{:?}}", pat_ident.ident));
40+
} else {
41+
let tokens = quote_spanned! { fn_arg.span() =>
42+
compile_error!("instrumented functions need to name arguments");
43+
};
44+
return TokenStream::from(tokens);
45+
}
46+
47+
args.push(pat);
48+
}
49+
}
4750

4851
let result = quote! {
4952
#(#attrs)*

examples/trace.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use async_log::span;
1+
use async_log::{instrument, span};
22
use log::info;
33

44
fn setup_logger() {
@@ -24,7 +24,7 @@ fn main() {
2424
})
2525
}
2626

27-
#[async_log::instrument]
27+
#[instrument]
2828
fn inner(y: &str) {
2929
info!("another nice value, y={}", y);
3030
}

0 commit comments

Comments
 (0)