windows-bindgen 0.66.0

Code generator for Windows metadata
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use super::*;

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum InterfaceKind {
    None,
    Default,
    Static,
    Composable,
    Base,
}

#[derive(Clone, Debug)]
pub enum MethodOrName {
    Method(Method),
    Name(MethodDef),
}

#[derive(Clone, Debug)]
pub struct Interface {
    pub def: TypeDef,
    pub generics: Vec<Type>,
    pub kind: InterfaceKind,
}

impl PartialEq for Interface {
    fn eq(&self, other: &Self) -> bool {
        self.def == other.def
    }
}

impl Eq for Interface {}

impl std::hash::Hash for Interface {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.def.hash(state);
    }
}

impl Ord for Interface {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.def.name(), self.def).cmp(&(other.def.name(), other.def))
    }
}

impl PartialOrd for Interface {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Interface {
    pub fn type_name(&self) -> TypeName {
        self.def.type_name()
    }

    pub fn get_methods(&self, config: &Config) -> Vec<MethodOrName> {
        self.def
            .methods()
            .map(|def| {
                let method = Method::new(def, &self.generics);
                if method.dependencies.included(config) {
                    MethodOrName::Method(method)
                } else {
                    config
                        .warnings
                        .skip_method(method.def, &method.dependencies, config);
                    MethodOrName::Name(method.def)
                }
            })
            .collect()
    }

    fn write_cfg(&self, config: &Config) -> (Cfg, TokenStream) {
        if !config.package {
            return (Cfg::default(), quote! {});
        }

        let cfg = Cfg::new(&self.dependencies(), config);
        let tokens = cfg.write(config, false);
        (cfg, tokens)
    }

