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