kexplain/lib.rs
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
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use syn::{parse_macro_input, parse_quote, ItemFn};
/// Unwrap the Option value or break.
macro_rules! or_continue {
( $wrapper:expr ) => {
match $wrapper {
Some(v) => v,
None => continue,
}
};
}
fn has_attr(attrs: &[syn::Attribute], attr_name: &str) -> bool {
attrs.iter().any(|a| {
a.parse_meta()
.ok()
.map(|meta| meta.path().is_ident(attr_name))
.unwrap_or(false)
})
}
fn has_skip_attr(attrs: &[syn::Attribute]) -> bool {
has_attr(attrs, "skip")
}
fn has_no_expr_attr(attrs: &[syn::Attribute]) -> bool {
has_attr(attrs, "no_expr")
}
fn find_ident(pat: &syn::Pat) -> Option<&Ident> {
match pat {
syn::Pat::Ident(pat_ident) => Some(&pat_ident.ident),
_ => None,
}
}
#[proc_macro_attribute]
/// ```
/// use kexplain::explain;
///
/// #[explain]
/// fn foo(a: u32, b: f64) -> u32 {
/// let _x = a * b as u32;
/// #[no_expr]
/// let x = a * b as u32;
/// #[skip]
/// let _y = a * b as u32;
/// x * 3
/// }
///
/// struct Foo;
///
/// impl Foo {
/// #[explain]
/// fn bar(&self, a: u32, b: f64) -> u32 {
/// let _x = a * b as u32;
/// #[no_expr]
/// let x = a * b as u32;
/// #[skip]
/// let _y = a * b as u32;
/// x * 3
/// }
/// }
///
/// fn main() {
/// assert_eq!(6, foo(1, 2.));
/// assert_eq!(6, foo_explain(1, 2., |name, expr, value| {
/// println!("{name} {expr:?} {value}");
/// }));
/// assert_eq!(6, Foo.bar(1, 2.));
/// assert_eq!(6, Foo.bar_explain(1, 2., |name, expr, value| {
/// println!("{name} {expr:?} {value}");
/// }));
/// }
/// ```
///
/// Example stdout:
/// ```text
/// STDOUT:
/// ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
/// a None 1
/// b None 2
/// _x Some("a * b as u32") 2
/// x None 2
/// None 6
/// a None 1
/// b None 2
/// _x Some("a * b as u32") 2
/// x None 2
/// None 6
/// ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
/// ```
///
/// See the `tests` for more examples.
pub fn explain(_attr: TokenStream, item: TokenStream) -> TokenStream {
let mut function = parse_macro_input!(item as ItemFn);
let mut new_function = function.clone();
// TODO wish I could use Span::def_site() but needs nightly
let callback = Ident::new("callback", Span::call_site());
let callback_arg: syn::FnArg = parse_quote! {
mut #callback: impl FnMut(&str, Option<&str>, &dyn std::fmt::Display)
};
new_function.sig.inputs.push(callback_arg);
// TODO wish I could use Span::def_site() but needs nightly
new_function.sig.ident = Ident::new(
&format!("{}_explain", function.sig.ident),
Span::call_site(),
);
let new_body = &mut new_function.block;
new_body.stmts.clear();
for arg in function.sig.inputs.iter() {
match arg {
syn::FnArg::Typed(pattype) if !has_skip_attr(&pattype.attrs) => {
let ident = or_continue!(find_ident(&pattype.pat));
let ident_str = ident.to_string();
let ident_str = ident_str.as_str();
new_body.stmts.push(parse_quote! {
#callback(#ident_str, None, &#ident);
});
}
syn::FnArg::Receiver(_receiver) => (),
syn::FnArg::Typed(_) => (),
}
}
for stmt in function.block.stmts.iter_mut() {
match stmt {
syn::Stmt::Local(local) => {
let should_skip = has_skip_attr(&local.attrs);
let skip_expression = has_no_expr_attr(&local.attrs);
local.attrs.clear();
new_body.stmts.push(syn::Stmt::Local(local.clone()));
if should_skip {
continue;
}
let expr = &or_continue!(local.init.as_ref()).1;
let ident = or_continue!(find_ident(&local.pat));
let ident_str = ident.to_string();
let ident_str = ident_str.as_str();
let expr_str = expr.to_token_stream().to_string();
let expr_str = expr_str.as_str();
let expr_expr: syn::Expr = if skip_expression {
parse_quote! { None }
} else {
parse_quote! { Some(#expr_str) }
};
new_body.stmts.push(parse_quote! {
#callback(#ident_str, #expr_expr, &#ident);
});
}
// syn::Stmt::Item(_item) => (),
// syn::Stmt::Expr(_expr) => (),
// syn::Stmt::Semi(_expr, _semi) => (),
_ => {
new_body.stmts.push(stmt.clone());
}
}
}
*new_body = parse_quote! {
{
let result = #new_body;
#callback("", None, &result);
result
}
};
(quote! {
#function
#new_function
})
.into()
}