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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use crate::methodinfo::ComArg;
use crate::prelude::*;
use crate::tyhandlers::{self, Direction, ModelTypeSystem, TypeContext};
use crate::utils;
use proc_macro2::Span;
use syn::Type;

/// Defines return handler for handling various different return type schemes.
pub trait ReturnHandler: ::std::fmt::Debug
{
    /// Returns the current type system. Used internally by the trait.
    fn type_system(&self) -> ModelTypeSystem;

    /// The return type of the original Rust method.
    fn rust_ty(&self) -> Type;

    /// The return type span.
    fn return_type_span(&self) -> Span;

    /// Infallible status.
    fn is_infallible(&self) -> bool;

    /// The return type for COM implementation.
    fn com_ty(&self) -> Type
    {
        tyhandlers::get_ty_handler(&self.rust_ty(), TypeContext::new(self.type_system()))
            .com_ty(self.return_type_span())
    }

    /// Gets the return statement for converting the COM result into Rust
    /// return.
    fn com_to_rust_return(&self, _result: &Ident) -> TokenStream
    {
        quote!()
    }

    /// Gets the return statement for converting the Rust result into COM
    /// outputs.
    fn rust_to_com_return(&self, _result: &Ident) -> TokenStream
    {
        quote!()
    }

    /// Gets the COM out arguments that result from the Rust return type.
    fn com_out_args(&self) -> Vec<ComArg>
    {
        vec![]
    }
}

/// Void return type.
#[derive(Debug)]
struct VoidHandler(Span);
impl ReturnHandler for VoidHandler
{
    fn rust_ty(&self) -> Type
    {
        utils::unit_ty(self.0)
    }

    fn com_ty(&self) -> Type
    {
        syn::parse2(quote_spanned!(self.0 => ())).unwrap()
    }

    // Void types do not depend on the type system.
    fn type_system(&self) -> ModelTypeSystem
    {
        ModelTypeSystem::Automation
    }

    /// The return type span.
    fn return_type_span(&self) -> Span
    {
        self.0
    }

    fn is_infallible(&self) -> bool
    {
        true
    }
}

/// Simple return type with the return value as the immediate value.
#[derive(Debug)]
struct ReturnOnlyHandler(Type, ModelTypeSystem, Span);
impl ReturnHandler for ReturnOnlyHandler
{
    fn type_system(&self) -> ModelTypeSystem
    {
        self.1
    }

    fn rust_ty(&self) -> Type
    {
        self.0.clone()
    }

    fn return_type_span(&self) -> Span
    {
        self.2
    }

    fn com_to_rust_return(&self, result: &Ident) -> TokenStream
    {
        tyhandlers::get_ty_handler(&self.rust_ty(), TypeContext::new(self.1)).com_to_rust(
            result,
            self.2,
            Direction::Retval,
            true,
        )
    }

    fn rust_to_com_return(&self, result: &Ident) -> TokenStream
    {
        tyhandlers::get_ty_handler(&self.rust_ty(), TypeContext::new(self.1)).rust_to_com(
            result,
            self.2,
            Direction::Retval,
            true,
        )
    }

    fn com_out_args(&self) -> Vec<ComArg>
    {
        vec![]
    }

    fn is_infallible(&self) -> bool
    {
        true
    }
}

/// Result type that supports error info for the `Err` value. Converted to
/// `[retval]` on success or `HRESULT` + `IErrorInfo` on error.
#[derive(Debug)]
struct ErrorResultHandler
{
    retval_ty: Type,
    return_ty: Type,
    span: Span,
    type_system: ModelTypeSystem,
}

impl ReturnHandler for ErrorResultHandler
{
    fn type_system(&self) -> ModelTypeSystem
    {
        self.type_system
    }
    fn rust_ty(&self) -> Type
    {
        self.return_ty.clone()
    }
    fn return_type_span(&self) -> Span
    {
        self.span
    }
    fn com_ty(&self) -> Type
    {
        let ts = self.type_system.as_typesystem_type(self.span);
        syn::parse2(quote_spanned!(self.span=>
            < intercom::raw::HRESULT as
                intercom::type_system::ExternType< #ts >>
                    ::ForeignType ))
        .unwrap()
    }

