Skip to main content

windows_bindgen/
lib.rs

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
61/// Creates a new [`Bindgen`] builder for generating Windows API bindings.
62pub fn builder() -> Bindgen {
63    Bindgen::new()
64}
65
66/// Builder for generating Windows API bindings.
67///
68/// This is the fluent alternative to [`bindgen`].
69///
70/// # Example
71///
72/// ```rust,no_run
73/// windows_bindgen::Bindgen::new()
74///     .output("src/bindings.rs")
75///     .filter("GetTickCount")
76///     .write();
77/// ```
78#[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/// Output layout for the generated bindings.
100#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
101enum Layout {
102    /// A single flat list of items (the default).
103    #[default]
104    Flat,
105    /// One Rust module per metadata namespace.
106    Modules,
107    /// One file per namespace + `Cargo.toml` features.
108    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/// Code-style mode for the generated bindings.
121#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
122enum Style {
123    /// Minimal bindings (no class wrappers, inherited forwarders, or handle ergonomics;
124    /// auto-revoke events).
125    #[default]
126    Minimal,
127    /// Full-fidelity bindings.
128    Full,
129    /// Raw / sys-style bindings.
130    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    /// Minimal bindings use the class's default interface directly.
141    fn emit_class_methods(self) -> bool {
142        !self.is_minimal()
143    }
144
145    /// Minimal bindings require casting to the interface that owns an inherited method.
146    fn emit_inherited_forwarders(self) -> bool {
147        !self.is_minimal()
148    }
149
150    /// Minimal bindings require casting inherited iterables to `IIterable<T>`.
151    fn emit_iterable_into_iterator(self) -> bool {
152        !self.is_minimal()
153    }
154
155    /// Minimal bindings expose input strings as `&str`.
156    fn minimal_string_input(self, param: &Param) -> bool {
157        self.is_minimal() && param.is_input_only() && matches!(param.ty, Type::String)
158    }
159
160    /// Minimal bindings return strings as `String`.
161    fn minimal_string_return(self, ty: &Type) -> bool {
162        self.is_minimal() && matches!(ty, Type::String)
163    }
164
165    /// Sys bindings omit standard derives beyond `Copy` and `Clone`.
166    fn derive_std_traits(self) -> bool {
167        !self.is_sys()
168    }
169
170    /// Sys bindings omit traits that require `windows-core`.
171    fn emit_core_traits(self) -> bool {
172        !self.is_sys()
173    }
174
175    /// Whether handle structs are emitted as bare aliases rather than newtypes.
176    fn emit_bare_typedef(self) -> bool {
177        self.is_sys() || self.is_minimal()
178    }
179}
180
181impl Bindgen {
182    /// Creates a new builder with default options.
183    pub fn new() -> Self {
184        Self::default()
185    }
186
187    /// Adds a `.winmd` file or directory.
188    ///
189    /// Explicit inputs replace the bundled metadata. Call [`Bindgen::input_default`] to include
190    /// the bundled metadata alongside them.
191    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    /// Adds the default Windows metadata.
197    ///
198    /// Included automatically when no explicit inputs are supplied.
199    pub fn input_default(&mut self) -> &mut Self {
200        self.input_default = true;
201        self
202    }
203
204    /// Adds a `.winmd` file from memory.
205    ///
206    /// Uses the same default metadata behavior as [`Bindgen::input`].
207    pub fn input_bytes(&mut self, input: &[u8]) -> &mut Self {
208        self.input.push(Input::Bytes(input.to_vec()));
209        self
210    }
211
212    /// Adds `.winmd` files from memory.
213    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    /// Adds `.winmd` files or directories.
225    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    /// Sets the generated Rust file.
237    ///
238    /// Defaults to `bindings.rs` in the runtime `OUT_DIR` directory. An explicit path is required
239    /// when `OUT_DIR` is unset or empty, and always when generating a package.
240    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    /// Adds a filter rule to include or exclude APIs.
246    ///
247    /// See the [crate documentation](crate) for an example table. The same syntax applies to
248    /// [`Bindgen::filters`], [`Bindgen::filter_file`], and [`bindgen`]'s `--filter` arguments.
249    ///
250    /// # Names and groups
251    ///
252    /// Select a function, constant, type, or namespace. Bare names match across namespaces;
253    /// qualify a name to restrict it to one namespace. Dots and `::` both separate path segments.
254    /// Namespace selections include descendant namespaces. The bundled Win32 metadata uses
255    /// `Windows.Win32`, not the subsystem namespaces used by the umbrella crates' Cargo features.
256    ///
257    /// Groups abbreviate separate selections and may nest: `Windows::Foundation::{Uri, AsyncStatus}`.
258    /// Trailing commas are allowed. `*` wildcards are not supported.
259    ///
260    /// # Members and dependencies
261    ///
262    /// A bare type selects all its members. Use `Type::Member` or `Type::{Member, OtherMember}`
263    /// for a subset. Members may be methods, properties, events, or enum variants.
264    /// Use native member or overload names, not renamed Rust methods. Property and event names
265    /// select their accessor pairs; requesting an event's `add_` method also selects its `remove_`
266    /// method. `Class::CreateInstance` selects a WinRT class's default constructor.
267    ///
268    /// Signature dependencies are included automatically, but interfaces reached only through
269    /// signatures can be name-only declarations. Select their methods explicitly to call them.
270    /// `Type::{}` requests the type without requesting its methods or enum variants; it does not
271    /// remove methods selected elsewhere. In minimal mode, a COM interface selected this way can
272    /// use [`Bindgen::implement`] to emit its implementation trait and vtable without caller wrappers.
273    ///
274    /// # Combining rules
275    ///
276    /// Prefix a selection with `!` to exclude it. More specific type/namespace rules take precedence;
277    /// exclusions win ties regardless of argument order. Member and enum-variant selections narrow
278    /// whole-type selections, also regardless of order. Excluded members and variants win over
279    /// included ones, except that implementation traits require the interface's complete method ABI.
280    /// Named [`Bindgen::implement`] selectors reject method-level inclusions or exclusions on matching
281    /// interfaces. Select the whole interface or use `Interface::{}` instead.
282    /// [`Bindgen::implement_all`] allows member filters, but emits the complete method ABI for
283    /// implemented interfaces.
284    ///
285    /// Chained members (`Type::Read::Write`), trailing separators (`Type::`), and empty entries
286    /// inside a group (`Type::{Read,,Write}`) are rejected. Use `Type::{Read, Write}` for several
287    /// members or `Type::{}` for a name-only selection.
288    pub fn filter(&mut self, filter: &str) -> &mut Self {
289        self.filters(std::iter::once(filter))
290    }
291
292    /// Adds filter rules from a text file.
293    ///
294    /// Uses [`Bindgen::filter`] syntax, with whitespace separating filters outside groups.
295    /// Groups may span lines. Lines beginning with `//` after optional whitespace are comments;
296    /// inline comments require a separate `//` token followed by whitespace or the end of the line.
297    #[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    /// Adds filter rules from text files.
303    #[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    /// Add multiple filter rules to include or exclude APIs.
316    ///
317    /// Uses the same syntax as [`Bindgen::filter`].
318    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    /// Specifies extra derives as `Type=Trait,OtherTrait`, for example `SYSTEMTIME=Debug`.
330    ///
331    /// The type may be a bare or dotted qualified name and must be included in the generated
332    /// bindings. Later entries for the same type replace earlier lists.
333    pub fn derive(&mut self, derive: &str) -> &mut Self {
334        self.derives(std::iter::once(derive))
335    }
336
337    /// Specifies extra derives for multiple types, using the syntax of [`Bindgen::derive`].
338    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    /// Set comma-separated `rustfmt` configuration options, such as `max_width=120`.
350    ///
351    /// These are passed to `rustfmt --config`, not used as an executable path.
352    /// The default is `newline_style=Unix`; supplied options override matching defaults.
353    /// Formatting is best effort: failures leave the output unformatted without a warning.
354    pub fn rustfmt(&mut self, rustfmt: &str) -> &mut Self {
355        self.rustfmt = Some(rustfmt.to_string());
356        self
357    }
358
359    /// Nest items in one Rust module per metadata namespace instead of a single flat list.
360    ///
361    /// Use this when the selected APIs define the same name in more than one namespace.
362    #[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    /// Generate bindings as a package with one file per namespace.
376    #[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    /// Includes implementation traits for every native and WinRT interface in scope.
386    ///
387    /// Unlike [`Bindgen::implement`], allows method-level filters. Implemented interfaces still
388    /// emit their complete method ABI.
389    #[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    /// Includes implementation traits for a native or WinRT interface or namespace prefix.
400    ///
401    /// Use a dotted qualified name (`Windows.Win32.ISequentialStream`) or a namespace prefix.
402    /// Unlike filters, bare interface names are not resolved. The interface must be included in
403    /// the generated bindings, directly or as a dependency; this does not select it.
404    /// Required base interface implementations are included unless excluded or supplied by a
405    /// referenced crate.
406    ///
407    /// Method-level inclusions or exclusions on matching interfaces or their required bases cause
408    /// [`Bindgen::write`] to panic. Select the whole interface or use `Interface::{}` instead.
409    #[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    /// Includes implementation traits for multiple native or WinRT interfaces or namespace prefixes.
422    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    /// Selects a composable WinRT class as a composition target.
434    ///
435    /// The class and its composable factory methods must also be selected by a filter.
436    #[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    /// Selects multiple composable WinRT classes as composition targets.
448    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    /// Generate raw or sys-style Rust bindings using `windows-link`.
460    ///
461    /// Mutually exclusive with [`Bindgen::full`].
462    #[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    /// Generate full-fidelity Rust bindings.
473    ///
474    /// Adds per-class wrapper methods, inherited interface forwarders, handle ergonomics,
475    /// free-function wrappers, and implementation traits for interfaces not marked `ExclusiveTo`.
476    /// Use [`Bindgen::implement`] or [`Bindgen::implement_all`] for `ExclusiveTo` interfaces; an
477    /// explicit selection replaces the full-mode default.
478    ///
479    /// Mutually exclusive with [`Bindgen::sys`].
480    #[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    /// Generate `extern` declarations rather than `link!` macros in any binding style.
488    ///
489    /// DLL and entry-point selection are left to the caller's import libraries, including ordinals.
490    pub fn extern_fns(&mut self) -> &mut Self {
491        self.extern_fns = true;
492        self
493    }
494
495    /// Use `pub(crate)` where possible to surface unused bindings as dead-code warnings.
496    ///
497    /// Interface and vtable types remain public for trait implementations.
498    pub fn dead_code(&mut self) -> &mut Self {
499        self.dead_code = true;
500        self
501    }
502
503    /// Generate the bindings.
504    ///
505    /// Without an explicit output, writes `OUT_DIR/bindings.rs`. Use distinct explicit paths for
506    /// multiple output files. Does not emit Cargo dependency-tracking directives.
507    ///
508    /// Resolves declarations on demand, including dependencies of selected APIs. Errors in unused
509    /// declarations may not be reported.
510    ///
511    /// Panics if input processing, code generation, or writing the output fails.
512    #[track_caller]
513    pub fn write(&self) {
514        // Validate before setting up reader and reference state.
515        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            // Register implicit references to sibling windows-* crates present in metadata.
575            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
842/// Finds delegates used only as event-handler parameters.
843fn 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) = &param.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
887/// Derives the cargo-feature name for a `--package` namespace.
888fn 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
896/// Prepend reference entries so they take precedence.
897fn 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}