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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

use prelude::*;
use std::rc::Rc;
use syn::{ ArgSelfRef, FnArg, FnDecl, MethodSig, PathArguments, ReturnType, Type };

use ast_converters::*;
use tyhandlers::{Direction, TypeContext, ModelTypeSystem, TypeHandler, get_ty_handler};
use returnhandlers::{ReturnHandler, get_return_handler};
use utils;

#[derive(Debug, PartialEq)]
pub enum ComMethodInfoError {
    TooFewArguments,
    BadSelfArg,
    BadArg(Box<FnArg>),
    BadReturnType,
}

#[derive(Clone)]
pub struct RustArg {

    /// Name of the Rust argument.
    pub name: Ident,

    /// Rust type of the COM argument.
    pub ty: Type,

    /// Type handler.
    pub handler: Rc<dyn TypeHandler>,
}

impl PartialEq for RustArg {

    fn eq(&self, other: &RustArg) -> bool
    {
        self.name == other.name
            && self.ty == other.ty
    }
}

impl ::std::fmt::Debug for RustArg {
    fn fmt( &self, f: &mut ::std::fmt::Formatter ) -> ::std::fmt::Result {
        write!( f, "{}: {:?}", self.name, self.ty )
    }
}

impl RustArg {

    pub fn new( name: Ident, ty: Type, type_system: ModelTypeSystem ) -> RustArg {

        let tyhandler = get_ty_handler(
                &ty, TypeContext::new( type_system ) );
        RustArg {
            name,
            ty,
            handler: tyhandler,
        }
    }
}

pub struct ComArg {

    /// Name of the argument.
    pub name: Ident,

    /// Rust type of the raw COM argument.
    pub ty: Type,

    /// Type handler.
    pub handler: Rc<dyn TypeHandler>,

    /// Argument direction. COM uses OUT params while Rust uses return values.
    pub dir : Direction
}

impl ComArg {

    pub fn new(
        name: Ident,
        ty: Type,
        dir: Direction,
        type_system: ModelTypeSystem
    ) -> ComArg {

        let tyhandler = get_ty_handler(
                &ty, TypeContext::new( type_system ) );
        ComArg {
            name,
            ty,
            dir,
            handler: tyhandler,
        }
    }

    pub fn from_rustarg(
        rustarg: RustArg,
        dir: Direction,
        type_system: ModelTypeSystem,
    ) -> ComArg {

        let tyhandler = get_ty_handler(
                &rustarg.ty, TypeContext::new( type_system ) );
        ComArg {
            name: rustarg.name,
            ty: rustarg.ty,
            dir,
            handler: tyhandler,
        }
    }
}

impl PartialEq for ComArg {

    fn eq(&self, other: &ComArg) -> bool
    {
        self.name == other.name
            && self.ty == other.ty
            && self.dir == other.dir
    }
}

impl ::std::fmt::Debug for ComArg {
    fn fmt( &self, f: &mut ::std::fmt::Formatter ) -> ::std::fmt::Result {
        write!( f, "{}: {:?} {:?}", self.name, self.dir, self.ty )
    }
}


#[derive(Debug, Clone)]
pub struct ComMethodInfo {

    /// The display name used in public places that do not require an unique name.
    pub display_name: Ident,

    /// Unique name that differentiates between different type systems.
    pub unique_name: Ident,

    /// True if the self parameter is not mutable.
    pub is_const: bool,

    /// Rust self argument.
    pub rust_self_arg: ArgSelfRef,

    /// Rust return type.
    pub rust_return_ty: Type,

    /// COM retval out parameter type, such as the value of Result<...>.
    pub retval_type: Option<Type>,

    /// COM return type, such as the error value of Result<...>.
    pub return_type: Option<Type>,

    /// Return value handler.
    pub returnhandler: Rc<dyn ReturnHandler>,

    /// Method arguments.
    pub args: Vec<RustArg>,

    /// True if the Rust method is unsafe.
    pub is_unsafe: bool,

