1#![doc = include_str!("../readme.md")]
2
3mod arches;
4mod binding_plan;
5mod cli;
6mod config;
7mod derive;
8mod derive_writer;
9mod format;
10mod guid;
11mod implements;
12mod io;
13mod package_writer;
14mod param;
15mod paths;
16mod references;
17mod selection;
18mod signature;
19mod tables;
20mod tokens;
21mod type_map;
22mod type_name;
23mod type_tree;
24mod types;
25mod value;
26mod winmd;
27
28use arches::*;
29use binding_plan::*;
30pub use cli::bindgen;
31use config::*;
32use derive::*;
33use derive_writer::*;
34use guid::*;
35use implements::*;
36use io::*;
37use package_writer::*;
38use param::*;
39use references::*;
40use selection::*;
41use signature::*;
42use std::cmp::Ordering;
43use std::collections::*;
44use std::fmt::Write;
45use std::path::{Path, PathBuf};
46use tables::*;
47use tokens::*;
48use type_map::*;
49use type_name::*;
50use type_tree::*;
51use types::*;
52use value::*;
53use winmd::*;
54mod filter_parser;
55mod legacy;
56mod method_names;
57mod type_closure;
58use method_names::*;
59use type_closure::*;
60
61pub fn builder() -> Bindgen {
63 Bindgen::new()
64}
65
66#[derive(Default)]
79pub struct Bindgen {
80 input: Vec<Input>,
81 input_default: bool,
82 filter: Vec<String>,
83 output: Option<PathBuf>,
84 derive: Vec<String>,
85 implement: Option<Vec<String>>,
86 compose: Vec<String>,
87 rustfmt: Option<String>,
88 layout: Layout,
89 style: Style,
90 extern_fns: bool,
91 dead_code: bool,
92}
93
94enum Input {
95 Path(PathBuf),
96 Bytes(Vec<u8>),
97}
98
99#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
101enum Layout {
102 #[default]
104 Flat,
105 Modules,
107 Package,
109}
110
111impl Layout {
112 fn is_flat(self) -> bool {
113 matches!(self, Self::Flat)
114 }
115 fn is_package(self) -> bool {
116 matches!(self, Self::Package)
117 }
118}
119
120#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
122enum Style {
123 #[default]
126 Minimal,
127 Full,
129 Sys,
131}
132
133impl Style {
134 fn is_sys(self) -> bool {
135 matches!(self, Self::Sys)
136 }
137 fn is_minimal(self) -> bool {
138 matches!(self, Self::Minimal)
139 }
140 fn emit_class_methods(self) -> bool {
142 !self.is_minimal()
143 }
144
145 fn emit_inherited_forwarders(self) -> bool {
147 !self.is_minimal()
148 }
149
150 fn emit_iterable_into_iterator(self) -> bool {
152 !self.is_minimal()
153 }
154
155 fn minimal_string_input(self, param: &Param) -> bool {
157 self.is_minimal() && param.is_input_only() && matches!(param.ty, Type::String)
158 }
159
160 fn minimal_string_return(self, ty: &Type) -> bool {
162 self.is_minimal() && matches!(ty, Type::String)
163 }
164
165 fn derive_std_traits(self) -> bool {
167 !self.is_sys()
168 }
169
170 fn emit_core_traits(self) -> bool {
172 !self.is_sys()
173 }
174
175 fn emit_bare_typedef(self) -> bool {
177 self.is_sys() || self.is_minimal()
178 }
179}
180
181impl Bindgen {
182 pub fn new() -> Self {
184 Self::default()
185 }
186
187 pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self {
192 self.input.push(Input::Path(input.as_ref().to_path_buf()));
193 self
194 }
195
196 pub fn input_default(&mut self) -> &mut Self {
200 self.input_default = true;
201 self
202 }
203
204 pub fn input_bytes(&mut self, input: &[u8]) -> &mut Self {
208 self.input.push(Input::Bytes(input.to_vec()));
209 self
210 }
211
212 pub fn input_byte_sets<I, B>(&mut self, inputs: I) -> &mut Self
214 where
215 I: IntoIterator<Item = B>,
216 B: AsRef<[u8]>,
217 {
218 for input in inputs {
219 self.input_bytes(input.as_ref());
220 }
221 self
222 }
223
224 pub fn inputs<I, S>(&mut self, inputs: I) -> &mut Self
226 where
227 I: IntoIterator<Item = S>,
228 S: AsRef<Path>,
229 {
230 for input in inputs {
231 self.input(input);
232 }
233 self
234 }
235
236 pub fn output(&mut self, output: impl AsRef<Path>) -> &mut Self {
241 self.output = Some(output.as_ref().to_path_buf());
242 self
243 }
244
245 pub fn filter(&mut self, filter: &str) -> &mut Self {
289 self.filters(std::iter::once(filter))
290 }
291
292 #[track_caller]
298 pub fn filter_file(&mut self, input: impl AsRef<Path>) -> &mut Self {
299 self.filters(cli::read_tokens(input, true))
300 }
301
302 #[track_caller]
304 pub fn filter_files<I, S>(&mut self, inputs: I) -> &mut Self
305 where
306 I: IntoIterator<Item = S>,
307 S: AsRef<Path>,
308 {
309 for input in inputs {
310 self.filter_file(input);
311 }
312 self
313 }
314
315 pub fn filters<I, S>(&mut self, filters: I) -> &mut Self
319 where
320 I: IntoIterator<Item = S>,
321 S: AsRef<str>,
322 {
323 for filter in filters {
324 self.filter.push(filter.as_ref().to_string());
325 }
326 self
327 }
328
329 pub fn derive(&mut self, derive: &str) -> &mut Self {
334 self.derives(std::iter::once(derive))
335 }
336
337 pub fn derives<I, S>(&mut self, derives: I) -> &mut Self
339 where
340 I: IntoIterator<Item = S>,
341 S: AsRef<str>,
342 {
343 for derive in derives {
344 self.derive.push(derive.as_ref().to_string());
345 }
346 self
347 }
348
349 pub fn rustfmt(&mut self, rustfmt: &str) -> &mut Self {
355 self.rustfmt = Some(rustfmt.to_string());
356 self
357 }
358
359 #[track_caller]
363 pub fn modules(&mut self) -> &mut Self {
364 if matches!(self.layout, Layout::Package) {
365 panic!("cannot combine `--package` and `--modules`");
366 }
367 self.layout = Layout::Modules;
368 self
369 }
370
371 fn uses_inline_core_types(&self) -> bool {
372 self.style.is_sys() && !self.layout.is_package()
373 }
374
375 #[track_caller]
377 pub fn package(&mut self) -> &mut Self {
378 if matches!(self.layout, Layout::Modules) {
379 panic!("cannot combine `--package` and `--modules`");
380 }
381 self.layout = Layout::Package;
382 self
383 }
384
385 #[track_caller]
390 pub fn implement_all(&mut self) -> &mut Self {
391 match &self.implement {
392 None => self.implement = Some(vec![]),
393 Some(names) if names.is_empty() => {}
394 Some(_) => panic!("cannot combine `implement_all` with selected implementations"),
395 }
396 self
397 }
398
399 #[track_caller]
410 pub fn implement(&mut self, name: &str) -> &mut Self {
411 assert!(
412 !self.implement.as_ref().is_some_and(Vec::is_empty),
413 "cannot combine selected implementations with `implement_all`"
414 );
415 self.implement
416 .get_or_insert_with(Vec::new)
417 .push(name.to_string());
418 self
419 }
420
421 pub fn implements<I, S>(&mut self, names: I) -> &mut Self
423 where
424 I: IntoIterator<Item = S>,
425 S: AsRef<str>,
426 {
427 for name in names {
428 self.implement(name.as_ref());
429 }
430 self
431 }
432
433 #[track_caller]
437 pub fn compose(&mut self, name: &str) -> &mut Self {
438 assert!(
439 name.rsplit_once('.')
440 .is_some_and(|(namespace, name)| !namespace.is_empty() && !name.is_empty()),
441 "`compose` requires a fully qualified class name"
442 );
443 self.compose.push(name.to_string());
444 self
445 }
446
447 pub fn composes<I, S>(&mut self, names: I) -> &mut Self
449 where
450 I: IntoIterator<Item = S>,
451 S: AsRef<str>,
452 {
453 for name in names {
454 self.compose(name.as_ref());
455 }
456 self
457 }
458
459 #[track_caller]
463 pub fn sys(&mut self) -> &mut Self {
464 assert!(
465 self.style != Style::Full,
466 "cannot combine `--sys` and `--full`"
467 );
468 self.style = Style::Sys;
469 self
470 }
471
472 #[track_caller]
481 pub fn full(&mut self) -> &mut Self {
482 assert!(!self.style.is_sys(), "cannot combine `--sys` and `--full`");
483 self.style = Style::Full;
484 self
485 }
486
487 pub fn extern_fns(&mut self) -> &mut Self {
491 self.extern_fns = true;
492 self
493 }
494
495 pub fn dead_code(&mut self) -> &mut Self {
499 self.dead_code = true;
500 self
501 }
502
503 #[track_caller]
513 pub fn write(&self) {
514 let default_output;
516 let output = if let Some(output) = &self.output {
517 output.as_path()
518 } else {
519 assert!(
520 !self.layout.is_package(),
521 "package output is required (call `.output()` or pass `--out`)"
522 );
523 let directory = std::env::var_os("OUT_DIR")
524 .filter(|value| !value.is_empty())
525 .unwrap_or_else(|| {
526 panic!("output is required (set `OUT_DIR`, call `.output()` or pass `--out`)")
527 });
528 default_output = PathBuf::from(directory).join("bindings.rs");
529 &default_output
530 };
531 assert!(
532 !output.as_os_str().is_empty(),
533 "output is required (call `.output()` or pass `--out`)"
534 );
535 assert!(
536 self.compose.is_empty() || self.style.is_minimal(),
537 "`compose` cannot be combined with `--full` or `--sys`"
538 );
539
540 let mut include: Vec<&str> = vec![];
541 let mut exclude: Vec<&str> = vec![];
542
543 for f in &self.filter {
544 if let Some(rest) = f.strip_prefix('!') {
545 exclude.push(rest);
546 } else {
547 include.push(f.as_str());
548 }
549 }
550
551 assert!(!include.is_empty(), "at least one `--filter` required");
552
553 let sys = self.style.is_sys();
554 let link = if sys { "windows_link" } else { "windows_core" };
555
556 let reader_storage;
557 let reader = if self.input.is_empty() {
558 default_reader(sys)
559 } else {
560 let input = expand_input(&self.input, self.input_default);
561 reader_storage = if self.layout.is_package() {
562 Reader::new_package(input, sys)
563 } else if sys {
564 Reader::new_sys(input)
565 } else {
566 Reader::new(input)
567 };
568 &reader_storage
569 };
570
571 let mut references: Vec<ReferenceStage> = Vec::new();
572
573 if !sys {
574 for (probe_namespace, crate_name, paths) in [
576 (
577 "Windows.Foundation",
578 "windows_future",
579 &[
580 "Windows.Foundation.AsyncActionCompletedHandler",
581 "Windows.Foundation.AsyncActionProgressHandler",
582 "Windows.Foundation.AsyncActionWithProgressCompletedHandler",
583 "Windows.Foundation.AsyncOperationCompletedHandler",
584 "Windows.Foundation.AsyncOperationProgressHandler",
585 "Windows.Foundation.AsyncOperationWithProgressCompletedHandler",
586 "Windows.Foundation.AsyncStatus",
587 "Windows.Foundation.IAsyncAction",
588 "Windows.Foundation.IAsyncActionWithProgress",
589 "Windows.Foundation.IAsyncInfo",
590 "Windows.Foundation.IAsyncOperation",
591 "Windows.Foundation.IAsyncOperationWithProgress",
592 ][..],
593 ),
594 (
595 "Windows.Foundation.Collections",
596 "windows_collections",
597 &[
598 "Windows.Foundation.Collections.CollectionChange",
599 "Windows.Foundation.Collections.IIterable",
600 "Windows.Foundation.Collections.IIterator",
601 "Windows.Foundation.Collections.IKeyValuePair",
602 "Windows.Foundation.Collections.IMap",
603 "Windows.Foundation.Collections.IMapChangedEventArgs",
604 "Windows.Foundation.Collections.IMapView",
605 "Windows.Foundation.Collections.IObservableMap",
606 "Windows.Foundation.Collections.IObservableVector",
607 "Windows.Foundation.Collections.IVector",
608 "Windows.Foundation.Collections.IVectorChangedEventArgs",
609 "Windows.Foundation.Collections.IVectorView",
610 "Windows.Foundation.Collections.MapChangedEventHandler",
611 "Windows.Foundation.Collections.VectorChangedEventHandler",
612 ][..],
613 ),
614 (
615 "Windows.Foundation",
616 "windows_reference",
617 &["Windows.Foundation.IReference"][..],
618 ),
619 (
620 "Windows.Foundation",
621 "windows_time",
622 &["Windows.Foundation.DateTime", "Windows.Foundation.TimeSpan"][..],
623 ),
624 (
625 "Windows.Foundation.Numerics",
626 "windows_numerics",
627 &[
628 "Windows.Foundation.Numerics.Matrix3x2",
629 "Windows.Foundation.Numerics.Matrix4x4",
630 "Windows.Foundation.Numerics.Vector2",
631 "Windows.Foundation.Numerics.Vector3",
632 "Windows.Foundation.Numerics.Vector4",
633 ][..],
634 ),
635 ] {
636 if reader.contains_namespace(probe_namespace) {
637 let filtered: Vec<&str> = paths
638 .iter()
639 .copied()
640 .filter(|path| {
641 if let Some((namespace, name)) = path.rsplit_once('.') {
642 return reader.contains_name(namespace, name);
643 }
644 false
645 })
646 .collect();
647 if !filtered.is_empty() {
648 prepend_default_refs(&mut references, crate_name, &filtered);
649 }
650 }
651 }
652 }
653
654 let derive_str: Vec<&str> = self.derive.iter().map(|s| s.as_str()).collect();
655 let implements = self.implement.as_ref().map(|names| {
656 let names_str: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
657 Implements::new(&names_str)
658 });
659
660 let references = References::new(reader, references);
661
662 let plan = {
663 let mut all_parsed = Vec::new();
664 for entry in &include {
665 all_parsed.extend(filter_parser::parse_filter_entry(entry));
666 }
667 for entry in &exclude {
668 let mut entries = filter_parser::parse_filter_entry(entry);
669 for e in &mut entries {
670 e.exclude = true;
671 }
672 all_parsed.extend(entries);
673 }
674 let resolved = filter_parser::resolve_entries(reader, &all_parsed);
675
676 BindingPlan::new(
677 reader,
678 &resolved,
679 references,
680 implements.as_ref(),
681 self.style,
682 )
683 };
684
685 let derive = Derive::new(reader, &plan.types, &derive_str);
686
687 let shadowed_prelude = Config::shadowed_prelude(&plan.types);
688 let config = Config {
689 bindgen: self,
690 reader,
691 plan: &plan,
692 derive: &derive,
693 implement: implements.as_ref(),
694 link,
695 namespace: "",
696 shadowed_prelude: &shadowed_prelude,
697 event_only_delegates: &HashSet::new(),
698 self_ty: None,
699 self_generics: Vec::new(),
700 prunable: std::sync::Arc::new(BTreeSet::new()),
701 };
702 let event_only_delegates = compute_event_only_delegates(&config);
703 let config = Config {
704 event_only_delegates: &event_only_delegates,
705 ..config
706 };
707 for target in &self.compose {
708 let class = composition_target(reader, target);
709 assert!(
710 plan.types.contains_key(&class.type_name()),
711 "composition target `{target}` is not selected by the filter"
712 );
713 assert!(
714 class
715 .required_interfaces(reader)
716 .iter()
717 .filter(|interface| interface.kind == InterfaceKind::Composable)
718 .filter(|interface| plan.types.contains_key(&interface.def.type_name()))
719 .any(|interface| interface.def.methods().any(|method| {
720 plan.selection
721 .includes_method(interface.type_name(), method)
722 && plan.includes_method(method, &interface.generics)
723 })),
724 "composition target `{target}` has no composable factory method selected by the \
725 filter"
726 );
727 }
728
729 let tree = TypeTree::new(&plan.types, self.layout.is_flat());
730 config.write(tree, output);
731 }
732}
733
734#[track_caller]
735fn composition_target(reader: &Reader, target: &str) -> Class {
736 let (namespace, name) = target.rsplit_once('.').unwrap();
737 let class = reader
738 .with_full_name(namespace, name)
739 .find_map(|ty| match ty {
740 Type::Class(class) => Some(class),
741 _ => None,
742 })
743 .unwrap_or_else(|| panic!("composition target `{target}` is not a WinRT class"));
744 assert!(
745 class
746 .required_interfaces(reader)
747 .iter()
748 .any(|interface| interface.kind == InterfaceKind::Composable),
749 "composition target `{target}` is not composable"
750 );
751 class
752}
753
754fn default_reader(sys: bool) -> &'static Reader {
755 static READER: std::sync::OnceLock<Reader> = std::sync::OnceLock::new();
756 static SYS_READER: std::sync::OnceLock<Reader> = std::sync::OnceLock::new();
757 if sys {
758 SYS_READER.get_or_init(|| Reader::from_index(default_index(), false))
759 } else {
760 READER.get_or_init(|| Reader::from_index(default_index(), true))
761 }
762}
763
764fn default_index() -> &'static windows_metadata::reader::Index {
765 static INDEX: std::sync::OnceLock<&windows_metadata::reader::Index> =
766 std::sync::OnceLock::new();
767 INDEX.get_or_init(|| windows_metadata::reader::Index::new(default_input()).leak())
768}
769
770#[track_caller]
771fn default_input() -> Vec<File> {
772 [windows_default::WINRT, windows_default::WIN32]
773 .into_iter()
774 .map(|bytes| File::new(bytes.to_vec()).unwrap())
775 .collect()
776}
777
778fn expand_input(input: &[Input], input_default: bool) -> Vec<File> {
779 #[track_caller]
780 fn expand_path(result: &mut Vec<File>, path: &Path) {
781 if path.is_dir() {
782 let mut paths = vec![];
783
784 for path in path
785 .read_dir()
786 .unwrap_or_else(|_| panic!("failed to read directory `{}`", path.display()))
787 .flatten()
788 .map(|entry| entry.path())
789 {
790 if path.is_file()
791 && path
792 .extension()
793 .is_some_and(|extension| extension.eq_ignore_ascii_case("winmd"))
794 {
795 paths.push(path);
796 }
797 }
798
799 assert!(
800 !paths.is_empty(),
801 "failed to find .winmd files in directory `{}`",
802 path.display()
803 );
804
805 for path in paths {
806 let bytes = std::fs::read(&path)
807 .unwrap_or_else(|_| panic!("failed to read binary file `{}`", path.display()));
808 let file = File::new(bytes)
809 .unwrap_or_else(|| panic!("failed to read .winmd format `{}`", path.display()));
810 result.push(file);
811 }
812 } else {
813 let Ok(bytes) = std::fs::read(path) else {
814 panic!("failed to read binary file `{}`", path.display());
815 };
816 let Some(file) = File::new(bytes) else {
817 panic!("failed to read .winmd format `{}`", path.display());
818 };
819 result.push(file);
820 }
821 }
822
823 let mut result = if input_default {
824 default_input()
825 } else {
826 vec![]
827 };
828
829 for input in input {
830 match input {
831 Input::Path(path) => expand_path(&mut result, path),
832 Input::Bytes(bytes) => result.push(
833 File::new(bytes.clone())
834 .unwrap_or_else(|| panic!("failed to read .winmd format from memory")),
835 ),
836 }
837 }
838
839 result
840}
841
842fn compute_event_only_delegates(config: &Config) -> HashSet<TypeName> {
844 let mut event_delegates: HashSet<TypeName> = HashSet::new();
845 let mut non_event_delegates: HashSet<TypeName> = HashSet::new();
846
847 for type_set in config.plan.types.values() {
848 for ty in type_set {
849 let (methods, generics): (Box<dyn Iterator<Item = MethodDef>>, &[Type]) = match ty {
850 Type::Interface(i) => (Box::new(i.def.methods()), &i.generics),
851 _ => continue,
852 };
853
854 for method in methods {
855 let sig = method.method_signature(generics, config.reader);
856 if !config.plan.includes_method(method, generics) {
857 continue;
858 }
859 let is_event_add = method.flags().contains(MethodAttributes::SpecialName)
860 && method.name().starts_with("add_");
861
862 for param in &sig.params {
863 if let Type::Delegate(d) = ¶m.ty {
864 if is_event_add {
865 event_delegates.insert(d.type_name());
866 } else {
867 non_event_delegates.insert(d.type_name());
868 }
869 }
870 }
871 }
872 }
873 }
874
875 event_delegates
876 .difference(&non_event_delegates)
877 .copied()
878 .collect()
879}
880
881fn namespace_starts_with(namespace: &str, starts_with: &str) -> bool {
882 namespace.starts_with(starts_with)
883 && (namespace.len() == starts_with.len()
884 || namespace.as_bytes().get(starts_with.len()) == Some(&b'.'))
885}
886
887fn namespace_feature(namespace: &str) -> String {
889 if let Some((_, rest)) = namespace.split_once('.') {
890 rest.replace('.', "_")
891 } else {
892 namespace.to_string()
893 }
894}
895
896fn prepend_default_refs(refs: &mut Vec<ReferenceStage>, crate_name: &str, paths: &[&str]) {
898 refs.splice(
899 0..0,
900 paths
901 .iter()
902 .rev()
903 .map(|path| ReferenceStage::new(crate_name, path)),
904 );
905}
906
907#[cfg(test)]
908mod tests {
909 use super::*;
910
911 #[test]
912 fn test_starts_with() {
913 assert!(namespace_starts_with(
914 "Windows.Win32.Graphics.Direct3D11on12",
915 "Windows.Win32.Graphics.Direct3D11on12"
916 ));
917 assert!(namespace_starts_with(
918 "Windows.Win32.Graphics.Direct3D11on12",
919 "Windows.Win32.Graphics"
920 ));
921 assert!(!namespace_starts_with(
922 "Windows.Win32.Graphics.Direct3D11on12",
923 "Windows.Win32.Graphics.Direct3D11"
924 ));
925 assert!(!namespace_starts_with(
926 "Windows.Win32.Graphics.Direct3D",
927 "Windows.Win32.Graphics.Direct3D11"
928 ));
929 }
930
931 #[test]
932 fn default_metadata_reader_is_reused() {
933 assert!(std::ptr::eq(default_reader(false), default_reader(false)));
934 assert!(std::ptr::eq(default_reader(true), default_reader(true)));
935 assert!(!std::ptr::eq(default_reader(false), default_reader(true)));
936 }
937
938 #[test]
939 fn implementation_selection() {
940 let mut builder = Bindgen::new();
941 builder
942 .implement("Test.IFirst")
943 .implements(["Test.ISecond", "Other"]);
944 assert_eq!(
945 builder.implement,
946 Some(vec![
947 "Test.IFirst".to_string(),
948 "Test.ISecond".to_string(),
949 "Other".to_string()
950 ])
951 );
952
953 let mut builder = Bindgen::new();
954 builder.implement_all().implement_all();
955 assert_eq!(builder.implement, Some(vec![]));
956
957 let mut builder = Bindgen::new();
958 builder.implements(std::iter::empty::<&str>());
959 assert_eq!(builder.implement, None);
960 }
961
962 #[test]
963 fn composition_selection() {
964 let mut builder = Bindgen::new();
965 builder
966 .compose("Test.First")
967 .composes(["Test.Second", "Other.Third"]);
968 assert_eq!(
969 builder.compose,
970 vec![
971 "Test.First".to_string(),
972 "Test.Second".to_string(),
973 "Other.Third".to_string()
974 ]
975 );
976 }
977
978 #[test]
979 #[should_panic(expected = "cannot combine selected implementations with `implement_all`")]
980 fn implementation_after_all_panics() {
981 Bindgen::new().implement_all().implement("Test.IFirst");
982 }
983
984 #[test]
985 #[should_panic(expected = "cannot combine `implement_all` with selected implementations")]
986 fn implementation_all_after_selection_panics() {
987 Bindgen::new().implement("Test.IFirst").implement_all();
988 }
989}