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

use ::prelude::*;
use super::*;
use super::macros::*;

use ::guid::GUID;
use ::ast_converters::*;
use ::methodinfo::ComMethodInfo;
use ::syn::{ Ident, Visibility, LitStr };
use ::ordermap::OrderMap;
use ::std::iter::FromIterator;
use ::tyhandlers::{ModelTypeSystem};

intercom_attribute!(
    ComInterfaceAttr< ComInterfaceAttrParam, NoParams > {
        com_iid : LitStr,
        raw_iid : LitStr,
        base : Ident,
    }
);

impl ComInterfaceAttr {

    pub fn iid( &self, ts : ModelTypeSystem ) -> Result< Option< &LitStr >, String > {

        match ts {
            ModelTypeSystem::Raw => self.raw_iid(),
            ModelTypeSystem::Automation => self.com_iid(),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct ComInterface
{
    display_name : Ident,
    visibility : Visibility,
    base_interface : Option<Ident>,
    variants : OrderMap<ModelTypeSystem, ComInterfaceVariant>,
    item_type: ::utils::InterfaceType,
    is_unsafe : bool,
}

#[derive(Debug, PartialEq)]
pub struct ComInterfaceVariant
{
    display_name : Ident,
    unique_name : Ident,
    unique_base_interface : Option<Ident>,
    type_system : ModelTypeSystem,
    iid : GUID,
    methods : Vec<ComMethodInfo>,
}

impl ComInterface
{
    /// Parses a #[com_interface] attribute and the associated item.
    pub fn parse(
        crate_name : &str,
        attr_params : TokenStream,
        item : &str,
    ) -> ParseResult<ComInterface>
    {
        // Parse the input code.
        let item : ::syn::Item = ::syn::parse_str( item )
            .map_err( |_| ParseError::ComInterface(
                    "<Unknown>".into(),
                    "Item syntax error".into() ) )?;

        Self::from_ast( crate_name, attr_params, &item )
    }

    /// Creates ComInterface from AST elements.
    pub fn from_ast(
        crate_name : &str,
        attr : TokenStream,
        item : &::syn::Item,
    ) -> ParseResult< ComInterface >
    {
        let attr : ComInterfaceAttr = ::syn::parse2( attr )
            .map_err( |_| ParseError::ComInterface(
                    item.get_ident().unwrap().to_string(),
                    "Attribute syntax error".into() ) )?;

        // Get the interface details. As [com_interface] can be applied to both
        // impls and traits this handles both of those.
        let ( itf_ident, fns, itf_type, unsafety ) =
                ::utils::get_ident_and_fns( item )
                    .ok_or_else( || ParseError::ComInterface(
                            item.get_ident().unwrap().to_string(),
                            "Unsupported associated item".into() ) )?;

        // The second argument is the optional base class. If there's no base
        // class defined, use IUnknown as the default. The value of NO_BASE will
        // construct an interface that has no base class.
        //
        // In practice the NO_BASE should be used ONLY for the IUnknown itself.
        let base = attr.base()
                .map_err( |msg| ParseError::ComInterface(
                    item.get_ident().unwrap().to_string(), msg ) )?;
        let base = match base {
            Some( b ) => if b == "NO_BASE" { None } else { Some( b.to_owned() ) },
            None => Some( Ident::new( "IUnknown", Span::call_site() ) ),
        };

        // Visibility for trait interfaces is the visibility of the trait.
        //
        // For implicit interfaces (impl Struct) the visibility is always public.
        // These interfaces should only exist for COM types that are meant to be
        // called from external sources as they can't be impl'd for random ComItf.
        //
        // Note this may conflict with visibility of the actual [com_class], but
        // nothing we can do for this really.
        let visibility = if let ::syn::Item::Trait( ref t ) = *item {
                    t.vis.clone()
                } else {
                    parse_quote!( pub )
                };

        let variants = OrderMap::from_iter(
            [ ModelTypeSystem::Automation, ModelTypeSystem::Raw ].iter().map( |&ts| {

            let itf_unique_ident = Ident::new(
                    &format!( "{}_{:?}", itf_ident.to_string(), ts ), Span::call_site() );

                // IUnknown interfaces do not have type system variants.
                let unique_base = match base {
                    Some( ref iunk ) if iunk == "IUnknown" => base.clone(),
                    ref b => b.as_ref().map( |b| Ident::new( &format!( "{}_{:?}", b, ts ), Span::call_site() ) )
                };

                let iid_attr = attr.iid( ts )
                        .map_err( |msg| ParseError::ComInterface(
                            item.get_ident().unwrap().to_string(), msg ) )?;
                let iid = match iid_attr {
                    Some( iid ) => GUID::parse( &iid.value() )
                        .map_err( |_| ParseError::ComInterface(
                                item.get_ident().unwrap().to_string(),
                                "Bad IID format".into() ) )?,
                    None => ::utils::generate_iid(
                            crate_name, &itf_unique_ident.to_string(), ts )
                };

                // Read the method details.
                //
                // TODO: Currently we ignore invalid methods. We should probably do
                //       something smarter.
                let methods = fns.iter()
                        .map( | sig |
                            ComMethodInfo::new( sig, ts ) )
                        .filter_map( Result::ok )
                        .collect::<Vec<_>>();

                Ok( ( ts, ComInterfaceVariant {
                    display_name: itf_ident.clone(),
                    unique_name : itf_unique_ident,
                    unique_base_interface : unique_base,
                    type_system : ts,
                    iid,
                    methods,
                } ) )
            } ).collect::<Result<Vec<_>,_>>()? );

        Ok( ComInterface {
            display_name: itf_ident,
            base_interface: base,
            item_type: itf_type,
            is_unsafe : unsafety.is_some(),
            visibility,
            variants,
        } )
    }

    /// Temp accessor for the automation variant.
    pub fn aut( &self ) -> &ComInterfaceVariant {
        &self.variants[ &ModelTypeSystem::Automation ]
    }

    /// Interface name.
    pub fn name( &self ) -> &Ident { &self.display_name }

    /// Interface visibility.
    pub fn visibility( &self ) -> &Visibility { &self.visibility }

    /// The base interface.
    pub fn base_interface( &self ) -> &Option<Ident> { &self.base_interface }

    /// Interface variants.
    pub fn variants( &self ) -> &OrderMap<ModelTypeSystem, ComInterfaceVariant> { &self.variants }

    /// The type of the associated item for the #[com_interface] attribute.
    ///
    /// Either an impl or a trait.
    pub fn item_type( &self ) -> ::utils::InterfaceType { self.item_type }

    /// True, if the interface requires unsafe impl.
    pub fn is_unsafe( &self ) -> bool { self.is_unsafe }
}

impl ComInterfaceVariant {

    /// Interface unique name.
    pub fn unique_name( &self ) -> &Ident { &self.unique_name }

    /// Interface base interface variant unique name.
    pub fn unique_base_interface( &self ) -> &Option<Ident> { &self.unique_base_interface }

    /// Implemented methods.
    pub fn methods( &self ) -> &Vec<ComMethodInfo> { &self.methods }

    /// Interface IID.
    pub fn iid( &self ) -> &GUID { &self.iid }

    /// Gets the type system this interface variant represents.
    pub fn type_system( &self ) -> ModelTypeSystem { self.type_system }
}

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

    #[test]
    fn parse_com_interface() {
        let itf = ComInterface::parse(
            "not used",
            quote!(
                com_iid = "12345678-1234-1234-1234-567890ABCDEF",
                raw_iid = "12345678-1234-1234-1234-567890FEDCBA",
            ),
            "trait ITrait { fn foo( &self ); fn bar( &self ); }" )
                .expect( "com_interface attribute parsing failed" );

        assert_eq!( itf.name(), "ITrait" );
        assert_eq!( itf.visibility(), &Visibility::Inherited );
        assert_eq!( itf.base_interface().as_ref().unwrap(), "IUnknown" );

        let variant = &itf.variants[ &Automation ];
        assert_eq!( variant.iid(),
            &GUID::parse( "12345678-1234-1234-1234-567890ABCDEF" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].display_name, "foo" );
        assert_eq!( variant.methods[1].display_name, "bar" );

        let variant = &itf.variants[ &Raw ];
        assert_eq!( variant.iid(),
            &GUID::parse( "12345678-1234-1234-1234-567890FEDCBA" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].display_name, "foo" );
        assert_eq!( variant.methods[1].display_name, "bar" );
    }

    #[test]
    fn parse_com_interface_with_auto_guid() {
        let itf = ComInterface::parse(
            "not used",
            quote!(),
            "pub trait IAutoGuid { fn one( &self ); fn two( &self ); }" )
                .expect( "com_interface attribute parsing failed" );

        assert_eq!( itf.name(), "IAutoGuid" );

        let pub_visibility : Visibility = parse_quote!( pub );
        assert_eq!( itf.visibility(), &pub_visibility );
        assert_eq!( itf.base_interface().as_ref().unwrap(), "IUnknown" );

        let variant = &itf.variants[ &Automation ];
        assert_eq!( variant.iid(),
            &GUID::parse( "3DC87B73-0998-30B6-75EA-D4F564454D4B" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].display_name, "one" );
        assert_eq!( variant.methods[1].display_name, "two" );

        let variant = &itf.variants[ &Raw ];
        assert_eq!( variant.iid(),
            &GUID::parse( "D552E455-9FB2-34A2-61C0-34BDE0A9095D" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].display_name, "one" );
        assert_eq!( variant.methods[1].display_name, "two" );
    }


    #[test]
    fn parse_com_interface_with_base_interface() {
        let itf = ComInterface::parse(
            "not used",
            quote!( base = IBase ),
            "pub trait IAutoGuid { fn one( &self ); fn two( &self ); }" )
                .expect( "com_interface attribute parsing failed" );

        assert_eq!( itf.name(), "IAutoGuid" );

        let pub_visibility : Visibility = parse_quote!( pub );
        assert_eq!( itf.visibility(), &pub_visibility );
        assert_eq!( itf.base_interface().as_ref().unwrap(), "IBase" );

        let variant = &itf.variants[ &ModelTypeSystem::Automation];
        assert_eq!( variant.iid(),
            &GUID::parse( "3DC87B73-0998-30B6-75EA-D4F564454D4B" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].display_name, "one" );
        assert_eq!( variant.methods[0].unique_name, "one_Automation" );
        assert_eq!( variant.methods[1].display_name, "two" );
        assert_eq!( variant.methods[1].unique_name, "two_Automation" );

        let variant = &itf.variants[ &ModelTypeSystem::Raw];
        assert_eq!( variant.iid(),
            &GUID::parse( "D552E455-9FB2-34A2-61C0-34BDE0A9095D" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].display_name, "one" );
        assert_eq!( variant.methods[0].unique_name, "one_Raw" );
        assert_eq!( variant.methods[1].display_name, "two" );
        assert_eq!( variant.methods[1].unique_name, "two_Raw" );
    }

    #[test]
    fn parse_com_interface_with_no_base_interface() {
        let itf = ComInterface::parse(
            "not used",
            quote!( base = NO_BASE ),
            "pub trait IAutoGuid { fn one( &self ); fn two( &self ); }" )
                .expect( "com_interface attribute parsing failed" );

        assert_eq!( itf.name(), "IAutoGuid" );

        let pub_visibility : Visibility = parse_quote!( pub );
        assert_eq!( itf.visibility(), &pub_visibility );
        assert_eq!( itf.base_interface(), &None );

        let variant = &itf.variants[ &Automation ];
        assert_eq!( variant.iid(),
            &GUID::parse( "3DC87B73-0998-30B6-75EA-D4F564454D4B" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].unique_name, "one_Automation" );
        assert_eq!( variant.methods[1].unique_name, "two_Automation" );

        let variant = &itf.variants[ &Raw ];
        assert_eq!( variant.iid(),
            &GUID::parse( "D552E455-9FB2-34A2-61C0-34BDE0A9095D" ).unwrap() );
        assert_eq!( variant.methods.len(), 2 );
        assert_eq!( variant.methods[0].unique_name, "one_Raw" );
        assert_eq!( variant.methods[1].unique_name, "two_Raw" );
    }
}