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
//! Python-like decorator for Rust
//!
//! Example
//! --------
//!
//! ```
//! use pydeco::deco;
//!
//! fn logging<F>(func: F) -> impl Fn(i32) -> i32
//! where
//!     F: Fn(i32) -> i32,
//! {
//!     move |i| {
//!         println!("Input = {}", i);
//!         let out = func(i);
//!         println!("Output = {}", out);
//!         out
//!     }
//! }
//!
//! #[deco(logging)]
//! fn add2(i: i32) -> i32 {
//!     i + 2
//! }
//!
//! add2(2);
//! ```
//!
//! - Decorator with parameter
//!
//! ```
//! use pydeco::deco;
//! use std::{fs, io::Write};
//!
//! fn logging<InputFunc: 'static>(
//!     log_filename: &'static str,
//! ) -> impl Fn(InputFunc) -> Box<dyn Fn(i32) -> i32>
//! where
//!     InputFunc: Fn(i32) -> i32,
//! {
//!     move |func: InputFunc| {
//!         Box::new(move |i: i32| {
//!             let mut f = fs::File::create(log_filename).unwrap();
//!             writeln!(f, "Input = {}", i).unwrap();
//!             let out = func(i);
//!             writeln!(f, "Output = {}", out).unwrap();
//!             out
//!         })
//!     }
//! }
//!
//! #[deco(logging("test.log"))]
//! fn add2(i: i32) -> i32 {
//!     i + 2
//! }
//!
//! add2(2);
//! ```
//!

use anyhow::{bail, Result};
use proc_macro::TokenStream;
use proc_macro2::TokenTree;
use syn::*;

#[proc_macro_attribute]
pub fn deco(attr: TokenStream, func: TokenStream) -> TokenStream {
    let func = func.into();
    let item_fn: ItemFn = syn::parse(func).expect("Input is not a function");
    let vis = &item_fn.vis;
    let ident = &item_fn.sig.ident;
    let block = &item_fn.block;

    let inputs = item_fn.sig.inputs;
    let output = item_fn.sig.output;

    let input_values: Vec<_> = inputs
        .iter()
        .map(|arg| match arg {
            &FnArg::Typed(ref val) => &val.pat,
            _ => unimplemented!("#[deco] cannot be used with associated function"),
        })
        .collect();

    let attr = DecoratorAttr::parse(attr.into()).expect("Failed to parse attribute");
    let caller = match attr {
        DecoratorAttr::Fixed { name } => {
            quote::quote! {
                #vis fn #ident(#inputs) #output {
                    let f = #name(deco_internal);
                    return f(#(#input_values,) *);

                    fn deco_internal(#inputs) #output #block
                }
            }
        }
        DecoratorAttr::Parametric { name, args } => {
            quote::quote! {
                #vis fn #ident(#inputs) #output {
                    let deco = #name(#(#args,) *);
                    let f = deco(deco_internal);
                    return f(#(#input_values,) *);

                    fn deco_internal(#inputs) #output #block
                }
            }
        }
    };
    caller.into()
}

#[derive(Debug, PartialEq)]
enum DecoratorAttr {
    Fixed { name: Ident },
    Parametric { name: Ident, args: Vec<Expr> },
}

impl DecoratorAttr {
    fn parse(attr: proc_macro2::TokenStream) -> Result<Self> {
        let mut ident = None;
        let mut args = Vec::new();
        for at in attr {
            match at {
                TokenTree::Ident(id) => {
                    ident = Some(id);
                }
                TokenTree::Group(grp) => {
                    if ident.is_none() {
                        bail!("Invalid token stream");
                    }
                    for t in grp.stream() {
                        if let Ok(expr) = syn::parse2(t.into()) {
                            args.push(expr);
                        }
                    }
                }
                _ => bail!("Invalid token stream"),
            }
        }
        if let Some(name) = ident {
            if args.is_empty() {
                Ok(DecoratorAttr::Fixed { name })
            } else {
                Ok(DecoratorAttr::Parametric { name, args })
            }
        } else {
            bail!("Decorator name not found");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn parse_attr() -> Result<()> {
        let ts = proc_macro2::TokenStream::from_str("logging").unwrap();
        assert!(matches!(DecoratorAttr::parse(ts)?, DecoratorAttr::Fixed {..}));
        Ok(())
    }

    #[test]
    fn parse_attr_parametric_literal() -> Result<()> {
        let ts = proc_macro2::TokenStream::from_str(r#"logging("test.log", 2)"#).unwrap();
        match DecoratorAttr::parse(ts)? {
            DecoratorAttr::Fixed { .. } => bail!("Failed to parse args"),
            DecoratorAttr::Parametric { args, .. } => {
                assert_eq!(args.len(), 2);
            }
        }
        Ok(())
    }

    #[test]
    fn parse_attr_parametric_variable() -> Result<()> {
        let ts =
            proc_macro2::TokenStream::from_str(r#"logging("test.log", some_variable)"#).unwrap();
        match DecoratorAttr::parse(ts)? {
            DecoratorAttr::Fixed { .. } => bail!("Failed to parse args"),
            DecoratorAttr::Parametric { args, .. } => {
                assert_eq!(args.len(), 2);
            }
        }
        Ok(())
    }

    #[test]
    fn parse_attr_parametric_expr() -> Result<()> {
        let ts = proc_macro2::TokenStream::from_str(r#"logging("test.log", (1 + 2))"#).unwrap();
        match DecoratorAttr::parse(ts)? {
            DecoratorAttr::Fixed { .. } => bail!("Failed to parse args"),
            DecoratorAttr::Parametric { args, .. } => {
                assert_eq!(args.len(), 2);
            }
        }
        Ok(())
    }

    #[test]
    fn parse_attr_empty() -> Result<()> {
        let ts = proc_macro2::TokenStream::from_str("").unwrap();
        assert!(DecoratorAttr::parse(ts).is_err());
        Ok(())
    }

    #[test]
    fn parse_attr_invalid() -> Result<()> {
        // inverse order
        let ts = proc_macro2::TokenStream::from_str(r#"("test.log", 2)logging"#).unwrap();
        assert!(DecoratorAttr::parse(ts).is_err());
        Ok(())
    }
}