    /// Type system.
    pub type_system : ModelTypeSystem,
}

impl PartialEq for ComMethodInfo {

    fn eq(&self, other: &ComMethodInfo) -> bool
    {
        self.display_name == other.display_name
            && self.unique_name == other.unique_name
            && self.is_const == other.is_const
            && self.rust_self_arg == other.rust_self_arg
            && self.rust_return_ty == other.rust_return_ty
            && self.retval_type == other.retval_type
            && self.return_type == other.return_type
            && self.args == other.args
    }
}

impl ComMethodInfo {

    /// Constructs new COM method info from a Rust method signature.
    pub fn new(
        m : &MethodSig,
        type_system : ModelTypeSystem,
    ) -> Result<ComMethodInfo, ComMethodInfoError>
    {
        Self::new_from_parts( m.ident.clone(), &m.decl, m.unsafety.is_some(), type_system )
    }

    pub fn new_from_parts(
        n: Ident,
        decl: &FnDecl,
        unsafety: bool,
        type_system : ModelTypeSystem,
    ) -> Result<ComMethodInfo, ComMethodInfoError>
    {
        // Process all the function arguments.
        // In Rust this includes the 'self' argument and the actual function
        // arguments. For COM the self is implicit so we'll handle it
        // separately.
        let mut iter = decl.inputs.iter();
        let rust_self_arg = iter.next()
                .ok_or_else( || ComMethodInfoError::TooFewArguments )?;

        let ( is_const, rust_self_arg ) = match *rust_self_arg {
            FnArg::SelfRef( ref self_arg ) => (
                self_arg.mutability.is_none(),
                self_arg.clone()
            ),
            _ => return Err( ComMethodInfoError::BadSelfArg ),
        } ;

        // Process other arguments.
        let args = iter.map( | arg | {
            let ty = arg.get_ty()
                .or_else( |_| Err(
                    ComMethodInfoError::BadArg( Box::new( arg.clone() ) )
                ) )?;
            let ident = arg.get_ident()
                .or_else( |_| Err(
                    ComMethodInfoError::BadArg( Box::new( arg.clone() ) )
                ) )?;

            Ok( RustArg::new( ident, ty, type_system ) )
        } ).collect::<Result<_,_>>()?;

        // Get the output.
        let rust_return_ty = match decl.output {
            ReturnType::Default => parse_quote!( () ),
            ReturnType::Type( _, ref ty ) => (**ty).clone(),
        };

        // Resolve the return type and retval type.
        let ( retval_type, return_type ) = if utils::is_unit( &rust_return_ty ) {
            ( None, None )
        } else if let Some( ( retval, ret ) ) = try_parse_result( &rust_return_ty ) {
            ( Some( retval ), Some( ret ) )
        } else {
            ( None, Some( rust_return_ty.clone() ) )
        };

        let returnhandler = get_return_handler(
                    &retval_type, &return_type, type_system )
                .or( Err( ComMethodInfoError::BadReturnType ) )?;
        Ok( ComMethodInfo {
            unique_name: Ident::new( &format!( "{}_{:?}", n, type_system ), Span::call_site() ),
            display_name: n,
            returnhandler: returnhandler.into(),
            is_const,
            rust_self_arg,
            rust_return_ty,
            retval_type,
            return_type,
            args,
            is_unsafe: unsafety,
            type_system
        } )
    }

    pub fn raw_com_args( &self ) -> Vec<ComArg>
    {
        let in_args = self.args
                .iter()
                .map( |ca| {
                    ComArg::from_rustarg( ca.clone(), Direction::In, self.type_system )
                } );
        let out_args = self.returnhandler.com_out_args();

        in_args.chain( out_args ).collect()
    }
}

