windows-bindgen 0.101.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
use super::*;

#[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<MethodOrName<CppMethod>> {
        if self.def.methods().any(|method| {
            method
                .find_attribute("NativeOverrideSlotAttribute")
                .is_some()
        }) {
            Self::vtable_methods(self.def, config.reader);
        }

        self.def
            .methods()
            // Redeclarations retain metadata contracts but use the inherited callable and slot.
            .filter(|method| {
                method
                    .find_attribute("NativeOverrideSlotAttribute")
                    .is_none()
            })
            .map(|def| {
                let method = CppMethod::new(def, config.reader);
                if !config.plan.includes_method(def, &[]) {
                    MethodOrName::Name(method.def)
                } else {
                    MethodOrName::Method(method)
                }
            })
            .collect()
    }

    fn vtable_methods(def: TypeDef, reader: &Reader) -> Vec<MethodDef> {
        assert!(
            def.interface_impls().count() <= 1,
            "native slot overrides require a single base on `{}`",
            def.name()
        );
        let mut methods = if let Some(base) = def.interface_impls().next() {
            let windows_metadata::Type::ClassName(base) = base.interface(&[]) else {
                panic!("invalid native interface base on `{}`", def.name());
            };
            Self::vtable_methods(def.index().expect(&base.namespace, &base.name), reader)
        } else {
            Vec::new()
        };
        let inherited = methods.len();
        let mut overrides = BTreeSet::new();
        for method in def.methods() {
            if let Some(attribute) = method.find_attribute("NativeOverrideSlotAttribute") {
                assert_eq!(
                    method
                        .attributes()
                        .filter(|attr| attr.name() == "NativeOverrideSlotAttribute")
                        .count(),
                    1,
                    "duplicate native override slot on `{}`",
                    method.name()
                );
                let values = attribute.value();
                let [(_, Value::U32(slot))] = values.as_slice() else {
                    panic!("invalid native override slot on `{}`", method.name());
                };
                let slot = *slot as usize;
                assert!(
                    slot < inherited
                        && overrides.insert(slot)
                        && !method.flags().contains(MethodAttributes::NewSlot),
                    "invalid inherited slot on `{}.{}`",
                    def.name(),
                    method.name()
                );
                let base = methods[slot];
                let signature = method.method_signature(&[], reader);
                let base_signature = base.method_signature(&[], reader);
                assert!(
                    method.name() == base.name()
                        && signature.call_flags == base_signature.call_flags
                        && signature.params.len() == base_signature.params.len()
                        && same_override_type(
                            &signature.return_type,
                            &base_signature.return_type,
                            reader,
                        )
                        && signature
                            .params
                            .iter()
                            .zip(&base_signature.params)
                            .all(|(a, b)| { same_override_type(&a.ty, &b.ty, reader) }),
                    "incompatible inherited slot on `{}.{}`",
                    def.name(),
                    method.name()
                );
                methods[slot] = method;
            } else {
                methods.push(method);
            }
        }
        methods
    }

    // `_Impl` emission is omitted when this interface or a base has skipped methods.
    pub fn has_skipped_methods(&self, config: &Config) -> bool {
        self.def
            .methods()
            .any(|def| !config.plan.includes_method(def, &[]))
    }

    fn write_cfg(&self, config: &Config) -> (Cfg, TokenStream) {
        write_full_cfg(self, config)
    }

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

        let base_interfaces = self.base_interfaces(config.reader);
        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 methods = write_vtbl_methods(&methods, &class_cfg, config, |method| {
                method.write_abi(config, false)
            });

            let hide_vtbl = config.doc_hidden_in_package();

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

        if config.bindgen.style.is_sys() {
            let mut result = quote! {};

            if !config.bindgen.layout.is_package() {
                if has_unknown_base && let Some(guid) = self.def.guid_attribute() {
                    let name: TokenStream = format!("IID_{}", self.def.name()).parse().unwrap();
                    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);

                    if base_interfaces.contains(&Type::Object) {
                        quote! {
                            #cfg
                            windows_core::imp::define_interface!(#name, #vtbl_name, #guid, inspectable);
                        }
                    } else {
                        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),*);
                });
            }

            // Implementation-only interfaces need ABI slots and `_Impl`, not caller wrappers.
            let suppress_methods = config.bindgen.style.is_minimal()
                && config.should_implement(self.def.type_name(), false)
                && config.plan.selection.is_shell(self.type_name());

            let mut methods_tokens = quote! {};

            if !suppress_methods {
                let method_names = &mut MethodNames::new();

                // These methods live in `impl #name`, so references to this
                // interface are emitted as `Self` (clippy::use_self).
                let self_config = config.with_self_ty(self.type_name(), &[]);

                for (method, vname) in named_methods(&methods) {
                    let cfg = method.write_cfg(config, &class_cfg, false);
                    let method = method.write(&self_config, method_names, &vname);

                    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() || (config.reader.legacy() && legacy::is_agile(self.def)) {
                result.combine(quote! {
                    #cfg
                    unsafe impl Send for #name {}
                    #cfg
                    unsafe impl Sync for #name {}
                });
            }

            if config.should_implement(self.def.type_name(), true) {
                let impl_name: TokenStream = format!("{}_Impl", self.def.name()).parse().unwrap();

                let cfg = if config.bindgen.layout.is_package() {
                    let mut dependencies = self.dependencies(config.reader);
                    let bases = base_interfaces.iter().filter_map(|ty| match ty {
                        Type::CppInterface(ty) => Some(ty),
                        _ => None,
                    });

                    for interface in std::iter::once(self).chain(bases) {
                        for method in interface.get_methods(config) {
                            if let MethodOrName::Method(method) = method {
                                dependencies.combine(&method.dependencies);
                            }
                        }
                    }

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

                let field_methods = write_impl_field_methods(&methods, |name| {
                    if has_unknown_base {
                        quote! { #name: #name::<Identity, OFFSET>, }
                    } else {
                        quote! { #name: #name::<Identity>, }
                    }
                });

                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 upcall = method.write_upcall(&impl_name, &name, config);

                    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 trait_methods = write_impl_trait_methods(&methods, |method| {
                    method.write_impl_signature(config)
                });

                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, 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:?}"),
                }
            });

                // If any methods were skipped due to missing dependencies, omit the
                // `_Impl` trait rather than emitting a partial vtable. Propagate the
                // omission across base interfaces.
                let has_skipped_methods = methods
                    .iter()
                    .any(|method| matches!(method, MethodOrName::Name(_)))
                    || base_interfaces.iter().any(|ty| match ty {
                        Type::CppInterface(ty) => ty.has_skipped_methods(config),
                        _ => false,
                    });

                if has_skipped_methods {
                    if has_unknown_base {
                        result.combine(quote! {
                            #cfg
                            impl windows_core::RuntimeName for #name {}
                        });
                    }
                } else {
                    result.combine( if has_unknown_base {
                let matches = base_interfaces.last().and_then(|ty|{
                    match ty {
                        Type::CppInterface(ty) => {
                            let name = ty.write_vtbl_name(config);
                            Some(quote! { || #name::matches(iid) })
                        }
                        _ => None,
                    }
                });

                quote! {
                    #cfg
                    pub trait #impl_name: #impl_base {
                        #(#trait_methods)*
                    }
                    #cfg
                    impl #vtbl_name {
                        #vis const fn new<Identity: #impl_name, const OFFSET: isize>() -> Self {
                            #(#impl_methods)*
                            Self {
                                #field_base
                                #(#field_methods)*
                            }
                        }
                        #vis 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 {
                        #vis 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 {
                        #vis 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 = windows_core::imp::box_into_raw(windows_core::imp::box_new(this));
                            unsafe { windows_core::ScopedInterface::new(<Self as windows_core::Interface>::from_raw(this as *mut _)) }
                        }
                    }
                }
            });
                }
            }

            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()).parse().unwrap();
        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()).parse().unwrap();
        let namespace = config.write_namespace(self.def.type_name());
        quote! { #namespace #name }
    }

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

        while let Some(base) = def
            .interface_impls()
            .map(move |imp| imp.ty(&[], reader))
            .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
    }
}

fn same_override_type(a: &Type, b: &Type, reader: &Reader) -> bool {
    let a = a.projection_type(reader);
    let b = b.projection_type(reader);
    match (&a, &b) {
        (Type::PtrMut(..), Type::PtrMut(..)) | (Type::PtrConst(..), Type::PtrConst(..)) => {
            same_override_type(&a.deref(), &b.deref(), reader)
        }
        _ => a == b,
    }
}

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

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

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