    fn com_to_rust_return(&self, result: &Ident) -> TokenStream
    {
        // Format the final Ok value.
        // If there is only one, it should be a raw value;
        // If there are multiple value turn them into a tuple.
        let (temp_values, ok_values) =
            get_rust_ok_values(self.com_out_args(), self.is_infallible());
        let ok_values = if ok_values.len() != 1 {
            quote!( ( #( #ok_values ),* ) )
        } else {
            quote!( #( #ok_values )* )
        };

        // Return statement checks for S_OK (should be is_success) HRESULT and
        // yields either Ok or Err Result based on that.
        quote!(
            // TODO: HRESULT::succeeded
            if #result == intercom::raw::S_OK || #result == intercom::raw::S_FALSE {
                #( #temp_values; )*
                Ok( #ok_values )
            } else {
                return Err( intercom::load_error(
                        self,
                        &__intercom_iid,
                        #result ) );
            }
        )
    }

    fn rust_to_com_return(&self, result: &Ident) -> TokenStream
    {
        // Get the OK idents. We'll use v0, v1, v2, ... depending on the amount
        // of patterns we need for possible tuples.
        let ok_idents = self
            .com_out_args()
            .iter()
            .enumerate()
            .map(|(idx, _)| Ident::new(&format!("v{}", idx + 1), Span::call_site()))
            .collect::<Vec<_>>();

        // Generate the pattern for the Ok(..).
        // Tuples get (v0, v1, v2, ..) pattern while everything else is
        // represented with just Ok( v0 ) as there's just one parameter.
        let ok_pattern = {
            // quote! takes ownership of tokens if we allow so let's give them
            // by reference here.
            let rok_idents = &ok_idents;
            match self.retval_ty {
                Type::Tuple(_) => quote!( ( #( #rok_idents ),* ) ),

                // Non-tuples should have only one ident. Concatenate the vector.
                _ => quote!( #( #rok_idents )* ),
            }
        };

        let (temp_writes, ok_writes, err_writes) = write_out_values(
            &ok_idents,
            self.com_out_args(),
            self.is_infallible(),
            self.span,
            self.type_system,
        );
        quote!(
            match #result.and_then(|#ok_pattern| {
                // These may fail, resulting in early exit from the lambda.
                #( #temp_writes; )*

                // Once we get here, everything should succeed.
                #( #ok_writes; )*
                Ok( intercom::raw::S_OK )
            }) {
                Ok( s ) => s,
                Err( e ) => {
                    #( #err_writes );*;
                    intercom::store_error( e ).hresult
                },
            }
        )
    }

    fn com_out_args(&self) -> Vec<ComArg>
    {
        get_out_args_for_result(&self.retval_ty, self.span, self.type_system)
    }

    fn is_infallible(&self) -> bool
    {
        false
    }
}

fn get_out_args_for_result(
    retval_ty: &Type,
    span: Span,
    type_system: ModelTypeSystem,
) -> Vec<ComArg>
{
    match *retval_ty {
        // Tuples map to multiple out args, no [retval].
        Type::Tuple(ref t) => t
            .elems
            .iter()
            .enumerate()
            .map(|(idx, ty)| {
                ComArg::new(
                    Ident::new(&format!("__out{}", idx + 1), span),
                    ty.clone(),
                    span,
                    Direction::Out,
                    type_system,
                )
            })
            .collect::<Vec<_>>(),
        _ => vec![ComArg::new(
            Ident::new("__out", span),
            retval_ty.clone(),
            span,
            Direction::Retval,
            type_system,
        )],
    }
}

fn write_out_values(
    idents: &[Ident],
    out_args: Vec<ComArg>,
    infallible: bool,
    span: Span,
    ts: ModelTypeSystem,
) -> (Vec<TokenStream>, Vec<TokenStream>, Vec<TokenStream>)
{
    let ts = ts.as_typesystem_type(span);
    let mut temp_tokens = vec![];
    let mut ok_tokens = vec![];
    let mut err_tokens = vec![];
    for (ident, out_arg) in idents.iter().zip(out_args) {
        let arg_name = out_arg.name;
        let temp_name = Ident::new(&format!("__{}_guard", arg_name), span);
        let ty = out_arg.ty;
        let ok_value = out_arg
            .handler
            .rust_to_com(ident, span, Direction::Out, infallible);
        let err_value = out_arg.handler.default_value();

        temp_tokens.push(quote!( let #temp_name = intercom::type_system::OutputGuard::<#ts, #ty>::wrap( #ok_value ) ));
        ok_tokens.push(quote!( *#arg_name = #temp_name.consume() ));
        err_tokens.push(quote!( *#arg_name = #err_value ));
    }

    (temp_tokens, ok_tokens, err_tokens)
}

/// Gets the result as Rust types for a success return value.
fn get_rust_ok_values(
    out_args: Vec<ComArg>,
    infallible: bool,
) -> (Vec<TokenStream>, Vec<TokenStream>)
{
    let mut temp_tokens = vec![];
    let mut ok_tokens = vec![];
    for out_arg in out_args {
        let value =
            out_arg
                .handler
                .com_to_rust(&out_arg.name, out_arg.span, Direction::Retval, infallible);
        let temp_name = Ident::new(&format!("__{}_guard", out_arg.name), out_arg.span);
        let unwrap = match infallible {
            true => quote!(),
            false => quote!(?),
        };

        temp_tokens.push(quote!(let #temp_name = #value));
        ok_tokens.push(quote!(#temp_name#unwrap));
    }
    (temp_tokens, ok_tokens)
}

/// Resolves the correct return handler to use.
pub fn get_return_handler(
    retval_ty: &Option<Type>,
    return_ty: &Option<Type>,
    span: Span,
    type_system: ModelTypeSystem,
) -> Result<Box<dyn ReturnHandler>, &'static str>
{
    Ok(match (retval_ty, return_ty) {
        (&None, &None) => Box::new(VoidHandler(span)),
        (&None, &Some(ref ty)) => Box::new(ReturnOnlyHandler(ty.clone(), type_system, span)),
        (&Some(ref rv), &Some(ref rt)) => Box::new(ErrorResultHandler {
            retval_ty: rv.clone(),
            return_ty: rt.clone(),
            span,
            type_system,
        }),

        // Unsupported return scheme. Note we are using Result::Err instead of
        // Option::None here because having no return handler is unsupported
        // error case.
        _ => return Err("Unsupported return type configuration"),
    })
}