Skip to main content

windows_bindgen/
lib.rs

1#![doc = include_str!("../../../README.md")]
2
3mod cli;
4mod config;
5mod derive;
6mod derive_writer;
7mod filter;
8mod format;
9mod guid;
10mod implements;
11mod io;
12mod package_writer;
13mod param;
14mod paths;
15mod references;
16mod signature;
17mod tables;
18mod tokens;
19mod type_map;
20mod type_name;
21mod type_tree;
22mod types;
23mod value;
24mod winmd;
25
26pub use cli::bindgen;
27use config::*;
28use derive::*;
29use derive_writer::*;
30use filter::*;
31use guid::*;
32use implements::*;
33use io::*;
34use package_writer::*;
35use param::*;
36use references::*;
37use signature::*;
38use std::cmp::Ordering;
39use std::collections::*;
40use std::fmt::Write;
41use std::path::{Path, PathBuf};
42use tables::*;
43use tokens::*;
44use type_map::*;
45use type_name::*;
46use type_tree::*;
47use types::*;
48use value::*;
49use winmd::*;
50mod filter_parser;
51mod method_names;
52mod type_closure;
53use method_names::*;
54use type_closure::*;
55
56fn report_timing(output: &Path, phase: &str, elapsed: std::time::Duration) {
57    if std::env::var_os("WINDOWS_BINDGEN_TIMINGS").is_some() {
58        eprintln!(
59            "windows-bindgen timing `{}` {phase}: {:.3} ms",
60            output.display(),
61            elapsed.as_secs_f64() * 1_000.0
62        );
63    }
64}
65
66/// Creates a new [`Bindgen`] builder for generating Windows API bindings.
67pub fn builder() -> Bindgen {
68    Bindgen::new()
69}
70
71/// Builder for generating Windows API bindings.
72///
73/// This is the fluent alternative to [`bindgen`].
74///
75/// # Example
76///
77/// ```rust,no_run
78/// windows_bindgen::Bindgen::new()
79///     .output("src/bindings.rs")
80///     .filter("GetTickCount")
81///     .write();
82/// ```
83#[derive(Default)]
84pub struct Bindgen {
85    input: Vec<Input>,
86    input_default: bool,
87    filter: Vec<String>,
88    output: PathBuf,
89    derive: Vec<String>,
90    implement: Option<Vec<String>>,
91    compose: Vec<String>,
92    rustfmt: Option<String>,
93    layout: Layout,
94    package_feature_root: Option<String>,
95    external_references: Vec<ReferenceStage>,
96    style: Style,
97    dead_code: bool,
98}
99
100enum Input {
101    Path(PathBuf),
102    Bytes(Vec<u8>),
103}
104
105/// Output layout for the generated bindings.
106#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
107enum Layout {
108    /// One Rust module per metadata namespace (the default).
109    #[default]
110    Modules,
111    /// A single flat list of items (no namespace modules).
112    Flat,
113    /// One file per namespace + `Cargo.toml` features.
114    Package,
115}
116
117impl Layout {
118    fn is_flat(self) -> bool {
119        matches!(self, Self::Flat)
120    }
121    fn is_package(self) -> bool {
122        matches!(self, Self::Package)
123    }
124}
125
126/// Code-style mode for the generated bindings.
127#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
128enum Style {
129    /// Full-fidelity bindings (the default).
130    #[default]
131    Default,
132    /// Raw / sys-style bindings.
133    Sys {
134        /// When `true`, emit `extern { fn ... }` instead of `link!` macros.
135        extern_fns: bool,
136    },
137    /// Minimal-mode bindings (drop class wrappers, inherited forwarders,
138    /// handle ergonomics; auto-revoke events).
139    Minimal,
140}
141
142impl Style {
143    fn is_sys(self) -> bool {
144        matches!(self, Self::Sys { .. })
145    }
146    fn is_minimal(self) -> bool {
147        matches!(self, Self::Minimal)
148    }
149    fn sys_fn_extern(self) -> bool {
150        matches!(self, Self::Sys { extern_fns: true })
151    }
152
153    /// Minimal bindings use the class's default interface directly.
154    fn emit_class_methods(self) -> bool {
155        !self.is_minimal()
156    }
157
158    /// Minimal bindings require casting to the interface that owns an inherited method.
159    fn emit_inherited_forwarders(self) -> bool {
160        !self.is_minimal()
161    }
162
163    /// Minimal bindings require casting inherited iterables to `IIterable<T>`.
164    fn emit_iterable_into_iterator(self) -> bool {
165        !self.is_minimal()
166    }
167
168    /// Minimal bindings expose input strings as `&str`.
169    fn minimal_string_input(self, param: &Param) -> bool {
170        self.is_minimal() && param.is_input_only() && matches!(param.ty, Type::String)
171    }
172
173    /// Minimal bindings return strings as `String`.
174    fn minimal_string_return(self, ty: &Type) -> bool {
175        self.is_minimal() && matches!(ty, Type::String)
176    }
177
178    /// Sys bindings omit standard derives beyond `Copy` and `Clone`.
179    fn derive_std_traits(self) -> bool {
180        !self.is_sys()
181    }
182
183    /// Sys bindings omit traits that require `windows-core`.
184    fn emit_core_traits(self) -> bool {
185        !self.is_sys()
186    }
187
188    /// Whether handle structs are emitted as bare aliases rather than newtypes.
189    fn emit_bare_typedef(self) -> bool {
190        self.is_sys() || self.is_minimal()
191    }
192}
193
194impl Bindgen {
195    /// Creates a new builder with default options.
196    pub fn new() -> Self {
197        Self::default()
198    }
199
200    /// Adds a `.winmd` file or directory.
201    pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self {
202        self.input.push(Input::Path(input.as_ref().to_path_buf()));
203        self
204    }
205
206    /// Adds the default Windows metadata.
207    pub fn input_default(&mut self) -> &mut Self {
208        self.input_default = true;
209        self
210    }
211
212    /// Adds a `.winmd` file from memory.
213    pub fn input_bytes(&mut self, input: &[u8]) -> &mut Self {
214        self.input.push(Input::Bytes(input.to_vec()));
215        self
216    }
217
218    /// Adds `.winmd` files from memory.
219    pub fn input_byte_sets<I, B>(&mut self, inputs: I) -> &mut Self
220    where
221        I: IntoIterator<Item = B>,
222        B: AsRef<[u8]>,
223    {
224        for input in inputs {
225            self.input_bytes(input.as_ref());
226        }
227        self
228    }
229
230    /// Adds `.winmd` files or directories.
231    pub fn inputs<I, S>(&mut self, inputs: I) -> &mut Self
232    where
233        I: IntoIterator<Item = S>,
234        S: AsRef<Path>,
235    {
236        for input in inputs {
237            self.input(input);
238        }
239        self
240    }
241
242    /// Sets the generated Rust file.
243    pub fn output(&mut self, output: impl AsRef<Path>) -> &mut Self {
244        self.output = output.as_ref().to_path_buf();
245        self
246    }
247
248    /// Add a filter rule to include or exclude APIs.
249    ///
250    /// Filter rules may be a function or type name, a namespace prefix, a fully-qualified name,
251    /// or a method-level entry of the form `Namespace.Type::Method` (with optional `Property` /
252    /// `Event` sugar). Prefix with `!` to exclude rather than include. See the crate-level
253    /// docs for the full grammar.
254    pub fn filter(&mut self, filter: &str) -> &mut Self {
255        self.filters(std::iter::once(filter))
256    }
257
258    /// Adds filter rules from a text file.
259    #[track_caller]
260    pub fn filter_file(&mut self, input: impl AsRef<Path>) -> &mut Self {
261        self.filters(cli::read_tokens(input))
262    }
263
264    /// Adds filter rules from text files.
265    #[track_caller]
266    pub fn filter_files<I, S>(&mut self, inputs: I) -> &mut Self
267    where
268        I: IntoIterator<Item = S>,
269        S: AsRef<Path>,
270    {
271        for input in inputs {
272            self.filter_file(input);
273        }
274        self
275    }
276
277    /// Add multiple filter rules to include or exclude APIs.
278    ///
279    /// Filter rules may be a function or type name, a namespace prefix, a fully-qualified name,
280    /// or a method-level entry of the form `Namespace.Type::Method` (with optional `Property` /
281    /// `Event` sugar). Prefix with `!` to exclude rather than include. See the crate-level
282    /// docs for the full grammar.
283    pub fn filters<I, S>(&mut self, filters: I) -> &mut Self
284    where
285        I: IntoIterator<Item = S>,
286        S: AsRef<str>,
287    {
288        for filter in filters {
289            self.filter.push(filter.as_ref().to_string());
290        }
291        self
292    }
293
294    /// Add an extra trait for types to derive.
295    pub fn derive(&mut self, derive: &str) -> &mut Self {
296        self.derives(std::iter::once(derive))
297    }
298
299    /// Add multiple extra traits for types to derive.
300    pub fn derives<I, S>(&mut self, derives: I) -> &mut Self
301    where
302        I: IntoIterator<Item = S>,
303        S: AsRef<str>,
304    {
305        for derive in derives {
306            self.derive.push(derive.as_ref().to_string());
307        }
308        self
309    }
310
311    /// Override the default Rust formatter path.
312    pub fn rustfmt(&mut self, rustfmt: &str) -> &mut Self {
313        self.rustfmt = Some(rustfmt.to_string());
314        self
315    }
316
317    /// Avoid the default namespace-to-module conversion.
318    #[track_caller]
319    pub fn flat(&mut self) -> &mut Self {
320        if matches!(self.layout, Layout::Package) {
321            panic!("cannot combine `--package` and `--flat`");
322        }
323        self.layout = Layout::Flat;
324        self
325    }
326
327    fn uses_inline_core_types(&self) -> bool {
328        self.style.is_sys() && !self.layout.is_package()
329    }
330
331    /// Generate bindings as a package with one file per namespace.
332    #[track_caller]
333    pub fn package(&mut self) -> &mut Self {
334        if matches!(self.layout, Layout::Flat) {
335            panic!("cannot combine `--package` and `--flat`");
336        }
337        self.layout = Layout::Package;
338        self
339    }
340
341    /// Treats the given top-level package namespace as a feature-only root
342    /// whose child namespaces depend directly on one another.
343    pub fn package_feature_root(&mut self, namespace: &str) -> &mut Self {
344        assert!(
345            !namespace.is_empty() && !namespace.contains('.'),
346            "package feature root must be a top-level namespace"
347        );
348        self.package_feature_root = Some(namespace.to_string());
349        self
350    }
351
352    /// Routes metadata types matched by `filter` to an external Rust crate or module prefix.
353    ///
354    /// The filter uses the same namespace and type syntax as [`Bindgen::filter`]. Routed types
355    /// remain available as dependencies of generated APIs, but are not generated in this output
356    /// package or represented by local Cargo feature gates.
357    ///
358    /// ```
359    /// # let mut builder = windows_bindgen::Bindgen::new();
360    /// builder.external_reference("Vendor.Types", "vendor_bindings::types");
361    /// ```
362    #[track_caller]
363    pub fn external_reference(&mut self, filter: &str, rust_path_prefix: &str) -> &mut Self {
364        validate_external_reference_filter(filter);
365        validate_rust_path_prefix(rust_path_prefix);
366        self.external_references.push(ReferenceStage::external(
367            rust_path_prefix.trim(),
368            filter.trim(),
369        ));
370        self
371    }
372
373    fn is_package_feature_root(&self, namespace: &str) -> bool {
374        is_flat_container(namespace) || self.package_feature_root.as_deref() == Some(namespace)
375    }
376
377    fn package_feature_root_contains(&self, namespace: &str) -> bool {
378        self.package_feature_root.as_deref().is_none_or(|root| {
379            namespace == root
380                || namespace
381                    .strip_prefix(root)
382                    .is_some_and(|suffix| suffix.starts_with('.'))
383        })
384    }
385
386    fn package_feature(&self, namespace: &str) -> String {
387        if let Some(root) = &self.package_feature_root {
388            if let Some(relative) = namespace
389                .strip_prefix(root)
390                .and_then(|relative| relative.strip_prefix('.'))
391            {
392                return relative.replace('.', "_");
393            }
394            return namespace.replace('.', "_");
395        }
396        namespace_feature(namespace)
397    }
398
399    /// Includes implementation traits for every WinRT interface in scope.
400    #[track_caller]
401    pub fn implement_all(&mut self) -> &mut Self {
402        match &self.implement {
403            None => self.implement = Some(vec![]),
404            Some(names) if names.is_empty() => {}
405            Some(_) => panic!("cannot combine `implement_all` with selected implementations"),
406        }
407        self
408    }
409
410    /// Includes implementation traits for a WinRT interface or namespace prefix.
411    ///
412    /// The name may be a fully-qualified type name (`Namespace.Name`) or a namespace prefix that
413    /// matches every type defined under it.
414    #[track_caller]
415    pub fn implement(&mut self, name: &str) -> &mut Self {
416        assert!(
417            !self.implement.as_ref().is_some_and(Vec::is_empty),
418            "cannot combine selected implementations with `implement_all`"
419        );
420        self.implement
421            .get_or_insert_with(Vec::new)
422            .push(name.to_string());
423        self
424    }
425
426    /// Includes implementation traits for multiple WinRT interfaces or namespace prefixes.
427    pub fn implements<I, S>(&mut self, names: I) -> &mut Self
428    where
429        I: IntoIterator<Item = S>,
430        S: AsRef<str>,
431    {
432        for name in names {
433            self.implement(name.as_ref());
434        }
435        self
436    }
437
438    /// Selects a composable WinRT class as a minimal-mode composition target.
439    ///
440    /// The class and its composable factory methods must also be selected by a filter.
441    #[track_caller]
442    pub fn compose(&mut self, name: &str) -> &mut Self {
443        assert!(
444            name.rsplit_once('.')
445                .is_some_and(|(namespace, name)| !namespace.is_empty() && !name.is_empty()),
446            "`compose` requires a fully qualified class name"
447        );
448        self.compose.push(name.to_string());
449        self
450    }
451
452    /// Selects multiple composable WinRT classes as minimal-mode composition targets.
453    pub fn composes<I, S>(&mut self, names: I) -> &mut Self
454    where
455        I: IntoIterator<Item = S>,
456        S: AsRef<str>,
457    {
458        for name in names {
459            self.compose(name.as_ref());
460        }
461        self
462    }
463
464    /// Generate raw or sys-style Rust bindings.
465    ///
466    /// Mutually exclusive with [`Bindgen::minimal`]; panics if `minimal` was
467    /// already selected.
468    #[track_caller]
469    pub fn sys(&mut self) -> &mut Self {
470        let extern_fns = matches!(self.style, Style::Sys { extern_fns: true });
471        if matches!(self.style, Style::Minimal) {
472            panic!("cannot combine `--sys` and `--minimal`");
473        }
474        self.style = Style::Sys { extern_fns };
475        self
476    }
477
478    /// Generate minimal-mode Rust bindings.
479    ///
480    /// Drops per-class wrapper methods, inherited interface forwarders, handle
481    /// ergonomics, and free-function wrappers.
482    ///
483    /// Mutually exclusive with `--sys`.
484    #[track_caller]
485    pub fn minimal(&mut self) -> &mut Self {
486        if matches!(self.style, Style::Sys { .. }) {
487            panic!("cannot combine `--sys` and `--minimal`");
488        }
489        self.style = Style::Minimal;
490        self
491    }
492
493    /// Generate `extern` declarations rather than `link!` macros for sys-style Rust bindings.
494    ///
495    /// Only valid in combination with [`Bindgen::sys`]; panics otherwise.
496    #[track_caller]
497    pub fn extern_fns(&mut self) -> &mut Self {
498        match &mut self.style {
499            Style::Sys { extern_fns } => *extern_fns = true,
500            _ => panic!("`--extern` requires `--sys`"),
501        }
502        self
503    }
504
505    /// Emit `pub(crate)` instead of `pub` on generated items to surface unused
506    /// bindings as dead-code warnings.
507    pub fn dead_code(&mut self) -> &mut Self {
508        self.dead_code = true;
509        self
510    }
511
512    /// Generate the bindings.
513    #[track_caller]
514    pub fn write(&self) {
515        let total = std::time::Instant::now();
516
517        // Validate before setting up reader and reference state.
518        assert!(
519            !self.output.as_os_str().is_empty(),
520            "output is required (call `.output()` or pass `--out`)"
521        );
522        assert!(
523            self.compose.is_empty() || self.style.is_minimal(),
524            "`compose` requires `minimal`"
525        );
526        assert!(
527            self.package_feature_root.is_none() || self.layout.is_package(),
528            "`package_feature_root` requires `package`"
529        );
530
531        let mut include: Vec<&str> = vec![];
532        let mut exclude: Vec<&str> = vec![];
533
534        for f in &self.filter {
535            if let Some(rest) = f.strip_prefix('!') {
536                exclude.push(rest);
537            } else {
538                include.push(f.as_str());
539            }
540        }
541
542        assert!(!include.is_empty(), "at least one `--filter` required");
543
544        let sys = self.style.is_sys();
545        let link = if sys { "windows_link" } else { "windows_core" };
546
547        let phase = std::time::Instant::now();
548        let reader_storage;
549        let reader = if self.input.is_empty() {
550            default_reader()
551        } else {
552            reader_storage = Reader::new(expand_input(&self.input, self.input_default));
553            &reader_storage
554        };
555        report_timing(&self.output, "metadata", phase.elapsed());
556
557        let phase = std::time::Instant::now();
558        let mut references = self.external_references.clone();
559
560        if !sys {
561            // Register implicit references to sibling windows-* crates present in metadata.
562            for (probe_namespace, crate_name, paths) in [
563                (
564                    "Windows.Foundation",
565                    "windows_future",
566                    &[
567                        "Windows.Foundation.AsyncActionCompletedHandler",
568                        "Windows.Foundation.AsyncActionProgressHandler",
569                        "Windows.Foundation.AsyncActionWithProgressCompletedHandler",
570                        "Windows.Foundation.AsyncOperationCompletedHandler",
571                        "Windows.Foundation.AsyncOperationProgressHandler",
572                        "Windows.Foundation.AsyncOperationWithProgressCompletedHandler",
573                        "Windows.Foundation.AsyncStatus",
574                        "Windows.Foundation.IAsyncAction",
575                        "Windows.Foundation.IAsyncActionWithProgress",
576                        "Windows.Foundation.IAsyncInfo",
577                        "Windows.Foundation.IAsyncOperation",
578                        "Windows.Foundation.IAsyncOperationWithProgress",
579                    ][..],
580                ),
581                (
582                    "Windows.Foundation.Collections",
583                    "windows_collections",
584                    &[
585                        "Windows.Foundation.Collections.CollectionChange",
586                        "Windows.Foundation.Collections.IIterable",
587                        "Windows.Foundation.Collections.IIterator",
588                        "Windows.Foundation.Collections.IKeyValuePair",
589                        "Windows.Foundation.Collections.IMap",
590                        "Windows.Foundation.Collections.IMapChangedEventArgs",
591                        "Windows.Foundation.Collections.IMapView",
592                        "Windows.Foundation.Collections.IObservableMap",
593                        "Windows.Foundation.Collections.IObservableVector",
594                        "Windows.Foundation.Collections.IVector",
595                        "Windows.Foundation.Collections.IVectorChangedEventArgs",
596                        "Windows.Foundation.Collections.IVectorView",
597                        "Windows.Foundation.Collections.MapChangedEventHandler",
598                        "Windows.Foundation.Collections.VectorChangedEventHandler",
599                    ][..],
600                ),
601                (
602                    "Windows.Foundation",
603                    "windows_reference",
604                    &["Windows.Foundation.IReference"][..],
605                ),
606                (
607                    "Windows.Foundation",
608                    "windows_time",
609                    &["Windows.Foundation.DateTime", "Windows.Foundation.TimeSpan"][..],
610                ),
611                (
612                    "Windows.Foundation.Numerics",
613                    "windows_numerics",
614                    &[
615                        "Windows.Foundation.Numerics.Matrix3x2",
616                        "Windows.Foundation.Numerics.Matrix4x4",
617                        "Windows.Foundation.Numerics.Vector2",
618                        "Windows.Foundation.Numerics.Vector3",
619                        "Windows.Foundation.Numerics.Vector4",
620                    ][..],
621                ),
622            ] {
623                if reader.contains_key(probe_namespace) {
624                    let filtered: Vec<&str> = paths
625                        .iter()
626                        .copied()
627                        .filter(|path| {
628                            if let Some((namespace, name)) = path.rsplit_once('.')
629                                && let Some(ns_map) = reader.get(namespace)
630                            {
631                                return ns_map.contains_key(name);
632                            }
633                            false
634                        })
635                        .collect();
636                    if !filtered.is_empty() {
637                        prepend_default_refs(&mut references, crate_name, &filtered);
638                    }
639                }
640            }
641        }
642
643        let derive_str: Vec<&str> = self.derive.iter().map(|s| s.as_str()).collect();
644        let implements = self.implement.as_ref().map(|names| {
645            let names_str: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
646            Implements::new(&names_str)
647        });
648
649        let references = References::new(reader, references);
650        report_timing(&self.output, "references", phase.elapsed());
651
652        let phase = std::time::Instant::now();
653        let (filter, types) = {
654            let mut all_parsed = Vec::new();
655            for entry in &include {
656                all_parsed.extend(filter_parser::parse_filter_entry(entry));
657            }
658            for entry in &exclude {
659                let mut entries = filter_parser::parse_filter_entry(entry);
660                for e in &mut entries {
661                    e.exclude = true;
662                }
663                all_parsed.extend(entries);
664            }
665            let resolved = filter_parser::resolve_entries(reader, &all_parsed);
666
667            let mut filter = Filter::from_resolved(reader, &resolved);
668
669            // Precise filters use bottom-up closure; broad filters and packages scan top-down.
670            let types = if !filter.has_broad_filter && !self.layout.is_package() {
671                filter.uses_closure = true;
672                TypeClosure::build(reader, &mut filter, &references, implements.as_ref())
673            } else {
674                TypeMap::filter(reader, &filter, &references, self.style.is_sys())
675            };
676
677            (filter, types)
678        };
679        report_timing(&self.output, "selection", phase.elapsed());
680
681        let phase = std::time::Instant::now();
682        let derive = Derive::new(reader, &types, &derive_str);
683        if let Some(implements) = &implements {
684            filter.validate_implements(implements);
685        }
686
687        let event_only_delegates = compute_event_only_delegates(&types, reader);
688
689        let config = Config {
690            bindgen: self,
691            reader,
692            types: &types,
693            references: &references,
694            filter: &filter,
695            derive: &derive,
696            implement: implements.as_ref(),
697            link,
698            namespace: "",
699            event_only_delegates: &event_only_delegates,
700            self_ty: None,
701            self_generics: Vec::new(),
702            prunable: std::sync::Arc::new(BTreeSet::new()),
703        };
704        let filter_config = Config {
705            implement: None,
706            ..config.clone()
707        };
708
709        for target in &self.compose {
710            let class = composition_target(reader, target);
711            assert!(
712                types.contains_key(&class.type_name()),
713                "composition target `{target}` is not selected by the filter"
714            );
715            assert!(
716                class
717                    .required_interfaces(reader)
718                    .iter()
719                    .filter(|interface| interface.kind == InterfaceKind::Composable)
720                    .filter(|interface| types.contains_key(&interface.def.type_name()))
721                    .any(|interface| interface
722                        .get_methods(&filter_config)
723                        .iter()
724                        .any(|method| matches!(method, MethodOrName::Method(_)))),
725                "composition target `{target}` has no composable factory method selected by the \
726                 filter"
727            );
728        }
729
730        let tree = TypeTree::new(&types);
731        report_timing(&self.output, "planning", phase.elapsed());
732        config.write(tree);
733        report_timing(&self.output, "total", total.elapsed());
734    }
735}
736
737#[track_caller]
738fn composition_target(reader: &Reader, target: &str) -> Class {
739    let (namespace, name) = target.rsplit_once('.').unwrap();
740    let class = reader
741        .with_full_name(namespace, name)
742        .find_map(|ty| match ty {
743            Type::Class(class) => Some(class),
744            _ => None,
745        })
746        .unwrap_or_else(|| panic!("composition target `{target}` is not a WinRT class"));
747    assert!(
748        class
749            .required_interfaces(reader)
750            .iter()
751            .any(|interface| interface.kind == InterfaceKind::Composable),
752        "composition target `{target}` is not composable"
753    );
754    class
755}
756
757fn default_reader() -> &'static Reader {
758    static READER: std::sync::OnceLock<Reader> = std::sync::OnceLock::new();
759    READER.get_or_init(|| Reader::new(default_input()))
760}
761
762#[track_caller]
763fn default_input() -> Vec<File> {
764    [windows_default::WINRT, windows_default::WIN32]
765        .into_iter()
766        .map(|bytes| File::new(bytes.to_vec()).unwrap())
767        .collect()
768}
769
770fn expand_input(input: &[Input], input_default: bool) -> Vec<File> {
771    #[track_caller]
772    fn expand_path(result: &mut Vec<File>, path: &Path) {
773        if path.is_dir() {
774            let mut paths = vec![];
775
776            for path in path
777                .read_dir()
778                .unwrap_or_else(|_| panic!("failed to read directory `{}`", path.display()))
779                .flatten()
780                .map(|entry| entry.path())
781            {
782                if path.is_file()
783                    && path
784                        .extension()
785                        .is_some_and(|extension| extension.eq_ignore_ascii_case("winmd"))
786                {
787                    paths.push(path);
788                }
789            }
790
791            assert!(
792                !paths.is_empty(),
793                "failed to find .winmd files in directory `{}`",
794                path.display()
795            );
796
797            for path in paths {
798                let bytes = std::fs::read(&path)
799                    .unwrap_or_else(|_| panic!("failed to read binary file `{}`", path.display()));
800                let file = File::new(bytes)
801                    .unwrap_or_else(|| panic!("failed to read .winmd format `{}`", path.display()));
802                result.push(file);
803            }
804        } else {
805            let Ok(bytes) = std::fs::read(path) else {
806                panic!("failed to read binary file `{}`", path.display());
807            };
808            let Some(file) = File::new(bytes) else {
809                panic!("failed to read .winmd format `{}`", path.display());
810            };
811            result.push(file);
812        }
813    }
814
815    let mut result = if input_default {
816        default_input()
817    } else {
818        vec![]
819    };
820
821    for input in input {
822        match input {
823            Input::Path(path) => expand_path(&mut result, path),
824            Input::Bytes(bytes) => result.push(
825                File::new(bytes.clone())
826                    .unwrap_or_else(|| panic!("failed to read .winmd format from memory")),
827            ),
828        }
829    }
830
831    result
832}
833
834/// Finds delegates used only as event-handler parameters.
835fn compute_event_only_delegates(types: &TypeMap, reader: &Reader) -> HashSet<TypeName> {
836    let mut event_delegates: HashSet<TypeName> = HashSet::new();
837    let mut non_event_delegates: HashSet<TypeName> = HashSet::new();
838
839    for type_set in types.values() {
840        for ty in type_set {
841            let (methods, generics): (Box<dyn Iterator<Item = MethodDef>>, &[Type]) = match ty {
842                Type::Interface(i) => (Box::new(i.def.methods()), &i.generics),
843                _ => continue,
844            };
845
846            for method in methods {
847                let is_event_add = method.flags().contains(MethodAttributes::SpecialName)
848                    && method.name().starts_with("add_");
849
850                let sig = method.method_signature(generics, reader);
851                for param in &sig.params {
852                    if let Type::Delegate(d) = &param.ty {
853                        if is_event_add {
854                            event_delegates.insert(d.type_name());
855                        } else {
856                            non_event_delegates.insert(d.type_name());
857                        }
858                    }
859                }
860            }
861        }
862    }
863
864    event_delegates
865        .difference(&non_event_delegates)
866        .copied()
867        .collect()
868}
869
870fn namespace_starts_with(namespace: &str, starts_with: &str) -> bool {
871    namespace.starts_with(starts_with)
872        && (namespace.len() == starts_with.len()
873            || namespace.as_bytes().get(starts_with.len()) == Some(&b'.'))
874}
875
876/// Collapses private per-header Win32 package namespaces to the public umbrella.
877fn flat_module_namespace(namespace: &str) -> &str {
878    const UMBRELLA: &str = "Windows.Win32";
879    if namespace.len() > UMBRELLA.len()
880        && namespace.starts_with(UMBRELLA)
881        && namespace.as_bytes()[UMBRELLA.len()] == b'.'
882    {
883        return UMBRELLA;
884    }
885    namespace
886}
887
888/// Derives the cargo-feature name for a `--package` namespace.
889fn namespace_feature(namespace: &str) -> String {
890    if let Some(stem) = namespace.strip_prefix("Windows.Win32.") {
891        stem.replace('.', "_")
892    } else if let Some((_, rest)) = namespace.split_once('.') {
893        rest.replace('.', "_")
894    } else {
895        namespace.to_string()
896    }
897}
898
899#[track_caller]
900fn validate_external_reference_filter(filter: &str) {
901    let filter = filter.trim();
902    assert!(
903        !filter.is_empty(),
904        "external reference filter must not be empty"
905    );
906    assert!(
907        !filter.starts_with('!'),
908        "external reference filter must include metadata, not exclude it"
909    );
910
911    let entries = filter_parser::parse_filter_entry(filter);
912    assert!(
913        !entries.is_empty()
914            && entries.iter().all(|entry| entry
915                .segments
916                .iter()
917                .all(|segment| !segment.trim().is_empty())),
918        "external reference filter is malformed: `{filter}`"
919    );
920}
921
922#[track_caller]
923fn validate_rust_path_prefix(path: &str) {
924    let path = path.trim();
925    assert!(
926        !path.is_empty(),
927        "external reference Rust path prefix must not be empty"
928    );
929
930    let tokens = path
931        .parse::<proc_macro2::TokenStream>()
932        .unwrap_or_else(|_| panic!("invalid external reference Rust path prefix: `{path}`"));
933    let mut tokens = tokens.into_iter();
934
935    loop {
936        let Some(proc_macro2::TokenTree::Ident(ident)) = tokens.next() else {
937            panic!("invalid external reference Rust path prefix: `{path}`");
938        };
939        assert!(
940            ident != "_",
941            "invalid external reference Rust path prefix: `{path}`"
942        );
943
944        let Some(first_colon) = tokens.next() else {
945            break;
946        };
947        let Some(second_colon) = tokens.next() else {
948            panic!("invalid external reference Rust path prefix: `{path}`");
949        };
950        assert!(
951            matches!(first_colon, proc_macro2::TokenTree::Punct(ref punct) if punct.as_char() == ':')
952                && matches!(second_colon, proc_macro2::TokenTree::Punct(ref punct) if punct.as_char() == ':'),
953            "invalid external reference Rust path prefix: `{path}`"
954        );
955    }
956}
957
958/// Prepend reference entries so they take precedence.
959fn prepend_default_refs(refs: &mut Vec<ReferenceStage>, crate_name: &str, paths: &[&str]) {
960    refs.splice(
961        0..0,
962        paths
963            .iter()
964            .rev()
965            .map(|path| ReferenceStage::implicit(crate_name, path)),
966    );
967}
968
969#[cfg(test)]
970mod tests {
971    use super::*;
972
973    #[test]
974    fn test_starts_with() {
975        assert!(namespace_starts_with(
976            "Windows.Win32.Graphics.Direct3D11on12",
977            "Windows.Win32.Graphics.Direct3D11on12"
978        ));
979        assert!(namespace_starts_with(
980            "Windows.Win32.Graphics.Direct3D11on12",
981            "Windows.Win32.Graphics"
982        ));
983        assert!(!namespace_starts_with(
984            "Windows.Win32.Graphics.Direct3D11on12",
985            "Windows.Win32.Graphics.Direct3D11"
986        ));
987        assert!(!namespace_starts_with(
988            "Windows.Win32.Graphics.Direct3D",
989            "Windows.Win32.Graphics.Direct3D11"
990        ));
991    }
992
993    #[test]
994    fn default_metadata_reader_is_reused() {
995        assert!(std::ptr::eq(default_reader(), default_reader()));
996    }
997
998    #[test]
999    fn implementation_selection() {
1000        let mut builder = Bindgen::new();
1001        builder
1002            .implement("Test.IFirst")
1003            .implements(["Test.ISecond", "Other"]);
1004        assert_eq!(
1005            builder.implement,
1006            Some(vec![
1007                "Test.IFirst".to_string(),
1008                "Test.ISecond".to_string(),
1009                "Other".to_string()
1010            ])
1011        );
1012
1013        let mut builder = Bindgen::new();
1014        builder.implement_all().implement_all();
1015        assert_eq!(builder.implement, Some(vec![]));
1016
1017        let mut builder = Bindgen::new();
1018        builder.implements(std::iter::empty::<&str>());
1019        assert_eq!(builder.implement, None);
1020    }
1021
1022    #[test]
1023    fn composition_selection() {
1024        let mut builder = Bindgen::new();
1025        builder
1026            .compose("Test.First")
1027            .composes(["Test.Second", "Other.Third"]);
1028        assert_eq!(
1029            builder.compose,
1030            vec![
1031                "Test.First".to_string(),
1032                "Test.Second".to_string(),
1033                "Other.Third".to_string()
1034            ]
1035        );
1036    }
1037
1038    #[test]
1039    fn custom_package_feature_root_is_generic() {
1040        let mut builder = Bindgen::new();
1041        builder.package().package_feature_root("Company");
1042
1043        assert!(builder.is_package_feature_root("Company"));
1044        assert!(builder.package_feature_root_contains("Company.Network"));
1045        assert!(!builder.package_feature_root_contains("Other.Network"));
1046        assert_eq!(
1047            builder.package_feature("Company.Network.Socket"),
1048            "Network_Socket"
1049        );
1050    }
1051
1052    #[test]
1053    fn external_reference_builder_is_repeatable() {
1054        let mut builder = Bindgen::new();
1055        builder
1056            .external_reference("Vendor.Types", "vendor_bindings::types")
1057            .external_reference("Vendor.Values", "vendor_bindings::values");
1058
1059        assert_eq!(builder.external_references.len(), 2);
1060    }
1061
1062    #[test]
1063    #[should_panic(expected = "external reference filter must not be empty")]
1064    fn empty_external_reference_filter_panics() {
1065        Bindgen::new().external_reference("", "vendor_bindings");
1066    }
1067
1068    #[test]
1069    #[should_panic(expected = "invalid external reference Rust path prefix")]
1070    fn malformed_external_reference_path_panics() {
1071        Bindgen::new().external_reference("Vendor.Types", "vendor-bindings::types");
1072    }
1073
1074    #[test]
1075    #[should_panic(expected = "package feature root must be a top-level namespace")]
1076    fn nested_package_feature_root_panics() {
1077        Bindgen::new().package_feature_root("Company.Native");
1078    }
1079
1080    #[test]
1081    #[should_panic(expected = "cannot combine selected implementations with `implement_all`")]
1082    fn implementation_after_all_panics() {
1083        Bindgen::new().implement_all().implement("Test.IFirst");
1084    }
1085
1086    #[test]
1087    #[should_panic(expected = "cannot combine `implement_all` with selected implementations")]
1088    fn implementation_all_after_selection_panics() {
1089        Bindgen::new().implement("Test.IFirst").implement_all();
1090    }
1091}