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

use syn::*;

use ast_converters::*;
use tyhandlers::{TyHandler, get_ty_handler};
use returnhandlers::{ReturnHandler, get_return_handler};
use utils;

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

pub struct ComArg {
    pub name: Ident,
    pub ty: Ty,
    pub handler: Box<TyHandler>,
}

impl ComArg {

    pub fn new( name: Ident, ty: Ty ) -> ComArg {

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

pub struct ComMethodInfo {

    pub name: Ident,

    pub is_const: bool,
    pub rust_self_arg: FnArg,
    pub rust_return_ty: Ty,

    pub retval_type: Option<Ty>,
    pub return_type: Option<Ty>,

    pub returnhandler: Box<ReturnHandler>,
    pub args: Vec<ComArg>,
}

impl ComMethodInfo {

    /// Constructs new COM method info from a Rust method signature.
    pub fn new(
        n: &Ident,
        m : &FnDecl
    ) -> 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 ( is_const, rust_self_arg, com_args ) = m.inputs
            .split_first()
            .ok_or( ComMethodInfoError::TooFewArguments )
            .and_then( | ( self_arg, other_args ) | {

                // Resolve the self argument.
                let ( is_const, rust_self_arg ) = match *self_arg {
                    FnArg::SelfRef(.., m) => (
                        m == Mutability::Immutable,
                        self_arg.clone(),
                    ),
                    _ => return Err( ComMethodInfoError::BadSelfArg ),
                };

                // Process other arguments.
                let args = other_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( ComArg::new( ident, ty ) )
                } ).collect::<Result<_,_>>()?;

                Ok( ( is_const, rust_self_arg, args ) )
            } )?;

        // Get the output.
        let output = &m.output;
        let rust_return_ty = output.get_ty()
                .or( Err( ComMethodInfoError::BadReturnTy ) )?;

        // 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 )
                .or( Err( ComMethodInfoError::BadReturnTy ) )?;
        Ok( ComMethodInfo {
            name: n.clone(),
            is_const: is_const,
            rust_self_arg: rust_self_arg,
            rust_return_ty: rust_return_ty,
            retval_type: retval_type,
            return_type: return_type,
            returnhandler: returnhandler,
            args: com_args,
        } )
    }
}

fn try_parse_result( ty : &Ty ) -> Option<( Ty, Ty )>
{
    let path = match *ty {
        Ty::Path( _, ref p ) => p,
        _ => 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.ident.to_string().contains( "Result" ) {
        return None;
    }

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

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

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

fn hresult_ty() -> Ty {
    Ty::Path(
        None,
        Path {
            global: true,
            segments: vec![
                PathSegment::from( Ident::from( "intercom" ) ),
                PathSegment::from( Ident::from( "HRESULT" ) ),
            ]
        }
    )
}

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

    #[test]
    fn no_args_or_return_value() {

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

        assert_eq!( info.is_const, true );
        assert_eq!( info.name, "foo" );
        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 {}" );

        assert_eq!( info.is_const, true );
        assert_eq!( info.name, "foo" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!( info.retval_type.is_none(), true );
        assert_eq!(
                info.return_type,
                parse_type( "bool" ).ok() );
    }

    #[test]
    fn result_return_value() {

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

        assert_eq!( info.is_const, true );
        assert_eq!( info.name, "foo" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!(
                info.retval_type,
                parse_type( "String" ).ok() );
        assert_eq!(
                info.return_type,
                parse_type( "f32" ).ok() );
    }

    #[test]
    fn comresult_return_value() {

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

        assert_eq!( info.is_const, true );
        assert_eq!( info.name, "foo" );
        assert_eq!( info.args.len(), 0 );
        assert_eq!(
                info.retval_type,
                parse_type( "String" ).ok() );
        assert_eq!(
                info.return_type,
                parse_type( "::intercom::HRESULT" ).ok() );
    }

    #[test]
    fn basic_arguments() {

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

        assert_eq!( info.is_const, true );
        assert_eq!( info.name, "foo" );
        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::from( "a" ) );
        assert_eq!( info.args[0].ty, parse_type( "u32" ).unwrap() );

        assert_eq!( info.args[1].name, Ident::from( "b" ) );
        assert_eq!( info.args[1].ty, parse_type( "f32" ).unwrap() );
    }

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

        let item = parse_item( code ).unwrap();
        ComMethodInfo::new(
            &item.ident,
            match item.node {
                ItemKind::Fn( ref fn_decl, .. ) => fn_decl,
                _ => panic!( "Code isn't function" ),
            } ).unwrap()
    }
}