    pub fn write(&self, config: &Config) -> TokenStream {
        let type_name = self.def.type_name();
        let methods = self.get_methods(config);

        let required_interfaces = self.required_interfaces();
        let name = self.write_name(config);

        let vtbl_name = self.write_vtbl_name(config);
        let is_exclusive = self.is_exclusive();
        let constraints = config.write_generic_constraints(&self.generics);
        let phantoms = config.write_generic_phantoms(&self.generics);
        let named_phantoms = config.write_generic_named_phantoms(&self.generics);
        let (class_cfg, cfg) = self.write_cfg(config);

        let vtbl = {
            let virtual_names = &mut MethodNames::new();
            let result = config.write_result();

            let vtbl_methods = methods.iter().map(|method| match method {
                MethodOrName::Method(method) => {
                    let name = virtual_names.add(method.def);
                    let vtbl = method.write_abi(config, false);

                    let method_cfg = class_cfg.difference(&method.dependencies, config);
                    let yes = method_cfg.write(config, false);

                    if yes.is_empty() {
                        quote! {
                            pub #name: unsafe extern "system" fn(#vtbl) -> #result HRESULT,
                        }
                    } else {
                        let no = method_cfg.write(config, true);

                        quote! {
                            #yes
                            pub #name: unsafe extern "system" fn(#vtbl) -> #result HRESULT,
                            #no
                            #name: usize,
                        }
                    }
                }
                MethodOrName::Name(method) => {
                    let name = virtual_names.add(*method);
                    quote! { #name: usize, }
                }
            });

            let hide_vtbl = if config.sys {
                quote! {}
            } else {
                quote! { #[doc(hidden)] }
            };

            let core = config.write_core();

            quote! {
                #cfg
                #[repr(C)]
                #hide_vtbl
                pub struct #vtbl_name where #constraints {
                    pub base__: #core IInspectable_Vtbl,
                    #(#vtbl_methods)*
                    #named_phantoms
                }
            }
        };

        if config.sys {
            let mut result = quote! {};

            if !config.package {
                if let Some(guid) = self.def.guid_attribute() {
                    let name: TokenStream = format!("IID_{}", self.def.name()).into();
                    result.combine(config.write_cpp_const_guid(name, &guid));
                }

                result.combine(vtbl);
            }

            result
        } else {
            let mut result = if self.generics.is_empty() {
                let guid = config.write_guid_u128(&self.def.guid_attribute().unwrap());

                quote! {
                    #cfg
                    windows_core::imp::define_interface!(#name, #vtbl_name, #guid);
                    #cfg
                    impl windows_core::RuntimeType for #name {
                        const SIGNATURE: windows_core::imp::ConstBuffer = windows_core::imp::ConstBuffer::for_interface::<Self>();
                    }
                }
            } else {
                let guid = self.def.guid_attribute().unwrap();
                let pinterface = Literal::byte_string(&format!("pinterface({{{guid}}}"));

                let generics = self.generics.iter().map(|generic| {
                    let name = generic.write_name(config);

                    quote! {
                        .push_slice(b";").push_other(#name::SIGNATURE)
                    }
                });

                quote! {
                    #[repr(transparent)]
                    #[derive(Clone, Debug, Eq, PartialEq)]
                    pub struct #name(windows_core::IUnknown, #phantoms) where #constraints;
                    impl<#constraints> windows_core::imp::CanInto<windows_core::IUnknown> for #name {}
                    impl<#constraints> windows_core::imp::CanInto<windows_core::IInspectable> for #name {}
                    unsafe impl<#constraints> windows_core::Interface for #name {
                        type Vtable = #vtbl_name;
                        const IID: windows_core::GUID = windows_core::GUID::from_signature(<Self as windows_core::RuntimeType>::SIGNATURE);
                    }
                    impl<#constraints> windows_core::RuntimeType for #name {
                        const SIGNATURE: windows_core::imp::ConstBuffer = windows_core::imp::ConstBuffer::new().push_slice(#pinterface)#(#generics)*.push_slice(b")");
                    }
                }
            };

            if !is_exclusive && self.generics.is_empty() {
                result.combine(quote! {
                #cfg
                windows_core::imp::interface_hierarchy!(#name, windows_core::IUnknown, windows_core::IInspectable);
            });
            }

            if !is_exclusive && !required_interfaces.is_empty() {
                if self.generics.is_empty() {
                    let interfaces = required_interfaces.iter().map(|ty| ty.write_name(config));

                    result.combine(quote! {
                        #cfg
                        windows_core::imp::required_hierarchy!(#name, #(#interfaces),*);
                    });
                } else {
                    let interfaces = required_interfaces.iter().map(|ty| {
                    let ty = ty.write_name(config);
                    quote!{
                        impl<#constraints> windows_core::imp::CanInto<#ty> for #name { const QUERY: bool = true; }
                    }
                });

                    result.combine(quote! {
                        #(#interfaces)*
                    });
                }
            }

            if !is_exclusive {
                let method_names = &mut MethodNames::new();
                let virtual_names = &mut MethodNames::new();
                let mut method_tokens = TokenStream::new();

                for method in methods.iter().filter_map(|method| match &method {
                    MethodOrName::Method(method) => Some(method),
                    _ => None,
                }) {
                    let cfg = method.write_cfg(config, &class_cfg, false);

                    let method = method.write(
                        config,
                        Some(self),
                        InterfaceKind::Default,
                        method_names,
                        virtual_names,
                    );

                    method_tokens.combine(quote! {
                        #cfg
                        #method
                    });
                }

                for interface in &required_interfaces {
                    let virtual_names = &mut MethodNames::new();

                    for method in
                        interface
                            .get_methods(config)
                            .iter()
                            .filter_map(|method| match &method {
                                MethodOrName::Method(method) => Some(method),
                                _ => None,
                            })
                    {
                        let cfg = method.write_cfg(config, &class_cfg, false);

                        let method = method.write(
                            config,
                            Some(interface),
                            interface.kind,
                            method_names,
                            virtual_names,
                        );

                        method_tokens.combine(quote! {
                            #cfg
                            #method
                        });
                    }
                }

                if !method_tokens.is_empty() {
                    result.combine(quote! {
                        #cfg
                        impl<#constraints> #name {
                            #method_tokens
                        }
                    });
                }

                if self.def.is_agile() {
                    result.combine(quote! {
                        #cfg
                        unsafe impl<#constraints> Send for #name {}
                        #cfg
                        unsafe impl<#constraints> Sync for #name {}
                    });
                }

                if let Some(into_iterator) = required_interfaces
                    .iter()
                    .find(|interface| interface.type_name() == TypeName::IIterable)
                    .map(|interface| {
                        let ty = interface.generics[0].write_name(config);
                        let namespace = config.write_namespace(TypeName::IIterator);

                        quote! {
                            #cfg
                            impl<#constraints> IntoIterator for #name {
                                type Item = #ty;
                                type IntoIter = #namespace IIterator<Self::Item>;

                                fn into_iter(self) -> Self::IntoIter {
                                    IntoIterator::into_iter(&self)
                                }
                            }
                            #cfg
                            impl<#constraints> IntoIterator for &#name {
                                type Item = #ty;
                                type IntoIter = #namespace IIterator<Self::Item>;

                                fn into_iter(self) -> Self::IntoIter {
                                    self.First().unwrap()
                                }
                            }

                        }
                    })
                {
                    result.combine(into_iterator);
                }
            }

            if config.implement || !is_exclusive {
                let impl_name: TokenStream = format!("{}_Impl", self.def.name()).into();

                let generics: Vec<_> = self
                    .generics
                    .iter()
                    .map(|ty| ty.write_name(config))
                    .collect();

                let runtime_name = format!("{type_name}");

                let cfg = if config.package {
                    fn combine(interface: &Interface, dependencies: &mut TypeMap, config: &Config) {
                        for method in interface.get_methods(config).iter() {
                            if let MethodOrName::Method(method) = method {
                                dependencies.combine(&method.dependencies);
                            }
                        }
                    }

                    let mut dependencies = self.dependencies();
                    combine(self, &mut dependencies, config);

                    required_interfaces
                        .iter()
                        .for_each(|interface| combine(interface, &mut dependencies, config));

                    Cfg::new(&dependencies, config).write(config, false)
                } else {
                    quote! {}
                };

                result.combine(quote! {
                    #cfg
                    impl<#constraints> windows_core::RuntimeName for #name {
                        const NAME: &'static str = #runtime_name;
                    }
                });

                let mut names = MethodNames::new();

                let field_methods: Vec<_> = methods
                    .iter()
                    .map(|method| match method {
                        MethodOrName::Method(method) => {
                            let name = names.add(method.def);
                            quote! { #name: #name::<#(#generics,)* Identity, OFFSET>, }
                        }
                        MethodOrName::Name(method) => {
                            let name = names.add(*method);
                            quote! { #name: 0, }
                        }
                    })
                    .collect();

                let mut names = MethodNames::new();

                let impl_methods: Vec<_> = methods.iter().map(|method| match method {
                MethodOrName::Method(method) => {
                    let name = names.add(method.def);
                    let signature = method.write_abi(config, true);
                    let call = quote! { #impl_name::#name };
                    let upcall = method.write_upcall(call, true);

                    quote! {
                        unsafe extern "system" fn #name<#constraints Identity: #impl_name <#(#generics,)*>, const OFFSET: isize> (#signature) -> windows_core::HRESULT {
                            unsafe {
                                let this: &Identity = &*((this as *const *const ()).offset(OFFSET) as *const Identity);
                                #upcall
                            }
                        }
                    }
                }
                _ => quote! {},
            }).collect();

                let mut names = MethodNames::new();

                let trait_methods: Vec<_> = methods
                    .iter()
                    .map(|method| match method {
                        MethodOrName::Method(method) => {
                            let name = names.add(method.def);
                            let signature = method.write_impl_signature(config, true, true);
                            quote! { fn #name #signature; }
                        }
                        _ => quote! {},
                    })
                    .collect();

                let requires = if required_interfaces.is_empty() {
                    quote! { windows_core::IUnknownImpl }
                } else {
                    let interfaces = required_interfaces
                        .iter()
                        .map(|ty| ty.write_impl_name(config));

                    quote! {  #(#interfaces)+* }
                };

                result.combine(quote! {
                #cfg
                pub trait #impl_name <#(#generics),*> : #requires where #constraints {
                    #(#trait_methods)*
                }
                #cfg
                impl<#constraints> #vtbl_name {
                    pub const fn new<Identity: #impl_name <#(#generics,)*>, const OFFSET: isize>() -> Self {
                        #(#impl_methods)*
                        Self {
                            base__: windows_core::IInspectable_Vtbl::new::<Identity, #name, OFFSET>(),
                            #(#field_methods)*
                            #named_phantoms
                        }
                    }
                    pub fn matches(iid: &windows_core::GUID) -> bool {
                        iid == &<#name as windows_core::Interface>::IID
                    }
                }
            });
            }

            result.combine(vtbl);
            result.combine(self.write_extensions());
            result
        }
    }

