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::{format_ident, quote};
use syn::{
    parenthesized,
    parse::{Parse, ParseStream},
    parse_macro_input, Ident, Result, Token, TypePath, Visibility,
};

struct CallbackTypes {
    pub interface: TypePath,
    pub arg_1: TypePath,
    pub arg_2: Option<TypePath>,
}

impl Parse for CallbackTypes {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        parenthesized!(content in input);
        let args = content.parse_terminated(TypePath::parse, Token![,])?;
        input.parse::<Token![;]>()?;
        let mut args = args.into_iter();
        if let (Some(interface), Some(arg_1), arg_2) = (args.next(), args.next(), args.next()) {
            Ok(CallbackTypes {
                interface,
                arg_1,
                arg_2,
            })
        } else {
            Err(content.error("expected (interface, arg_1, arg_2)"))
        }
    }
}

struct CallbackStruct {
    pub vis: Visibility,
    _struct_token: Token![struct],
    pub ident: Ident,
    pub args: CallbackTypes,
}

impl Parse for CallbackStruct {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(CallbackStruct {
            vis: input.parse()?,
            _struct_token: input.parse()?,
            ident: input.parse()?,
            args: input.parse()?,
        })
    }
}

/// Implement a `CompletedCallback` using the types specified as tuple struct fields.
#[proc_macro_attribute]
pub fn completed_callback(_attr: TokenStream, input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as CallbackStruct);
    impl_completed_callback(&ast)
}

fn impl_completed_callback(ast: &CallbackStruct) -> TokenStream {
    let vis = &ast.vis;

    let name = &ast.ident;
    let closure = get_closure(name);
    let interface = &ast.args.interface;
    let interface = interface
        .path
        .segments
        .last()
        .expect("completed_callback should always specify an interface");
    let interface_impl = format_ident!("{}_Impl", interface.ident);

    let arg_1 = &ast.args.arg_1;
    let arg_2 = &ast.args.arg_2;

    let msg = format!("Implementation of [`{}`].", interface.ident);

    let gen = match arg_2 {
        Some(arg_2) => quote! {
            type #closure = CompletedClosure<#arg_1, #arg_2>;

            #[doc = #msg]
            #[implement(#interface)]
            #vis struct #name(::std::cell::UnsafeCell<Option<#closure>>);

            impl #name {
                pub fn create(
                    closure: #closure,
                ) -> #interface {
                    Self(Some(closure).into()).into()
                }

                pub fn wait_for_async_operation(
                    closure: Box<
                        dyn FnOnce(#interface) -> crate::Result<()>,
                    >,
                    completed: #closure,
                ) -> crate::Result<()> {
                    let (tx, rx) = ::std::sync::mpsc::channel();
                    let completed: #closure =
                        Box::new(move |arg_1, arg_2| -> ::windows::core::Result<()> {
                            let result = completed(arg_1, arg_2).map_err(crate::Error::WindowsError);
                            tx.send(result).expect("send over mpsc channel");
                            Ok(())
                        });
                    let callback = Self::create(completed);

                    closure(callback)?;
                    crate::wait_with_pump(rx)?
                }
            }

            #[allow(non_snake_case)]
            impl #interface_impl for #name {
                fn Invoke<'a>(
                    &self,
                    arg_1: <#arg_1 as InvokeArg<'a>>::Input,
                    arg_2: <#arg_2 as InvokeArg<'a>>::Input,
                ) -> ::windows::core::Result<()> {
                    match unsafe { (*self.0.get()).take() } {
                        Some(completed) => completed(
                            <#arg_1 as InvokeArg<'a>>::convert(arg_1),
                            <#arg_2 as InvokeArg<'a>>::convert(arg_2),
                        ),
                        None => Ok(()),
                    }
                }
            }
        },
        None => quote! {
            type #closure = Box<dyn FnOnce(<#arg_1 as ClosureArg>::Output) -> ::windows::core::Result<()>>;

            #[doc = #msg]
            #[implement(#interface)]
            #vis struct #name(::std::cell::UnsafeCell<Option<#closure>>);

            impl #name {
                pub fn create(
                    closure: #closure,
                ) -> #interface {
                    Self(Some(closure).into()).into()
                }

                pub fn wait_for_async_operation(
                    closure: Box<
                        dyn FnOnce(#interface) -> crate::Result<()>,
                    >,
                    completed: #closure,
                ) -> crate::Result<()> {
                    let (tx, rx) = ::std::sync::mpsc::channel();
                    let completed: #closure =
                        Box::new(move |arg_1| -> ::windows::core::Result<()> {
                            let result = completed(arg_1).map_err(crate::Error::WindowsError);
                            tx.send(result).expect("send over mpsc channel");
                            Ok(())
                        });
                    let callback = Self::create(completed);

                    closure(callback)?;
                    crate::wait_with_pump(rx)?
                }
            }

            #[allow(non_snake_case)]
            impl #interface_impl for #name {
                fn Invoke<'a>(
                    &self,
                    arg_1: <#arg_1 as InvokeArg<'a>>::Input,
                ) -> ::windows::core::Result<()> {
                    match unsafe { (*self.0.get()).take() } {
                        Some(completed) => completed(
                            <#arg_1 as InvokeArg<'a>>::convert(arg_1),
                        ),
                        None => Ok(()),
                    }
                }
            }
        },
    };

    gen.into()
}

/// Implement an `EventCallback` using the types specified as tuple struct fields.
#[proc_macro_attribute]
pub fn event_callback(_attr: TokenStream, input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as CallbackStruct);
    impl_event_callback(&ast)
}

fn impl_event_callback(ast: &CallbackStruct) -> TokenStream {
    let vis = &ast.vis;

    let name = &ast.ident;
    let closure = get_closure(name);

    let interface = &ast.args.interface;
    let interface = interface
        .path
        .segments
        .last()
        .expect("event_callback should always specify an interface");
    let interface_impl = format_ident!("{}_Impl", interface.ident);

    let arg_1 = &ast.args.arg_1;
    let arg_2 = &ast
        .args
        .arg_2
        .as_ref()
        .expect("event_callback should always have 2 arguments");

    let msg = format!("Implementation of [`{}`].", interface.ident);

    let gen = quote! {
        type #closure = EventClosure<#arg_1, #arg_2>;

        #[doc = #msg]
        #[implement(#interface)]
        #vis struct #name(::std::cell::UnsafeCell<#closure>);

        impl #name {
            pub fn create(
                closure: #closure,
            ) -> #interface {
                Self(closure.into()).into()
            }
        }

        #[allow(non_snake_case)]
        impl #interface_impl for  #name {
            fn Invoke<'a>(
                &self,
                arg_1: <#arg_1 as InvokeArg<'a>>::Input,
                arg_2: <#arg_2 as InvokeArg<'a>>::Input,
            ) -> ::windows::core::Result<()> {
                unsafe { (*self.0.get())(
                    <#arg_1 as InvokeArg<'a>>::convert(arg_1),
                    <#arg_2 as InvokeArg<'a>>::convert(arg_2),
                ) }
            }
        }
    };

    gen.into()
}

fn get_closure(name: &Ident) -> Ident {
    format_ident!("{}Closure", name)
}