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

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

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

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

    pub fn write(&self, config: &Config) -> TokenStream {
        let required_interfaces = self.required_interfaces(config.reader);
        let type_name = self.def.type_name();
        let get_methods = |interface: &Interface| {
            interface
                .get_methods(config)
                .into_iter()
                .map(|method| match method {
                    MethodOrName::Method(method)
                        if !config.plan.selection.includes_method(type_name, method.def) =>
                    {
                        MethodOrName::Name(method.def)
                    }
                    method => method,
                })
                .collect::<Vec<_>>()
        };
        let name = to_ident(type_name.name());
        // Methods flattened onto the class live in `impl #name`, so references to the
        // class (e.g. constructor return types) are emitted as `Self`.
        let self_config = config.with_self_ty(type_name, &[]);
        let (class_cfg, cfg) = self.write_cfg(config);
        let runtime_name = format!("{type_name}");

        let runtime_name = quote! {
            #cfg
            impl windows_core::RuntimeName for #name {
                const NAME: &'static str = #runtime_name;
            }
        };

        let mut methods = quote! {};
        let mut iterable = None;

        if config.bindgen.style.emit_class_methods() {
            let mut method_names = MethodNames::new();

            for interface in &required_interfaces {
                for (method, vname) in named_methods(&get_methods(interface)) {
                    let cfg = method.write_cfg(config, &class_cfg, false);
                    let def = method.def;

                    let method = method.write(
                        &self_config,
                        Some(interface),
                        interface.kind,
                        &mut method_names,
                        &vname,
                        true,
                    );

                    if interface.type_name() == TypeName::IIterable
                        && !matches!(
                            interface.kind,
                            InterfaceKind::Static | InterfaceKind::Composable
                        )
                        && def.name() == "First"
                    {
                        iterable = Some((interface, method_names.last_name(def)));
                    }

                    methods.combine(quote! {
                        #cfg
                        #method
                    });
                }
            }
        } else {
            // In minimal mode, only flatten static/factory methods onto the class
            // (needed for static caching). Instance methods live on their interfaces.
            let mut method_names = MethodNames::new();

            let needs_compose = config.should_compose(type_name);

            for interface in required_interfaces
                .iter()
                .filter(|i| matches!(i.kind, InterfaceKind::Static | InterfaceKind::Composable))
            {
                for (method, vname) in named_methods(&get_methods(interface)) {
                    let cfg = method.write_cfg(config, &class_cfg, false);

                    let method = method.write(
                        &self_config,
                        Some(interface),
                        interface.kind,
                        &mut method_names,
                        &vname,
                        needs_compose,
                    );

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

        let result = config.write_core();

        let vis = config.item_vis();

        let has_default_ctor = self.has_default_constructor(config.reader)
            && config
                .plan
                .selection
                .is_activatable(type_name.namespace(), type_name.name());

        let new = has_default_ctor.then(||
            quote! {
                #vis fn new() -> #result Result<Self> {
                    Self::IActivationFactory(|f| f.ActivateInstance::<Self>())
                }
                fn IActivationFactory<R, F: FnOnce(&windows_core::imp::IGenericFactory) -> #result Result<R>>(
                    callback: F,
                ) -> #result Result<R> {
                    static SHARED: windows_core::imp::FactoryCache<#name, windows_core::imp::IGenericFactory> =
                        windows_core::imp::FactoryCache::new();
                    SHARED.call(callback)
                }
            }
        );

        let factories: Vec<_> = required_interfaces.iter().filter_map(|interface| match interface.kind {
            InterfaceKind::Static | InterfaceKind::Composable => {
                let methods: Vec<_> = get_methods(interface)
                    .into_iter()
                    .filter_map(|method| match method {
                        MethodOrName::Method(method) => Some(method),
                        MethodOrName::Name(_) => None,
                    })
                    .collect();
                if methods.is_empty() {
                    None
                } else {
                        let method_name = to_ident(trim_tick(interface.def.name()));
                        let interface_type = interface.write_name(config);

                        let cfg = Cfg::write_any(
                            methods.iter().map(|method| class_cfg.difference(&method.dependencies, config)),
                            config,
                        );

                        Some(quote! {
                            #cfg
                            fn #method_name<R, F: FnOnce(&#interface_type) -> #result Result<R>>(
                                callback: F,
                            ) -> #result Result<R> {
                                static SHARED: windows_core::imp::FactoryCache<#name, #interface_type> =
                                    windows_core::imp::FactoryCache::new();
                                SHARED.call(callback)
                            }
                        })
                    }
                }
                _ => None,
            }).collect();

        if let Some(default_interface) = self.default_interface(config.reader) {
            if default_interface.is_async() {
                let default_interface = default_interface.write_name(config);

                return quote! {
                    #cfg
                    pub type #name = #default_interface;
                };
            }

            let is_exclusive = default_interface.is_exclusive();
            let default_interface = default_interface.write_name(config);

            let interface_hierarchy = if is_exclusive {
                quote! { windows_core::imp::interface_hierarchy!(#name, windows_core::IUnknown, windows_core::IInspectable); }
            } else {
                quote! { windows_core::imp::interface_hierarchy!(#name, windows_core::IUnknown, windows_core::IInspectable, #default_interface); }
            };

            let required_hierarchy = {
                let mut interfaces: Vec<_> = required_interfaces
                    .iter()
                    .filter(|ty| {
                        !ty.is_exclusive()
                            && matches!(ty.kind, InterfaceKind::None | InterfaceKind::Base)
                    })
                    .filter(|ty| {
                        config.provides(&Type::Interface((*ty).clone()))
                            && config.plan.selection.includes_hierarchy(
                                self.def.namespace(),
                                self.def.name(),
                                ty,
                            )
                    })
                    .map(|ty| ty.write_name(config))
                    .collect();

                interfaces.extend(
                    self.bases(config.reader)
                        .iter()
                        .filter(|ty| config.provides(&Type::Class((*ty).clone())))
                        .map(|ty| ty.write_name(config)),
                );

                if interfaces.is_empty() {
                    quote! {}
                } else {
                    quote! {
                        #cfg
                        windows_core::imp::required_hierarchy!(#name, #(#interfaces),*);
                    }
                }
            };

            let agile = self.def.is_agile().then(|| {
                quote! {
                    #cfg
                    unsafe impl Send for #name {}
                    #cfg
                    unsafe impl Sync for #name {}
                }
            });

            let into_iterator = if config.bindgen.style.emit_iterable_into_iterator() {
                iterable.map(|(interface, first)| {
                    let ty = interface.generics[0].write_name(config);

                    quote! {
                        #cfg
                        impl IntoIterator for #name {
                            type Item = #ty;
                            type IntoIter = windows_collections::BufferedIterator<Self::Item>;

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

                            fn into_iter(self) -> Self::IntoIter {
                                windows_collections::BufferedIterator::new(self.#first().unwrap())
                            }
                        }

                    }
                })
            } else {
                None
            };

            let deref = if config.bindgen.style.is_minimal() {
                quote! {
                    #cfg
                    impl core::ops::Deref for #name {
                        type Target = #default_interface;
                        fn deref(&self) -> &Self::Target {
                            unsafe { core::mem::transmute(self) }
                        }
                    }
                }
            } else {
                quote! {}
            };

            let impl_block = if new.is_none() && methods.is_empty() && factories.is_empty() {
                quote! {}
            } else {
                quote! {
                    #cfg
                    impl #name {
                        #new
                        #methods
                        #(#factories)*
                    }
                }
            };

            quote! {
                #cfg
                #[repr(transparent)]
                #[derive(Clone, Debug, Eq, PartialEq)]
                pub struct #name(windows_core::IUnknown);
                #cfg
                #interface_hierarchy
                #required_hierarchy
                #impl_block
                #cfg
                impl windows_core::RuntimeType for #name {
                    const SIGNATURE: windows_core::imp::ConstBuffer = windows_core::imp::ConstBuffer::for_class::<Self, #default_interface>();
                }
                #cfg
                unsafe impl windows_core::Interface for #name {
                    type Vtable = <#default_interface as windows_core::Interface>::Vtable;
                    const IID: windows_core::GUID = <#default_interface as windows_core::Interface>::IID;
                    const INSPECTABLE: bool = true;
                }
                #deref
                #runtime_name
                #agile
                #into_iterator
            }
        } else {
            let impl_block = if methods.is_empty() && factories.is_empty() {
                quote! {}
            } else {
                quote! {
                    #cfg
                    impl #name {
                        #methods
                        #(#factories)*
                    }
                }
            };

            quote! {
                #cfg
                pub struct #name;
                #impl_block
                #runtime_name
            }
        }
    }

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

    fn default_interface(&self, reader: &Reader) -> Option<Type> {
        self.def
            .interface_impls()
            .find(|imp| imp.has_attribute("DefaultAttribute"))
            .map(|imp| imp.ty(&[], reader))
    }

    pub fn runtime_signature(&self, reader: &Reader) -> String {
        format!(
            "rc({};{})",
            self.type_name(),
            self.default_interface(reader)
                .unwrap()
                .runtime_signature(reader)
        )
    }

    pub fn bases(&self, reader: &Reader) -> Vec<Self> {
        let mut bases = Vec::new();
        let mut def = self.def;

        loop {
            let extends = def.extends().unwrap();

            if extends == (TypeName::Object.0, TypeName::Object.1) {
                break;
            }

            let Type::Class(base) = reader.unwrap_type_name(extends.namespace(), extends.name())
            else {
                panic!("type not found: {extends:?}");
            };

            def = base.def;
            bases.push(base);
        }

        bases
    }

    pub fn required_interfaces(&self, reader: &Reader) -> Vec<Interface> {
        fn walk(
            def: TypeDef,
            generics: &[Type],
            is_base: bool,
            set: &mut Vec<Interface>,
            reader: &Reader,
        ) {
            for imp in def.interface_impls() {
                let Type::Interface(mut interface) = imp.ty(generics, reader) else {
                    panic!();
                };

                interface.kind = if !is_base && imp.has_attribute("DefaultAttribute") {
                    InterfaceKind::Default
                } else if is_base {
                    InterfaceKind::Base
                } else {
                    InterfaceKind::None
                };

                if let Some(pos) = set
                    .iter()
                    .position(|existing| existing.def == interface.def)
                {
                    if interface.kind == InterfaceKind::Default {
                        set[pos].kind = interface.kind;
                    }
                } else {
                    walk(interface.def, &interface.generics, is_base, set, reader);
                    set.push(interface);
                }
            }
        }
        let mut set = vec![];
        walk(self.def, &[], false, &mut set, reader);

        for base in self.bases(reader) {
            walk(base.def, &[], true, &mut set, reader);
        }

        for attribute in self.def.attributes() {
            let kind = match attribute.name() {
                "StaticAttribute" | "ActivatableAttribute" => InterfaceKind::Static,
                "ComposableAttribute" => InterfaceKind::Composable,
                _ => continue,
            };

            for (_, arg) in attribute.value() {
                if let Value::TypeName(tn) = arg
                    && let Some(Type::Interface(mut interface)) = reader
                        .with_full_name(tn.namespace.as_str(), tn.name.as_str())
                        .next()
                {
                    interface.kind = kind;
                    set.push(interface);
                    break;
                }
            }
        }

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

    fn has_default_constructor(&self, reader: &Reader) -> bool {
        self.def
            .attributes()
            .filter(|attribute| attribute.name() == "ActivatableAttribute")
            .any(|attribute| {
                !attribute.value().iter().any(|(_, arg)| {
                    if let Value::TypeName(tn) = arg {
                        matches!(
                            reader
                                .with_full_name(tn.namespace.as_str(), tn.name.as_str())
                                .next(),
                            Some(Type::Interface(_))
                        )
                    } else {
                        false
                    }
                })
            })
    }
}

impl Dependencies for Class {
    fn combine(&self, dependencies: &mut TypeMap, reader: &Reader) {
        for interface in self.required_interfaces(reader) {
            Type::Interface(interface).combine(dependencies, reader);
        }
        for base in self.bases(reader) {
            Type::Class(base).combine(dependencies, reader);
        }
    }
}