    fn write_extensions(&self) -> TokenStream {
        match self.type_name() {
            TypeName::IIterator => {
                quote! {
                    impl<T: windows_core::RuntimeType> Iterator for IIterator<T> {
                        type Item = T;

                        fn next(&mut self) -> Option<Self::Item> {
                            let result = if self.HasCurrent().unwrap_or(false) {
                                self.Current().ok()
                            } else {
                                None
                            };

                            if result.is_some() {
                                self.MoveNext().ok()?;
                            }

                            result
                        }
                    }
                }
            }
            TypeName::IIterable => {
                quote! {
                    impl<T: windows_core::RuntimeType> IntoIterator for IIterable<T> {
                        type Item = T;
                        type IntoIter = IIterator<Self::Item>;

                        fn into_iter(self) -> Self::IntoIter {
                            IntoIterator::into_iter(&self)
                        }
                    }
                    impl<T: windows_core::RuntimeType> IntoIterator for &IIterable<T> {
                        type Item = T;
                        type IntoIter = IIterator<Self::Item>;

                        fn into_iter(self) -> Self::IntoIter {
                            self.First().unwrap()
                        }
                    }

                }
            }
            _ => quote! {},
        }
    }

    pub fn write_name(&self, config: &Config) -> TokenStream {
        self.type_name().write(config, &self.generics)
    }

