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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
#![doc = include_str!("../readme.md")]
mod arches;
mod binding_plan;
mod cli;
mod config;
mod derive;
mod derive_writer;
mod format;
mod guid;
mod implements;
mod io;
mod package_writer;
mod param;
mod paths;
mod references;
mod selection;
mod signature;
mod tables;
mod tokens;
mod type_map;
mod type_name;
mod type_tree;
mod types;
mod value;
mod winmd;
use arches::*;
use binding_plan::*;
pub use cli::bindgen;
use config::*;
use derive::*;
use derive_writer::*;
use guid::*;
use implements::*;
use io::*;
use package_writer::*;
use param::*;
use references::*;
use selection::*;
use signature::*;
use std::cmp::Ordering;
use std::collections::*;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use tables::*;
use tokens::*;
use type_map::*;
use type_name::*;
use type_tree::*;
use types::*;
use value::*;
use winmd::*;
mod filter_parser;
mod legacy;
mod method_names;
mod type_closure;
use method_names::*;
use type_closure::*;
/// Creates a new [`Bindgen`] builder for generating Windows API bindings.
pub fn builder() -> Bindgen {
Bindgen::new()
}
/// Builder for generating Windows API bindings.
///
/// This is the fluent alternative to [`bindgen`].
///
/// # Example
///
/// ```rust,no_run
/// windows_bindgen::Bindgen::new()
/// .output("src/bindings.rs")
/// .filter("GetTickCount")
/// .write();
/// ```
#[derive(Default)]
pub struct Bindgen {
input: Vec<Input>,
input_default: bool,
filter: Vec<String>,
output: Option<PathBuf>,
derive: Vec<String>,
implement: Option<Vec<String>>,
compose: Vec<String>,
rustfmt: Option<String>,
layout: Layout,
style: Style,
extern_fns: bool,
dead_code: bool,
}
enum Input {
Path(PathBuf),
Bytes(Vec<u8>),
}
/// Output layout for the generated bindings.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
enum Layout {
/// A single flat list of items (the default).
#[default]
Flat,
/// One Rust module per metadata namespace.
Modules,
/// One file per namespace + `Cargo.toml` features.
Package,
}
impl Layout {
fn is_flat(self) -> bool {
matches!(self, Self::Flat)
}
fn is_package(self) -> bool {
matches!(self, Self::Package)
}
}
/// Code-style mode for the generated bindings.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
enum Style {
/// Minimal bindings (no class wrappers, inherited forwarders, or handle ergonomics;
/// auto-revoke events).
#[default]
Minimal,
/// Full-fidelity bindings.
Full,
/// Raw / sys-style bindings.
Sys,
}
impl Style {
fn is_sys(self) -> bool {
matches!(self, Self::Sys)
}
fn is_minimal(self) -> bool {
matches!(self, Self::Minimal)
}
/// Minimal bindings use the class's default interface directly.
fn emit_class_methods(self) -> bool {
!self.is_minimal()
}
/// Minimal bindings require casting to the interface that owns an inherited method.
fn emit_inherited_forwarders(self) -> bool {
!self.is_minimal()
}
/// Minimal bindings require casting inherited iterables to `IIterable<T>`.
fn emit_iterable_into_iterator(self) -> bool {
!self.is_minimal()
}
/// Minimal bindings expose input strings as `&str`.
fn minimal_string_input(self, param: &Param) -> bool {
self.is_minimal() && param.is_input_only() && matches!(param.ty, Type::String)
}
/// Minimal bindings return strings as `String`.
fn minimal_string_return(self, ty: &Type) -> bool {
self.is_minimal() && matches!(ty, Type::String)
}
/// Sys bindings omit standard derives beyond `Copy` and `Clone`.
fn derive_std_traits(self) -> bool {
!self.is_sys()
}
/// Sys bindings omit traits that require `windows-core`.
fn emit_core_traits(self) -> bool {
!self.is_sys()
}
/// Whether handle structs are emitted as bare aliases rather than newtypes.
fn emit_bare_typedef(self) -> bool {
self.is_sys() || self.is_minimal()
}
}
impl Bindgen {
/// Creates a new builder with default options.
pub fn new() -> Self {
Self::default()
}
/// Adds a `.winmd` file or directory.
///
/// Explicit inputs replace the bundled metadata. Call [`Bindgen::input_default`] to include
/// the bundled metadata alongside them.
pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self {
self.input.push(Input::Path(input.as_ref().to_path_buf()));
self
}
/// Adds the default Windows metadata.
///
/// Included automatically when no explicit inputs are supplied.
pub fn input_default(&mut self) -> &mut Self {
self.input_default = true;
self
}
/// Adds a `.winmd` file from memory.
///
/// Uses the same default metadata behavior as [`Bindgen::input`].
pub fn input_bytes(&mut self, input: &[u8]) -> &mut Self {
self.input.push(Input::Bytes(input.to_vec()));
self
}
/// Adds `.winmd` files from memory.
pub fn input_byte_sets<I, B>(&mut self, inputs: I) -> &mut Self
where
I: IntoIterator<Item = B>,
B: AsRef<[u8]>,
{
for input in inputs {
self.input_bytes(input.as_ref());
}
self
}
/// Adds `.winmd` files or directories.
pub fn inputs<I, S>(&mut self, inputs: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<Path>,
{
for input in inputs {
self.input(input);
}
self
}
/// Sets the generated Rust file.
///
/// Defaults to `bindings.rs` in the runtime `OUT_DIR` directory. An explicit path is required
/// when `OUT_DIR` is unset or empty, and always when generating a package.
pub fn output(&mut self, output: impl AsRef<Path>) -> &mut Self {
self.output = Some(output.as_ref().to_path_buf());
self
}
/// Adds a filter rule to include or exclude APIs.
///
/// See the [crate documentation](crate) for an example table. The same syntax applies to
/// [`Bindgen::filters`], [`Bindgen::filter_file`], and [`bindgen`]'s `--filter` arguments.
///
/// # Names and groups
///
/// Select a function, constant, type, or namespace. Bare names match across namespaces;
/// qualify a name to restrict it to one namespace. Dots and `::` both separate path segments.
/// Namespace selections include descendant namespaces. The bundled Win32 metadata uses
/// `Windows.Win32`, not the subsystem namespaces used by the umbrella crates' Cargo features.
///
/// Groups abbreviate separate selections and may nest: `Windows::Foundation::{Uri, AsyncStatus}`.
/// Trailing commas are allowed. `*` wildcards are not supported.
///
/// # Members and dependencies
///
/// A bare type selects all its members. Use `Type::Member` or `Type::{Member, OtherMember}`
/// for a subset. Members may be methods, properties, events, or enum variants.
/// Use native member or overload names, not renamed Rust methods. Property and event names
/// select their accessor pairs; requesting an event's `add_` method also selects its `remove_`
/// method. `Class::CreateInstance` selects a WinRT class's default constructor.
///
/// Signature dependencies are included automatically, but interfaces reached only through
/// signatures can be name-only declarations. Select their methods explicitly to call them.
/// `Type::{}` requests the type without requesting its methods or enum variants; it does not
/// remove methods selected elsewhere. In minimal mode, a COM interface selected this way can
/// use [`Bindgen::implement`] to emit its implementation trait and vtable without caller wrappers.
///
/// # Combining rules
///
/// Prefix a selection with `!` to exclude it. More specific type/namespace rules take precedence;
/// exclusions win ties regardless of argument order. Member and enum-variant selections narrow
/// whole-type selections, also regardless of order. Excluded members and variants win over
/// included ones, except that implementation traits require the interface's complete method ABI.
/// Named [`Bindgen::implement`] selectors reject method-level inclusions or exclusions on matching
/// interfaces. Select the whole interface or use `Interface::{}` instead.
/// [`Bindgen::implement_all`] allows member filters, but emits the complete method ABI for
/// implemented interfaces.
///
/// Chained members (`Type::Read::Write`), trailing separators (`Type::`), and empty entries
/// inside a group (`Type::{Read,,Write}`) are rejected. Use `Type::{Read, Write}` for several
/// members or `Type::{}` for a name-only selection.
pub fn filter(&mut self, filter: &str) -> &mut Self {
self.filters(std::iter::once(filter))
}
/// Adds filter rules from a text file.
///
/// Uses [`Bindgen::filter`] syntax, with whitespace separating filters outside groups.
/// Groups may span lines. Lines beginning with `//` after optional whitespace are comments;
/// inline comments require a separate `//` token followed by whitespace or the end of the line.
#[track_caller]
pub fn filter_file(&mut self, input: impl AsRef<Path>) -> &mut Self {
self.filters(cli::read_tokens(input, true))
}
/// Adds filter rules from text files.
#[track_caller]
pub fn filter_files<I, S>(&mut self, inputs: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<Path>,
{
for input in inputs {
self.filter_file(input);
}
self
}
/// Add multiple filter rules to include or exclude APIs.
///
/// Uses the same syntax as [`Bindgen::filter`].
pub fn filters<I, S>(&mut self, filters: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for filter in filters {
self.filter.push(filter.as_ref().to_string());
}
self
}
/// Specifies extra derives as `Type=Trait,OtherTrait`, for example `SYSTEMTIME=Debug`.
///
/// The type may be a bare or dotted qualified name and must be included in the generated
/// bindings. Later entries for the same type replace earlier lists.
pub fn derive(&mut self, derive: &str) -> &mut Self {
self.derives(std::iter::once(derive))
}
/// Specifies extra derives for multiple types, using the syntax of [`Bindgen::derive`].
pub fn derives<I, S>(&mut self, derives: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for derive in derives {
self.derive.push(derive.as_ref().to_string());
}
self
}
/// Set comma-separated `rustfmt` configuration options, such as `max_width=120`.
///
/// These are passed to `rustfmt --config`, not used as an executable path.
/// The default is `newline_style=Unix`; supplied options override matching defaults.
/// Formatting is best effort: failures leave the output unformatted without a warning.
pub fn rustfmt(&mut self, rustfmt: &str) -> &mut Self {
self.rustfmt = Some(rustfmt.to_string());
self
}
/// Nest items in one Rust module per metadata namespace instead of a single flat list.
///
/// Use this when the selected APIs define the same name in more than one namespace.
#[track_caller]
pub fn modules(&mut self) -> &mut Self {
if matches!(self.layout, Layout::Package) {
panic!("cannot combine `--package` and `--modules`");
}
self.layout = Layout::Modules;
self
}
fn uses_inline_core_types(&self) -> bool {
self.style.is_sys() && !self.layout.is_package()
}
/// Generate bindings as a package with one file per namespace.
#[track_caller]
pub fn package(&mut self) -> &mut Self {
if matches!(self.layout, Layout::Modules) {
panic!("cannot combine `--package` and `--modules`");
}
self.layout = Layout::Package;
self
}
/// Includes implementation traits for every native and WinRT interface in scope.
///
/// Unlike [`Bindgen::implement`], allows method-level filters. Implemented interfaces still
/// emit their complete method ABI.
#[track_caller]
pub fn implement_all(&mut self) -> &mut Self {
match &self.implement {
None => self.implement = Some(vec![]),
Some(names) if names.is_empty() => {}
Some(_) => panic!("cannot combine `implement_all` with selected implementations"),
}
self
}
/// Includes implementation traits for a native or WinRT interface or namespace prefix.
///
/// Use a dotted qualified name (`Windows.Win32.ISequentialStream`) or a namespace prefix.
/// Unlike filters, bare interface names are not resolved. The interface must be included in
/// the generated bindings, directly or as a dependency; this does not select it.
/// Required base interface implementations are included unless excluded or supplied by a
/// referenced crate.
///
/// Method-level inclusions or exclusions on matching interfaces or their required bases cause
/// [`Bindgen::write`] to panic. Select the whole interface or use `Interface::{}` instead.
#[track_caller]
pub fn implement(&mut self, name: &str) -> &mut Self {
assert!(
!self.implement.as_ref().is_some_and(Vec::is_empty),
"cannot combine selected implementations with `implement_all`"
);
self.implement
.get_or_insert_with(Vec::new)
.push(name.to_string());
self
}
/// Includes implementation traits for multiple native or WinRT interfaces or namespace prefixes.
pub fn implements<I, S>(&mut self, names: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for name in names {
self.implement(name.as_ref());
}
self
}
/// Selects a composable WinRT class as a composition target.
///
/// The class and its composable factory methods must also be selected by a filter.
#[track_caller]
pub fn compose(&mut self, name: &str) -> &mut Self {
assert!(
name.rsplit_once('.')
.is_some_and(|(namespace, name)| !namespace.is_empty() && !name.is_empty()),
"`compose` requires a fully qualified class name"
);
self.compose.push(name.to_string());
self
}
/// Selects multiple composable WinRT classes as composition targets.
pub fn composes<I, S>(&mut self, names: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
for name in names {
self.compose(name.as_ref());
}
self
}
/// Generate raw or sys-style Rust bindings using `windows-link`.
///
/// Mutually exclusive with [`Bindgen::full`].
#[track_caller]
pub fn sys(&mut self) -> &mut Self {
assert!(
self.style != Style::Full,
"cannot combine `--sys` and `--full`"
);
self.style = Style::Sys;
self
}
/// Generate full-fidelity Rust bindings.
///
/// Adds per-class wrapper methods, inherited interface forwarders, handle ergonomics,
/// free-function wrappers, and implementation traits for interfaces not marked `ExclusiveTo`.
/// Use [`Bindgen::implement`] or [`Bindgen::implement_all`] for `ExclusiveTo` interfaces; an
/// explicit selection replaces the full-mode default.
///
/// Mutually exclusive with [`Bindgen::sys`].
#[track_caller]
pub fn full(&mut self) -> &mut Self {
assert!(!self.style.is_sys(), "cannot combine `--sys` and `--full`");
self.style = Style::Full;
self
}
/// Generate `extern` declarations rather than `link!` macros in any binding style.
///
/// DLL and entry-point selection are left to the caller's import libraries, including ordinals.
pub fn extern_fns(&mut self) -> &mut Self {
self.extern_fns = true;
self
}
/// Use `pub(crate)` where possible to surface unused bindings as dead-code warnings.
///
/// Interface and vtable types remain public for trait implementations.
pub fn dead_code(&mut self) -> &mut Self {
self.dead_code = true;
self
}
/// Generate the bindings.
///
/// Without an explicit output, writes `OUT_DIR/bindings.rs`. Use distinct explicit paths for
/// multiple output files. Does not emit Cargo dependency-tracking directives.
///
/// Resolves declarations on demand, including dependencies of selected APIs. Errors in unused
/// declarations may not be reported.
///
/// Panics if input processing, code generation, or writing the output fails.
#[track_caller]
pub fn write(&self) {
// Validate before setting up reader and reference state.
let default_output;
let output = if let Some(output) = &self.output {
output.as_path()
} else {
assert!(
!self.layout.is_package(),
"package output is required (call `.output()` or pass `--out`)"
);
let directory = std::env::var_os("OUT_DIR")
.filter(|value| !value.is_empty())
.unwrap_or_else(|| {
panic!("output is required (set `OUT_DIR`, call `.output()` or pass `--out`)")
});
default_output = PathBuf::from(directory).join("bindings.rs");
&default_output
};
assert!(
!output.as_os_str().is_empty(),
"output is required (call `.output()` or pass `--out`)"
);
assert!(
self.compose.is_empty() || self.style.is_minimal(),
"`compose` cannot be combined with `--full` or `--sys`"
);
let mut include: Vec<&str> = vec![];
let mut exclude: Vec<&str> = vec![];
for f in &self.filter {
if let Some(rest) = f.strip_prefix('!') {
exclude.push(rest);
} else {
include.push(f.as_str());
}
}
assert!(!include.is_empty(), "at least one `--filter` required");
let sys = self.style.is_sys();
let link = if sys { "windows_link" } else { "windows_core" };
let reader_storage;
let reader = if self.input.is_empty() {
default_reader(sys)
} else {
let input = expand_input(&self.input, self.input_default);
reader_storage = if self.layout.is_package() {
Reader::new_package(input, sys)
} else if sys {
Reader::new_sys(input)
} else {
Reader::new(input)
};
&reader_storage
};
let mut references: Vec<ReferenceStage> = Vec::new();
if !sys {
// Register implicit references to sibling windows-* crates present in metadata.
for (probe_namespace, crate_name, paths) in [
(
"Windows.Foundation",
"windows_future",
&[
"Windows.Foundation.AsyncActionCompletedHandler",
"Windows.Foundation.AsyncActionProgressHandler",
"Windows.Foundation.AsyncActionWithProgressCompletedHandler",
"Windows.Foundation.AsyncOperationCompletedHandler",
"Windows.Foundation.AsyncOperationProgressHandler",
"Windows.Foundation.AsyncOperationWithProgressCompletedHandler",
"Windows.Foundation.AsyncStatus",
"Windows.Foundation.IAsyncAction",
"Windows.Foundation.IAsyncActionWithProgress",
"Windows.Foundation.IAsyncInfo",
"Windows.Foundation.IAsyncOperation",
"Windows.Foundation.IAsyncOperationWithProgress",
][..],
),
(
"Windows.Foundation.Collections",
"windows_collections",
&[
"Windows.Foundation.Collections.CollectionChange",
"Windows.Foundation.Collections.IIterable",
"Windows.Foundation.Collections.IIterator",
"Windows.Foundation.Collections.IKeyValuePair",
"Windows.Foundation.Collections.IMap",
"Windows.Foundation.Collections.IMapChangedEventArgs",
"Windows.Foundation.Collections.IMapView",
"Windows.Foundation.Collections.IObservableMap",
"Windows.Foundation.Collections.IObservableVector",
"Windows.Foundation.Collections.IVector",
"Windows.Foundation.Collections.IVectorChangedEventArgs",
"Windows.Foundation.Collections.IVectorView",
"Windows.Foundation.Collections.MapChangedEventHandler",
"Windows.Foundation.Collections.VectorChangedEventHandler",
][..],
),
(
"Windows.Foundation",
"windows_reference",
&["Windows.Foundation.IReference"][..],
),
(
"Windows.Foundation",
"windows_time",
&["Windows.Foundation.DateTime", "Windows.Foundation.TimeSpan"][..],
),
(
"Windows.Foundation.Numerics",
"windows_numerics",
&[
"Windows.Foundation.Numerics.Matrix3x2",
"Windows.Foundation.Numerics.Matrix4x4",
"Windows.Foundation.Numerics.Vector2",
"Windows.Foundation.Numerics.Vector3",
"Windows.Foundation.Numerics.Vector4",
][..],
),
] {
if reader.contains_namespace(probe_namespace) {
let filtered: Vec<&str> = paths
.iter()
.copied()
.filter(|path| {
if let Some((namespace, name)) = path.rsplit_once('.') {
return reader.contains_name(namespace, name);
}
false
})
.collect();
if !filtered.is_empty() {
prepend_default_refs(&mut references, crate_name, &filtered);
}
}
}
}
let derive_str: Vec<&str> = self.derive.iter().map(|s| s.as_str()).collect();
let implements = self.implement.as_ref().map(|names| {
let names_str: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
Implements::new(&names_str)
});
let references = References::new(reader, references);
let plan = {
let mut all_parsed = Vec::new();
for entry in &include {
all_parsed.extend(filter_parser::parse_filter_entry(entry));
}
for entry in &exclude {
let mut entries = filter_parser::parse_filter_entry(entry);
for e in &mut entries {
e.exclude = true;
}
all_parsed.extend(entries);
}
let resolved = filter_parser::resolve_entries(reader, &all_parsed);
BindingPlan::new(
reader,
&resolved,
references,
implements.as_ref(),
self.style,
)
};
let derive = Derive::new(reader, &plan.types, &derive_str);
let shadowed_prelude = Config::shadowed_prelude(&plan.types);
let config = Config {
bindgen: self,
reader,
plan: &plan,
derive: &derive,
implement: implements.as_ref(),
link,
namespace: "",
shadowed_prelude: &shadowed_prelude,
event_only_delegates: &HashSet::new(),
self_ty: None,
self_generics: Vec::new(),
prunable: std::sync::Arc::new(BTreeSet::new()),
};
let event_only_delegates = compute_event_only_delegates(&config);
let config = Config {
event_only_delegates: &event_only_delegates,
..config
};
for target in &self.compose {
let class = composition_target(reader, target);
assert!(
plan.types.contains_key(&class.type_name()),
"composition target `{target}` is not selected by the filter"
);
assert!(
class
.required_interfaces(reader)
.iter()
.filter(|interface| interface.kind == InterfaceKind::Composable)
.filter(|interface| plan.types.contains_key(&interface.def.type_name()))
.any(|interface| interface.def.methods().any(|method| {
plan.selection
.includes_method(interface.type_name(), method)
&& plan.includes_method(method, &interface.generics)
})),
"composition target `{target}` has no composable factory method selected by the \
filter"
);
}
let tree = TypeTree::new(&plan.types, self.layout.is_flat());
config.write(tree, output);
}
}
#[track_caller]
fn composition_target(reader: &Reader, target: &str) -> Class {
let (namespace, name) = target.rsplit_once('.').unwrap();
let class = reader
.with_full_name(namespace, name)
.find_map(|ty| match ty {
Type::Class(class) => Some(class),
_ => None,
})
.unwrap_or_else(|| panic!("composition target `{target}` is not a WinRT class"));
assert!(
class
.required_interfaces(reader)
.iter()
.any(|interface| interface.kind == InterfaceKind::Composable),
"composition target `{target}` is not composable"
);
class
}
fn default_reader(sys: bool) -> &'static Reader {
static READER: std::sync::OnceLock<Reader> = std::sync::OnceLock::new();
static SYS_READER: std::sync::OnceLock<Reader> = std::sync::OnceLock::new();
if sys {
SYS_READER.get_or_init(|| Reader::from_index(default_index(), false))
} else {
READER.get_or_init(|| Reader::from_index(default_index(), true))
}
}
fn default_index() -> &'static windows_metadata::reader::Index {
static INDEX: std::sync::OnceLock<&windows_metadata::reader::Index> =
std::sync::OnceLock::new();
INDEX.get_or_init(|| windows_metadata::reader::Index::new(default_input()).leak())
}
#[track_caller]
fn default_input() -> Vec<File> {
[windows_default::WINRT, windows_default::WIN32]
.into_iter()
.map(|bytes| File::new(bytes.to_vec()).unwrap())
.collect()
}
fn expand_input(input: &[Input], input_default: bool) -> Vec<File> {
#[track_caller]
fn expand_path(result: &mut Vec<File>, path: &Path) {
if path.is_dir() {
let mut paths = vec![];
for path in path
.read_dir()
.unwrap_or_else(|_| panic!("failed to read directory `{}`", path.display()))
.flatten()
.map(|entry| entry.path())
{
if path.is_file()
&& path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("winmd"))
{
paths.push(path);
}
}
assert!(
!paths.is_empty(),
"failed to find .winmd files in directory `{}`",
path.display()
);
for path in paths {
let bytes = std::fs::read(&path)
.unwrap_or_else(|_| panic!("failed to read binary file `{}`", path.display()));
let file = File::new(bytes)
.unwrap_or_else(|| panic!("failed to read .winmd format `{}`", path.display()));
result.push(file);
}
} else {
let Ok(bytes) = std::fs::read(path) else {
panic!("failed to read binary file `{}`", path.display());
};
let Some(file) = File::new(bytes) else {
panic!("failed to read .winmd format `{}`", path.display());
};
result.push(file);
}
}
let mut result = if input_default {
default_input()
} else {
vec![]
};
for input in input {
match input {
Input::Path(path) => expand_path(&mut result, path),
Input::Bytes(bytes) => result.push(
File::new(bytes.clone())
.unwrap_or_else(|| panic!("failed to read .winmd format from memory")),
),
}
}
result
}
/// Finds delegates used only as event-handler parameters.
fn compute_event_only_delegates(config: &Config) -> HashSet<TypeName> {
let mut event_delegates: HashSet<TypeName> = HashSet::new();
let mut non_event_delegates: HashSet<TypeName> = HashSet::new();
for type_set in config.plan.types.values() {
for ty in type_set {
let (methods, generics): (Box<dyn Iterator<Item = MethodDef>>, &[Type]) = match ty {
Type::Interface(i) => (Box::new(i.def.methods()), &i.generics),
_ => continue,
};
for method in methods {
let sig = method.method_signature(generics, config.reader);
if !config.plan.includes_method(method, generics) {
continue;
}
let is_event_add = method.flags().contains(MethodAttributes::SpecialName)
&& method.name().starts_with("add_");
for param in &sig.params {
if let Type::Delegate(d) = ¶m.ty {
if is_event_add {
event_delegates.insert(d.type_name());
} else {
non_event_delegates.insert(d.type_name());
}
}
}
}
}
}
event_delegates
.difference(&non_event_delegates)
.copied()
.collect()
}
fn namespace_starts_with(namespace: &str, starts_with: &str) -> bool {
namespace.starts_with(starts_with)
&& (namespace.len() == starts_with.len()
|| namespace.as_bytes().get(starts_with.len()) == Some(&b'.'))
}
/// Derives the cargo-feature name for a `--package` namespace.
fn namespace_feature(namespace: &str) -> String {
if let Some((_, rest)) = namespace.split_once('.') {
rest.replace('.', "_")
} else {
namespace.to_string()
}
}
/// Prepend reference entries so they take precedence.
fn prepend_default_refs(refs: &mut Vec<ReferenceStage>, crate_name: &str, paths: &[&str]) {
refs.splice(
0..0,
paths
.iter()
.rev()
.map(|path| ReferenceStage::new(crate_name, path)),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_starts_with() {
assert!(namespace_starts_with(
"Windows.Win32.Graphics.Direct3D11on12",
"Windows.Win32.Graphics.Direct3D11on12"
));
assert!(namespace_starts_with(
"Windows.Win32.Graphics.Direct3D11on12",
"Windows.Win32.Graphics"
));
assert!(!namespace_starts_with(
"Windows.Win32.Graphics.Direct3D11on12",
"Windows.Win32.Graphics.Direct3D11"
));
assert!(!namespace_starts_with(
"Windows.Win32.Graphics.Direct3D",
"Windows.Win32.Graphics.Direct3D11"
));
}
#[test]
fn default_metadata_reader_is_reused() {
assert!(std::ptr::eq(default_reader(false), default_reader(false)));
assert!(std::ptr::eq(default_reader(true), default_reader(true)));
assert!(!std::ptr::eq(default_reader(false), default_reader(true)));
}
#[test]
fn implementation_selection() {
let mut builder = Bindgen::new();
builder
.implement("Test.IFirst")
.implements(["Test.ISecond", "Other"]);
assert_eq!(
builder.implement,
Some(vec![
"Test.IFirst".to_string(),
"Test.ISecond".to_string(),
"Other".to_string()
])
);
let mut builder = Bindgen::new();
builder.implement_all().implement_all();
assert_eq!(builder.implement, Some(vec![]));
let mut builder = Bindgen::new();
builder.implements(std::iter::empty::<&str>());
assert_eq!(builder.implement, None);
}
#[test]
fn composition_selection() {
let mut builder = Bindgen::new();
builder
.compose("Test.First")
.composes(["Test.Second", "Other.Third"]);
assert_eq!(
builder.compose,
vec![
"Test.First".to_string(),
"Test.Second".to_string(),
"Other.Third".to_string()
]
);
}
#[test]
#[should_panic(expected = "cannot combine selected implementations with `implement_all`")]
fn implementation_after_all_panics() {
Bindgen::new().implement_all().implement("Test.IFirst");
}
#[test]
#[should_panic(expected = "cannot combine `implement_all` with selected implementations")]
fn implementation_all_after_selection_panics() {
Bindgen::new().implement("Test.IFirst").implement_all();
}
}