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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
use super::*;

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

// Shared by the WinRT (`Interface`/`Method`) and Win32/COM (`CppInterface`/`CppMethod`)
// generators: a vtable slot is either a fully-projected method or an opaque,
// name-only placeholder (filtered out or missing dependencies).
#[derive(Clone, Debug)]
pub enum MethodOrName<M> {
    Method(M),
    Name(MethodDef),
}

// The two pieces a vtable/`_Impl` writer needs from a projected method, regardless of
// whether it is a WinRT `Method` or a Win32/COM `CppMethod`. Lets the shared emitters
// below iterate `MethodOrName<M>` without caring which generator produced it.
pub trait MethodItem {
    fn def(&self) -> MethodDef;
    fn dependencies(&self) -> &TypeMap;
}

impl MethodItem for Method {
    fn def(&self) -> MethodDef {
        self.def
    }
    fn dependencies(&self) -> &TypeMap {
        &self.dependencies
    }
}

impl MethodItem for CppMethod {
    fn def(&self) -> MethodDef {
        self.def
    }
    fn dependencies(&self) -> &TypeMap {
        &self.dependencies
    }
}

// Caller names may omit filtered methods, but vtable names must count every slot.
pub fn named_methods<M: MethodItem>(
    methods: &[MethodOrName<M>],
) -> impl Iterator<Item = (&M, TokenStream)> {
    let mut names = MethodNames::new();
    methods.iter().filter_map(move |method| match method {
        MethodOrName::Method(method) => Some((method, names.add(method.def()))),
        MethodOrName::Name(def) => {
            names.add(*def);
            None
        }
    })
}

