I'm trying to write a macro that will expand this:
let res = log_request_response!(client.my_call("friend".to_string(), 5));
Into this:
let res = {
debug!("Request: {}", args_separated_by_commas);
let res = client.my_call("friend".to_string(), 5);
debug!("Response: {}", res);
res
};
My attempt so far is something like this:
#[macro_export]
macro_rules! log_request_response_to_scuba {
($($client:ident)?.$call:ident($($arg:expr),*);) => {
let mut s = String::new();
$(
{
s.push_str(&format!("{:?}, ", $arg));
}
)*
s.truncate(s.len() - 2);
debug!("Request: {}", s);
// Somehow reconstruct the entire thing with res = at the start.
debug!("Response: {}", res);
res
};
}
But this fails to compile:
error: macro expansion ignores token `{` and any following
--> src/main.rs:10:13
|
10 | {
| ^
...
39 | let res = log_request_response_to_scuba!(client.my_call(hey, 5));
| ------------------------------------------------------ caused by the macro expansion here
|
= note: the usage of `log_request_response_to_scuba!` is likely invalid in expression context
If I remove the .
in between the client
and call
match it throws a different error about an ambiguous match (which makes sense).
So my first nitty gritty question is how do I match a dot? To me this match looks correct but apparently not.
Beyond that any help with making a macro that does what I want would be great. If it were a regex I'd just want this:
.*\((.*)\).*
Where I just capture the stuff inside the parentheses and split them. Then I use the 0th capture group to get the whole thing.
Thanks!