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
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse_macro_input,
    spanned::Spanned,
    Attribute,
    AttrStyle,
    Data,
    DataStruct,
    DeriveInput,
    Field,
    Fields,
    FieldsNamed,
    Ident,
    LitStr,
    MetaList,
    Type
};

type Result<T> = std::result::Result<T, syn::Error>;

#[proc_macro_derive(Command, attributes(command, arg))]
pub fn command(input: TokenStream) -> TokenStream {
    let derive_input = parse_macro_input!(input as DeriveInput);
    match Command::parse(derive_input) {
        Ok(command) => command.into(),
        Err(err) => err.into_compile_error().into()
    }
}


struct CommandAttributes {
    executable: String
}


    impl CommandAttributes {

        fn parse(derive_input: &DeriveInput) -> Result<Self> {
            let mut executable = None;
            for attr in &derive_input.attrs {
                if attr.path().is_ident("command") {
                    match &attr.meta {
                        syn::Meta::List(MetaList {
                            path: _,
                            delimiter: _,
                            tokens: _
                        }) => {
                            attr.parse_nested_meta(|meta| {
                                if meta.path.is_ident("executable") {
                                    let value = meta.value()?;
                                    let s: LitStr = value.parse()?;
                                    executable = Some(s.value());
                                    Ok(())
                                } else{
                                    return Err(syn::Error::new(attr.span(), "Unsupported attribute"))
                                }

                            })?;

                        },
                        _ => {}
                    }
                }
            }
            if let Some(executable) = executable {
                Ok(Self {
                    executable 
                })
            } else {
                Err(syn::Error::new(derive_input.span(), "No 'executable' defined for 'command'"))
            }
        }
    }

struct Command {
    attributes: CommandAttributes,
    ident: Ident,
    args: Vec<Arg>
}

impl Command {

    fn parse(derive_input: DeriveInput) -> Result<Command> {
        let attributes = CommandAttributes::parse(&derive_input)?;

        let args = match derive_input.data {
            Data::Struct(DataStruct {
                struct_token: _,
                fields: Fields::Named(
                    FieldsNamed {
                        brace_token: _,
                        mut named
                    }
                ),
                semi_token: _
            }) => named.iter_mut().filter_map(collect_arg).collect(),
            _ => Err(syn::Error::new(derive_input.span(),
            "Only structs with named fields supported."))
        }?;
        Ok(Command {
            attributes,
            ident: derive_input.ident.clone(),
            args
        })
    }

}



enum ArgType {
    Option {
        name: String
    },
    Flag {
        name: String
    },
    Positional
}

#[allow(dead_code)]
struct Arg {
    arg_type: ArgType,
    ident: Ident,
    ty: Type
}

type ArgResult = Result<(Option<Attribute>, Option<ArgType>)>;

fn parse_arg_with_attributes(attr: Attribute) -> ArgResult {
    let mut arg_type = None;
    attr.parse_nested_meta(|meta| {
        if meta.path.is_ident("option") {
            if arg_type.is_none() {
                let value = meta.value()?;
                let s: LitStr = value.parse()?;
                arg_type = Some(ArgType::Option {
                    name: s.value()
                });
                Ok(())
            } else {
                Err(meta.error("Only one argument type allowed."))
            }
        } else if meta.path.is_ident("flag") {
            if arg_type.is_none() {
                let value = meta.value()?;
                let s: LitStr = value.parse()?;
                arg_type = Some(ArgType::Flag {
                    name: s.value()
                });
                Ok(())
            } else {
                Err(meta.error("Only one argument type allowed."))
            }
        } else {
            Err(meta.error("Unrecognized arg"))
        }
    }).map(|_| {
        arg_type.map_or((Some(attr), None), |arg_type| (None, Some(arg_type)))
    })
}

fn map_to_attr_or_arg(attr: Attribute) -> ArgResult {
    match attr.style {
        AttrStyle::Outer => match &attr.meta {
            syn::Meta::List(list) if list.path.is_ident("arg")
                => parse_arg_with_attributes(attr),
                syn::Meta::Path(path) if path.is_ident("arg") =>
                    Ok((None, Some(ArgType::Positional))),
                _  => Ok((Some(attr), None))
        },
        _  => Ok((Some(attr), None))
    }
}

fn collect_arg(field: &mut Field) -> Option<Result<Arg>> {
    if let Some(ident) = &field.ident {
        let arg_results: Result<Vec<_>> = field.attrs.clone()
            .into_iter().map(map_to_attr_or_arg).collect();
        match arg_results {
            Ok(results) => {
                let unzipped: (Vec<_>, Vec<_>) = results.into_iter().unzip();
                match unzipped {
                    (attrs, arg_types) => {
                        let attrs: Vec<_> = attrs.into_iter()
                            .filter_map(|attr| attr).collect();
                        let mut arg_types: Vec<_> = arg_types.into_iter()
                            .filter_map(|arg_type| arg_type).collect();
                        field.attrs = attrs;
                        match arg_types.len() {
                            1 => Some(Ok(Arg {
                                arg_type: arg_types.remove(0),
                                ident: ident.clone(),
                                ty: field.ty.clone()
                            })),
                            0 => None,
                            _ => Some(Err(syn::Error::new(field.span(), "Too many args")))
                        }
                    },
                }
            },
            Err(err) => Some(Err(err))
        }
    } else {
        None
    }
}

fn append_arg_tokens(arg: &Arg) -> proc_macro2::TokenStream {
    let ident = &arg.ident;
    match &arg.arg_type {
        ArgType::Option { name } => quote! {
            cmdstruct::Arg::append_option(&self.#ident, #name, &mut command);
        },
        ArgType::Flag { name } => quote! {  
            if self.#ident {
                command.arg(#name);
            }
        },
        ArgType::Positional => quote! {
            cmdstruct::Arg::append_arg(&self.#ident, &mut command);
        }
    }
}


impl Into<TokenStream> for Command {

    fn into(self) -> TokenStream {
        let args: Vec<_> = self.args.iter().map(append_arg_tokens).collect();
        let executable = &self.attributes.executable;
        let struct_ident = &self.ident;
        let impls_combined = quote! {

            impl #struct_ident {

                pub fn command(&self) -> std::process::Command {
                    let mut command = std::process::Command::new(#executable);
                    #(#args)*
                    command
                }
            }
        };
        impls_combined.into()
    }

}