// Shared `_Vtbl` method-field emitter; callers provide the ABI signature tail.
pub fn write_vtbl_methods<M: MethodItem>(
    methods: &[MethodOrName<M>],
    class_cfg: &Cfg,
    config: &Config,
    mut signature: impl FnMut(&M) -> TokenStream,
) -> Vec<TokenStream> {
    let mut names = MethodNames::new();
    methods
        .iter()
        .map(|method| match method {
            MethodOrName::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 sig = signature(method);

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

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

// Shared `_Vtbl::new()` field initializer emitter.
pub fn write_impl_field_methods<M: MethodItem>(
    methods: &[MethodOrName<M>],
    mut method_field: impl FnMut(&TokenStream) -> TokenStream,
) -> Vec<TokenStream> {
    let mut names = MethodNames::new();
    methods
        .iter()
        .map(|method| match method {
            MethodOrName::Method(method) => {
                let name = names.add(method.def());
                method_field(&name)
            }
            MethodOrName::Name(method) => {
                let name = names.add(*method);
                quote! { #name: 0, }
            }
        })
        .collect()
}

// Shared `_Impl` trait method emitter.
pub fn write_impl_trait_methods<M: MethodItem>(
    methods: &[MethodOrName<M>],
    mut signature: impl FnMut(&M) -> TokenStream,
) -> Vec<TokenStream> {
    let mut names = MethodNames::new();
    methods
        .iter()
        .map(|method| match method {
            MethodOrName::Method(method) => {
                let name = names.add(method.def());
                let sig = signature(method);
                quote! { fn #name #sig; }
            }
            _ => quote! {},
        })
        .collect()
}

#[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<Method>> {
        self.def
            .methods()
            .map(|def| {
                let method = Method::new(def, &self.generics, config.reader);
                if !config.plan.includes_method(def, &self.generics) {
                    MethodOrName::Name(method.def)
                } else {
                    MethodOrName::Method(method)
                }
            })
            .collect()
    }

    // `_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, &self.generics))
    }

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

    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(config.reader);
        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 named_phantoms = config.write_generic_named_phantoms(&self.generics);
        let (class_cfg, cfg) = self.write_cfg(config);

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

            // Drop trailing usize slots - nothing indexes past the last real
            // method, so they waste space and compile time.
            let methods_for_vtbl: &[MethodOrName<Method>] = {
                let last_real = methods
                    .iter()
                    .rposition(|m| matches!(m, MethodOrName::Method(_)));
                match last_real {
                    Some(pos) => &methods[..=pos],
                    None => &[],
                }
            };

            let vtbl_methods = write_vtbl_methods(methods_for_vtbl, &class_cfg, config, |method| {
                let vtbl = method.write_abi(config, false);
                quote! { (#vtbl) -> #core HRESULT }
            });

            let hide_vtbl = config.doc_hidden_in_package();

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

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

            if !config.bindgen.layout.is_package() {
                if let Some(guid) = self.def.guid_attribute() {
                    let name: TokenStream = format!("IID_{}", trim_tick(self.def.name()))
                        .parse()
                        .unwrap();
                    result.combine(config.write_cpp_const_guid(name, &guid));
                }

                result.combine(vtbl);
            }

            result
        } else {
            let guid = config.write_guid_u128(&self.def.guid_attribute().unwrap());
            let runtime_name = if config.emit_runtime_name(type_name) {
                let arity = self.generics.len();
                let name = if arity == 0 {
                    format!("{type_name}")
                } else {
                    format!("{type_name}`{arity}")
                };
                let name = Literal::byte_string(name.as_bytes());
                quote! { , #name }
            } else {
                quote! {}
            };
            let mut result = quote! {
                #cfg
                windows_core::imp::define_winrt_interface!(#name, #vtbl_name, #guid #runtime_name);
            };

            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: Vec<_> = required_interfaces
                        .iter()
                        .filter(|ty| {
                            config.provides(&Type::Interface((*ty).clone()))
                                && config.plan.selection.includes_hierarchy(
                                    type_name.namespace(),
                                    type_name.name(),
                                    ty,
                                )
                        })
                        .map(|ty| ty.write_name(config))
                        .collect();

                    if !interfaces.is_empty() {
                        result.combine(quote! {
                            #cfg
                            windows_core::imp::required_hierarchy!(#name, #(#interfaces),*);
                        });
                    }
                } else {
                    let interfaces = required_interfaces
                        .iter()
                        .filter(|ty| {
                            config.provides(&Type::Interface((*ty).clone()))
                                && config.plan.selection.includes_hierarchy(
                                    type_name.namespace(),
                                    type_name.name(),
                                    ty,
                                )
                        })
                        .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)*
                    });
                }
            }

            // Implementation-only interfaces need ABI slots and `_Impl`, not callable wrappers.
            let minimal = config.bindgen.style.is_minimal();
            let implementation_only = config.should_implement(type_name, false)
                && config.plan.selection.is_shell(type_name);
            let suppress_methods = minimal
                && ((is_exclusive && self.is_factory(config.reader)) || implementation_only);
            let emit_methods = !suppress_methods && (!is_exclusive || minimal);
            if emit_methods {
                let method_names = &mut MethodNames::new();
                let mut method_tokens = TokenStream::new();
                let mut iterable = None;
                // References to this interface can be emitted as `Self` inside this impl.
                let self_config = config.with_self_ty(self.type_name(), &self.generics);

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

                    let method = method.write(
                        &self_config,
                        Some(self),
                        InterfaceKind::Default,
                        method_names,
                        &vname,
                        true,
                    );

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

                for interface in &required_interfaces {
                    if !config.bindgen.style.emit_inherited_forwarders()
                        || !config.plan.selection.includes_hierarchy(
                            type_name.namespace(),
                            type_name.name(),
                            interface,
                        )
                    {
                        continue;
                    }
                    for (method, vname) in named_methods(&interface.get_methods(config)) {
                        let cfg = method.write_cfg(config, &class_cfg, false);
                        let def = method.def;

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

                        if interface.type_name() == TypeName::IIterable && def.name() == "First" {
                            iterable = Some((interface, method_names.last_name(def)));
                        }

                        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 {}
                    });
                }

                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<#constraints> 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<#constraints> 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
                };

                if let Some(into_iterator) = into_iterator {
                    result.combine(into_iterator);
                }
            }

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

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

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

                let cfg = if config.bindgen.layout.is_package() {
                    let mut dependencies = self.dependencies(config.reader);

                    for interface in std::iter::once(self).chain(&required_interfaces) {
                        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! {}
                };

                result.combine(if self.generics.is_empty() {
                    quote! {
                        #cfg
                        impl<#constraints> windows_core::RuntimeName for #name {
                            const NAME: &'static str = #runtime_name;
                        }
                    }
                } else {
                    quote! {
                        #cfg
                        impl<#constraints> windows_core::RuntimeName for #name {
                            const NAME: &'static str = #runtime_name;
                            const RUNTIME_CLASS_NAME: windows_core::imp::ConstBuffer = <Self as windows_core::RuntimeType>::NAME;
                        }
                    }
                });

                // Omit `_Impl` when this interface or a required interface has skipped methods.
                let has_skipped_methods = methods
                    .iter()
                    .any(|method| matches!(method, MethodOrName::Name(_)))
                    || required_interfaces
                        .iter()
                        .any(|ty| ty.has_skipped_methods(config));

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

                    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, config);

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

                    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 {
                    #vis const fn new<Identity: #impl_name <#(#generics,)*>, const OFFSET: isize>() -> Self {
                        #(#impl_methods)*
                        Self {
                            base__: windows_core::IInspectable_Vtbl::new::<Identity, OFFSET>(),
                            #(#field_methods)*
                            #named_phantoms
                        }
                    }
                    #vis fn matches(iid: &windows_core::GUID) -> bool {
                        iid == &<#name as windows_core::Interface>::IID
                    }
                }
            });
                }
            }

            result.combine(vtbl);
            if emit_methods {
                result.combine(self.write_extensions(&methods));
            }
            result
        }
    }

    fn write_extensions(&self, methods: &[MethodOrName<Method>]) -> TokenStream {
        let has_method = |name: &str| {
            methods.iter().any(
                |method| matches!(method, MethodOrName::Method(method) if method.def.name() == name),
            )
        };
        match self.type_name() {
            TypeName::IIterator
                if ["get_Current", "get_HasCurrent", "MoveNext"]
                    .iter()
                    .all(|name| has_method(name)) =>
            {
                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() {
                                // Ignore MoveNext errors; treat as end-of-stream on the next
                                // iteration but still yield the value already fetched.
                                let _ = self.MoveNext();
                            }

                            result
                        }
                    }
                }
            }
            TypeName::IIterable if has_method("First") => {
                quote! {
                    impl<T: windows_core::RuntimeType> IntoIterator for IIterable<T> {
                        type Item = T;
                        type IntoIter = windows_collections::BufferedIterator<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 = windows_collections::BufferedIterator<Self::Item>;

                        fn into_iter(self) -> Self::IntoIter {
                            windows_collections::BufferedIterator::new(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", trim_tick(self.def.name()))
            .parse()
            .unwrap();

        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", trim_tick(self.def.name()))
            .parse()
            .unwrap();
        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")
    }

    // Factory interfaces are reached through their class in minimal mode.
    pub fn is_factory(&self, reader: &Reader) -> bool {
        let Some(attribute) = self.def.find_attribute("ExclusiveToAttribute") else {
            return false;
        };
        let value = attribute.value();
        let Some((_, Value::TypeName(class_tn))) = value.first() else {
            return false;
        };
        let Some(Type::Class(class)) = reader
            .with_full_name(class_tn.namespace.as_str(), class_tn.name.as_str())
            .next()
        else {
            return false;
        };

        let our_namespace = self.def.namespace();
        let our_name = self.def.name();

        for attribute in class.def.attributes() {
            match attribute.name() {
                "StaticAttribute" | "ActivatableAttribute" | "ComposableAttribute" => {
                    for (_, arg) in attribute.value() {
                        if let Value::TypeName(tn) = arg
                            && tn.namespace.as_str() == our_namespace
                            && tn.name.as_str() == our_name
                        {
                            return true;
                        }
                    }
                }
                _ => {}
            }
        }

        false
    }

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

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

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

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

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

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

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

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

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

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

    #[test]
    fn definition_identity_agrees_across_collections() {
        let reader = default_reader(false);
        let Type::Interface(mut left) = reader
            .with_full_name("Windows.Foundation.Collections", "IIterable`1")
            .next()
            .unwrap()
        else {
            panic!();
        };
        left.generics = vec![Type::String];
        let mut right = left.clone();
        right.generics = vec![Type::U32];
        assert_eq!(left.cmp(&right), Ordering::Equal);
        assert_eq!(left, right);
        assert_eq!(HashSet::from([left.clone(), right.clone()]).len(), 1);
        assert_eq!(BTreeSet::from([left, right]).len(), 1);
    }
}