    fn write_vtbl_name(&self, config: &Config) -> TokenStream {
        let name: TokenStream = format!("{}_Vtbl", self.def.name()).into();

        if self.generics.is_empty() {
            name
        } else {
            let generics = self.generics.iter().map(|ty| ty.write_name(config));
            quote! { #name < #(#generics,)* > }
        }
    }

    pub fn write_impl_name(&self, config: &Config) -> TokenStream {
        let name: TokenStream = format!("{}_Impl", self.def.name()).into();
        let namespace = config.write_namespace(self.def.type_name());

        if self.generics.is_empty() {
            quote! { #namespace #name }
        } else {
            let generics = self.generics.iter().map(|ty| ty.write_name(config));
            quote! { #namespace #name < #(#generics),* > }
        }
    }

    pub fn is_exclusive(&self) -> bool {
        self.def.has_attribute("ExclusiveToAttribute")
    }

    pub fn runtime_signature(&self) -> String {
        interface_signature(self.def, &self.generics)
    }

    pub fn required_interfaces(&self) -> Vec<Self> {
        fn walk(interface: &Interface, set: &mut Vec<Interface>) {
            for ty in interface
                .def
                .interface_impls()
                .map(|imp| imp.ty(&interface.generics))
            {
                let Type::Interface(interface) = ty else {
                    panic!();
                };

                if !set.iter().any(|existing| existing.def == interface.def) {
                    walk(&interface, set);
                    set.push(interface);
                }
            }
        }
        let mut set = vec![];
        walk(self, &mut set);

        set.sort();
        set.dedup();
        set
    }
}

impl Dependencies for Interface {
    fn combine(&self, dependencies: &mut TypeMap) {
        Type::Object.combine(dependencies);

        for interface in self.required_interfaces() {
            Type::Interface(interface).combine(dependencies);
        }

        // Different specializations of Interface may have different generics...
        for ty in &self.generics {
            ty.combine(dependencies);
        }

        let is_iterable = self.type_name() == TypeName::IIterable;

        for method in self.def.methods() {
            for ty in method
                .signature(self.def.namespace(), &self.generics)
                .types()
            {
                if is_iterable || ty.is_core() {
                    ty.combine(dependencies);
                }
            }
        }
    }
}