fn try_parse_result( ty : &Type ) -> Option<( Type, Type )>
{
    let path = match *ty {
        Type::Path( ref p ) => &p.path,
        _ => return None,
    };

    // Ensure the type name contains 'Result'. We don't really have
    // good ways to ensure it is an actual Result type but at least we can
    // use this to discount things like Option<>, etc.
    let last_segment = path.segments.last()?;
    if ! last_segment.value().ident.to_string().contains( "Result" ) {
        return None;
    }

    // Ensure the Result has angle bracket arguments.
    if let PathArguments::AngleBracketed( ref data )
            = last_segment.value().arguments {

        // The returned types depend on how many arguments the Result has.
        return Some( match data.args.len() {
            1 => ( data.args[ 0 ].get_ty().ok()?, hresult_ty() ),
            2 => ( data.args[ 0 ].get_ty().ok()?, data.args[ 1 ].get_ty().ok()? ),
            _ => return None,
        } )
    }

    // We couldn't find a valid type. Return nothing.
    None
}

fn hresult_ty() -> Type {
    parse_quote!( ::intercom::raw::HRESULT )
}

#[cfg(test)]
mod tests {

    use syn::{ Item };

    use super::*;
    use tyhandlers::ModelTypeSystem::*;

    #[test]
    fn no_args_or_return_value() {

        let info = test_info( "fn foo( &self ) {}", Automation );

        assert_eq!( info.is_const, true );
        assert_eq!( info.display_name, "foo" );
        assert_eq!( info.unique_name, "foo_Automation" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!( info.retval_type.is_none(), true );
        assert_eq!( info.return_type.is_none(), true );
    }

    #[test]
    fn basic_return_value() {

        let info = test_info( "fn foo( &self ) -> bool {}", Raw );

        assert_eq!( info.is_const, true );
        assert_eq!( info.display_name, "foo" );
        assert_eq!( info.unique_name, "foo_Raw" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!( info.retval_type.is_none(), true );
        assert_eq!(
                info.return_type,
                Some( parse_quote!( bool ) ) );
    }

    #[test]
    fn result_return_value() {

        let info = test_info( "fn foo( &self ) -> Result<String, f32> {}", Automation );

        assert_eq!( info.is_const, true );
        assert_eq!( info.display_name, "foo" );
        assert_eq!( info.unique_name, "foo_Automation" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!(
                info.retval_type,
                Some( parse_quote!( String ) ) );
        assert_eq!(
                info.return_type,
                Some( parse_quote!( f32 ) ) );
    }

    #[test]
    fn comresult_return_value() {

        let info = test_info( "fn foo( &self ) -> ComResult<String> {}", Automation );

        assert_eq!( info.is_const, true );
        assert_eq!( info.display_name, "foo" );
        assert_eq!( info.unique_name, "foo_Automation" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!(
                info.retval_type,
                Some( parse_quote!( String ) ) );
        assert_eq!(
                info.return_type,
                Some( parse_quote!( ::intercom::raw::HRESULT ) ) );
    }

    #[test]
    fn basic_arguments() {

        let info = test_info( "fn foo( &self, a : u32, b : f32 ) {}", Raw );

        assert_eq!( info.is_const, true );
        assert_eq!( info.display_name, "foo" );
        assert_eq!( info.unique_name, "foo_Raw" );
        assert_eq!( info.retval_type.is_none(), true );
        assert_eq!( info.return_type.is_none(), true );

        assert_eq!( info.args.len(), 2 );

        assert_eq!( info.args[0].name, Ident::new( "a", Span::call_site() ) );
        assert_eq!( info.args[0].ty, parse_quote!( u32 ) );

        assert_eq!( info.args[1].name, Ident::new( "b", Span::call_site() ) );
        assert_eq!( info.args[1].ty, parse_quote!( f32 ) );
    }

    fn test_info( code : &str, ts : ModelTypeSystem) -> ComMethodInfo {

        let item = syn::parse_str( code ).unwrap();
        let ( ident, decl, unsafety ) = match item {
            Item::Fn( ref f ) => ( f.ident.clone(), f.decl.as_ref(), f.unsafety.is_some() ),
            _ => panic!( "Code isn't function" ),
        };
        ComMethodInfo::new_from_parts(
                ident, decl, unsafety, ts ).unwrap()
    }
}