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
use super::*;

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

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct CppInterface {
    pub def: TypeDef,
}

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

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

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

    pub fn get_methods(&self, config: &Config) -> Vec<CppMethodOrName> {
        let namespace = self.def.namespace();

        self.def
            .methods()
            .map(|def| {
                let method = CppMethod::new(def, namespace);
                if method.dependencies.included(config) {
                    CppMethodOrName::Method(method)
                } else {
                    config
                        .warnings
                        .skip_method(method.def, &method.dependencies, config);
                    CppMethodOrName::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 methods = self.get_methods(config);

        let base_interfaces = self.base_interfaces();
        let has_unknown_base = matches!(base_interfaces.first(), Some(Type::IUnknown));
        let (class_cfg, cfg) = self.write_cfg(config);
        let vtbl_name = self.write_vtbl_name(config);

        let vtbl = {
            let core = config.write_core();

            let base = match base_interfaces.last() {
                Some(Type::IUnknown) => {
                    quote! { pub base__: #core IUnknown_Vtbl, }
                }
                Some(Type::Object) => {
                    quote! { pub base__: #core IInspectable_Vtbl, }
                }
                Some(Type::CppInterface(ty)) => {
                    let name = ty.write_vtbl_name(config);
                    quote! { pub base__: #name, }
                }
                _ => quote! {},
            };

            let mut names = MethodNames::new();

            let methods = methods.iter().map(|method| match method {
                CppMethodOrName::Method(method) => {
                    let method_cfg = class_cfg.difference(&method.dependencies, config);
                    let yes = method_cfg.write(config, false);

                    let name = names.add(method.def);
                    let abi = method.write_abi(config, false);

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

                        quote! {
                            #yes
                            pub #name: unsafe extern "system" fn #abi,
                            #no
                            #name: usize,
                        }
                    }
                }
                CppMethodOrName::Name(method) => {
                    let name = names.add(*method);
                    quote! { #name: usize, }
                }
            });

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

            quote! {
                #cfg
                #[repr(C)]
                #hide_vtbl
                pub struct #vtbl_name {
                    #base
                    #(#methods)*
                }
            }
        };

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

            if !config.package {
                if has_unknown_base {
                    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 name = to_ident(self.def.name());

            let mut result = if has_unknown_base {
                if let Some(guid) = self.def.guid_attribute() {
                    let guid = config.write_guid_u128(&guid);

                    quote! {
                        #cfg
                        windows_core::imp::define_interface!(#name, #vtbl_name, #guid);
                    }
                } else {
                    quote! {
                        #cfg
                        windows_core::imp::define_interface!(#name, #vtbl_name, 0);
                    }
                }
            } else {
                quote! {
                    #cfg
                    windows_core::imp::define_interface!(#name, #vtbl_name);
                }
            };

            if let Some(Type::CppInterface(base)) = base_interfaces.last() {
                let base = base.write_name(config);

                result.combine(quote! {
                    #cfg
                    impl core::ops::Deref for #name {
                        type Target = #base;
                        fn deref(&self) -> &Self::Target {
                            unsafe { core::mem::transmute(self) }
                        }
                    }
                });
            }

            if !base_interfaces.is_empty() {
                let bases = base_interfaces.iter().map(|ty| ty.write_name(config));
                result.combine(quote! {
                    #cfg
                    windows_core::imp::interface_hierarchy!(#name, #(#bases),*);
                })
            }

            let method_names = &mut MethodNames::new();
            let virtual_names = &mut MethodNames::new();
            let mut methods_tokens = quote! {};

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

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

            if !methods_tokens.is_empty() {
                result.combine(quote! {
                    #cfg
                    impl #name {
                        #methods_tokens
                    }
                });
            }

            result.combine(vtbl);

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

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

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

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

                base_interfaces.iter().for_each(|interface| {
                    if let Type::CppInterface(ty) = interface {
                        combine(ty, &mut dependencies, config);
                    }
                });

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

            let mut names = MethodNames::new();

            let field_methods: Vec<_> = methods
                .iter()
                .map(|method| match method {
                    CppMethodOrName::Method(method) => {
                        let name = names.add(method.def);
                        if has_unknown_base {
                            quote! { #name: #name::<Identity, OFFSET>, }
                        } else {
                            quote! { #name: #name::<Identity>, }
                        }
                    }
                    CppMethodOrName::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 {
                CppMethodOrName::Method(method) => {
                    let name = names.add(method.def);
                    let signature = method.write_abi(config, true);
                    let upcall = method.write_upcall(&impl_name, &name);

                    if has_unknown_base {
                    quote! {
                        unsafe extern "system" fn #name<Identity: #impl_name, const OFFSET: isize> #signature {
                            unsafe {
                                let this: &Identity = &*((this as *const *const ()).offset(OFFSET) as *const Identity);
                                #upcall
                            }
                        }
                    }
                } else {
                    quote! {
                        unsafe extern "system" fn #name<Identity: #impl_name> #signature {
                            unsafe {
                                let this = (this as *mut *mut core::ffi::c_void) as *const windows_core::ScopedHeap;
                                let this = &*((*this).this as *const Identity);
                                #upcall
                            }
                        }
                    }
                }
                }
                _ => quote! {},
            }).collect();

            let mut names = MethodNames::new();

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

            let impl_base = base_interfaces.last().map(|ty| ty.write_impl_name(config));

            let field_base = base_interfaces.last().map(|ty|{
                match ty {
                    Type::IUnknown => quote! { base__: windows_core::IUnknown_Vtbl::new::<Identity, OFFSET>(), },
                    Type::Object => quote! { base__: windows_core::IInspectable_Vtbl::new::<Identity, #name, OFFSET>(), },
                    Type::CppInterface(ty) => {
                        let ty = ty.write_vtbl_name(config);
                        if has_unknown_base {
                            quote! { base__: #ty::new::<Identity, OFFSET>(), }
                        } else {
                            quote! { base__: #ty::new::<Identity>(), }
                        }
                    }
                    rest => panic!("{rest:?}"),
                }
            });

            result.combine( if has_unknown_base {
                let matches = base_interfaces.iter().filter_map(|ty|{
                    match ty {
                        Type::CppInterface(ty) => {
                            let name = ty.write_name(config);
                            Some(quote! { || iid == &<#name as windows_core::Interface>::IID })
                        }
                        _ => None,
                    }
                });

                quote! {
                    #cfg
                    pub trait #impl_name: #impl_base {
                        #(#trait_methods)*
                    }
                    #cfg
                    impl #vtbl_name {
                        pub const fn new<Identity: #impl_name, const OFFSET: isize>() -> Self {
                            #(#impl_methods)*
                            Self {
                                #field_base
                                #(#field_methods)*
                            }
                        }
                        pub fn matches(iid: &windows_core::GUID) -> bool {
                            iid == &<#name as windows_core::Interface>::IID #(#matches)*
                        }
                    }
                    #cfg
                    impl windows_core::RuntimeName for #name {}
                }
            } else {
                let implvtbl_ident = impl_name.join("Vtbl");

                quote! {
                    #cfg
                    pub trait #impl_name : #impl_base {
                        #(#trait_methods)*
                    }
                    #cfg
                    impl #vtbl_name {
                        pub const fn new<Identity: #impl_name>() -> Self {
                            #(#impl_methods)*
                            Self{
                                #field_base
                                #(#field_methods)*
                            }
                        }
                    }
                    #cfg
                    struct #implvtbl_ident<T: #impl_name> (core::marker::PhantomData<T>);
                    #cfg
                    impl<T: #impl_name> #implvtbl_ident<T> {
                        const VTABLE: #vtbl_name = #vtbl_name::new::<T>();
                    }
                    #cfg
                    impl #name {
                        pub fn new<'a, T: #impl_name>(this: &'a T) -> windows_core::ScopedInterface<'a, Self> {
                            let this = windows_core::ScopedHeap { vtable: &#implvtbl_ident::<T>::VTABLE as *const _ as *const _, this: this as *const _ as *const _ };
                            let this = core::mem::ManuallyDrop::new(windows_core::imp::Box::new(this));
                            unsafe { windows_core::ScopedInterface::new(core::mem::transmute(&this.vtable)) }
                        }
                    }
                }
            });

            result
        }
    }

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

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

    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());
        quote! { #namespace #name }
    }

    pub fn base_interfaces(&self) -> Vec<Type> {
        let mut bases = vec![];
        let mut def = self.def;

        while let Some(base) = def.interface_impls().map(move |imp| imp.ty(&[])).next() {
            match base {
                Type::CppInterface(ref ty) => {
                    def = ty.def;
                    bases.insert(0, base);
                }
                Type::Object => {
                    bases.insert(0, Type::IUnknown);
                    bases.insert(1, Type::Object);
                    break;
                }
                Type::IUnknown => {
                    bases.insert(0, Type::IUnknown);
                    break;
                }
                rest => panic!("{rest:?}"),
            }
        }

        bases
    }
}

impl Dependencies for CppInterface {
    fn combine(&self, dependencies: &mut TypeMap) {
        let base_interfaces = self.base_interfaces();

        for interface in &base_interfaces {
            interface.combine(dependencies);
        }

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