Skip to main content

windows_clang/
lib.rs

1#![allow(non_upper_case_globals)]
2#![doc = include_str!("../../../README.md")]
3
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::path::{Path, PathBuf};
6use windows_metadata as metadata;
7
8use proc_macro2::{Literal, Span, TokenStream};
9use quote::quote;
10
11use windows_rdl::emit::{uuid_to_u128_literal, write_ident, write_typed_value};
12use windows_rdl::{Error, expand_input_files, formatter, implib, write_to_file};
13
14mod cx;
15use cx::*;
16mod canon;
17use canon::*;
18mod r#enum;
19use r#enum::*;
20mod item;
21use item::*;
22mod r#struct;
23use r#struct::*;
24mod collector;
25use collector::*;
26use field::*;
27mod annotation;
28mod field;
29use annotation::*;
30mod typedef;
31use typedef::*;
32mod callback;
33use callback::*;
34mod r#fn;
35use r#fn::*;
36mod r#const;
37use r#const::*;
38mod interface;
39use interface::*;
40mod provision;
41pub use provision::*;
42mod remap;
43pub use remap::*;
44mod scrape;
45pub use scrape::*;
46mod guid;
47use guid::*;
48mod scope;
49use scope::*;
50mod naming;
51use naming::*;
52mod macros;
53use macros::*;
54
55fn write_type(namespace: &str, ty: &metadata::Type) -> TokenStream {
56    windows_rdl::emit::write_type(namespace, &normalize_rdl_type(ty))
57}
58
59/// Creates a libclang-backed RDL generator.
60pub fn clang() -> Clang {
61    Clang::new()
62}
63
64/// Returns the loaded libclang version string.
65pub fn clang_version() -> Result<String, Error> {
66    Clang::version()
67}
68
69/// Parse context shared across the AST walk; pending vectors are drained after the walk.
70pub(crate) struct Parser<'a> {
71    pub namespace: &'a str,
72    /// `Some(root)` enables per-header mode: references route through defining headers.
73    pub header_root: Option<&'a str>,
74    pub library: &'a str,
75    /// Per-symbol DLL overrides recovered from the SDK import libraries.
76    pub libraries: &'a HashMap<String, String>,
77    pub ref_map: &'a HashMap<String, String>,
78    /// Per-header mode: resolves token-only const casts whose type has no cursor.
79    pub header_names: Option<&'a HashMap<String, String>>,
80    pub tag_rename: &'a HashMap<String, String>,
81    /// Enum reprs taken from integer typedefs in the C flags/enum idiom.
82    pub enum_merge: &'a HashMap<String, &'static str>,
83    pub tu: &'a TranslationUnit,
84    pub pending_typedefs: Vec<Cursor>,
85    pub pending_records: Vec<Cursor>,
86    pub pending_macros: Vec<String>,
87    processing_dependency: bool,
88    /// Per-header mode: incomplete pointer-only records emitted as opaque structs.
89    pub pending_opaque: Vec<(String, String)>,
90    /// Enum names for which `DEFINE_ENUM_FLAG_OPERATORS(X)` was seen.
91    pub flag_enums: HashSet<String>,
92    /// IID variables: interface name -> UUID, from `IID_XXX` GUID declarations.
93    pub iid_vars: HashMap<String, String>,
94    /// Object-like macro replacement tokens for resolving calling conventions.
95    pub macro_defs: &'a HashMap<String, Vec<String>>,
96    /// Leading-underscore macros explicitly selected by the caller.
97    pub include_macros: &'a HashSet<String>,
98    /// Function symbols explicitly excluded by the caller.
99    pub exclude_symbols: &'a HashSet<String>,
100    /// Types whose native size/alignment combination cannot be represented.
101    pub unsupported_types: &'a HashSet<String>,
102    /// Expanded export name -> source spelling for object-like function aliases.
103    /// Charset-selection aliases are excluded because they choose an `A`/`W` variant.
104    pub alias_map: HashMap<String, String>,
105    /// Non-empty means only listed functions are roots; dependencies still flow in later.
106    pub symbols: &'a HashSet<String>,
107    /// Drops functions with no resolved import library; off for fixtures without `.lib` inputs.
108    pub drop_lib_less: bool,
109    /// Resolution-winmd names that keep true WinRT ABI types out of the flat root.
110    pub winrt_types: Option<&'a HashSet<String>>,
111}
112
113/// Per-namespace inputs for one emission pass over cached translation units.
114struct NamespaceSpec<'a> {
115    namespace: &'a str,
116    library: &'a str,
117    libraries: &'a HashMap<String, String>,
118    filter: &'a [String],
119    symbols: &'a HashSet<String>,
120    include_macros: &'a HashSet<String>,
121    exclude_symbols: &'a HashSet<String>,
122}
123
124impl<'a> Parser<'a> {
125    #[expect(clippy::too_many_arguments)]
126    fn new(
127        namespace: &'a str,
128        library: &'a str,
129        libraries: &'a HashMap<String, String>,
130        ref_map: &'a HashMap<String, String>,
131        tag_rename: &'a HashMap<String, String>,
132        enum_merge: &'a HashMap<String, &'static str>,
133        macro_defs: &'a HashMap<String, Vec<String>>,
134        tu: &'a TranslationUnit,
135        symbols: &'a HashSet<String>,
136        include_macros: &'a HashSet<String>,
137        exclude_symbols: &'a HashSet<String>,
138        unsupported_types: &'a HashSet<String>,
139    ) -> Self {
140        Self {
141            namespace,
142            header_root: None,
143            library,
144            libraries,
145            ref_map,
146            header_names: None,
147            tag_rename,
148            enum_merge,
149            tu,
150            pending_typedefs: vec![],
151            pending_records: vec![],
152            pending_macros: vec![],
153            processing_dependency: false,
154            pending_opaque: vec![],
155            flag_enums: HashSet::new(),
156            iid_vars: HashMap::new(),
157            alias_map: build_alias_map(macro_defs),
158            macro_defs,
159            include_macros,
160            exclude_symbols,
161            unsupported_types,
162            symbols,
163            drop_lib_less: false,
164            winrt_types: None,
165        }
166    }
167
168    /// Applies the lib-less drop policy before inserting a function.
169    fn insert_fn(&self, item: Fn, collector: &mut Collector) {
170        if self.drop_lib_less && item.library.is_empty() {
171            return;
172        }
173        collector.insert(Item::Fn(item));
174    }
175
176    /// Processes one cursor, inserting items or queuing macros for the second pass.
177    fn process_cursor(
178        &mut self,
179        child: Cursor,
180        collector: &mut Collector,
181        extern_c: bool,
182    ) -> Result<(), Error> {
183        // Allowlist mode emits only named functions as roots. Queued dependencies bypass it.
184        if !self.processing_dependency && !self.symbols.is_empty() {
185            match child.kind() {
186                CXCursor_FunctionDecl
187                    if !child.is_definition()
188                        && self.symbols.contains(&child.name())
189                        && !is_midl_proxy_stub(&child, self.libraries)
190                        && !self.exclude_symbols.contains(&child.name())
191                        && !function_references_unsupported(
192                            &child,
193                            self.unsupported_types,
194                            self.tag_rename,
195                        ) =>
196                {
197                    let item = Fn::parse(child, self, extern_c)?;
198                    self.insert_fn(item, collector);
199                }
200                CXCursor_LinkageSpec => {
201                    for inner in child.children() {
202                        let inner_extern_c = inner.language() == CXLanguage_C;
203                        self.process_cursor(inner, collector, inner_extern_c)?;
204                    }
205                }
206                _ => {}
207            }
208            return Ok(());
209        }
210        match child.kind() {
211            CXCursor_StructDecl if child.is_definition() => {
212                let tag_name = child.name();
213                let name = if is_anonymous_name(&tag_name) {
214                    self.tag_rename
215                        .get(&child.location_id())
216                        .cloned()
217                        .unwrap_or(tag_name)
218                } else {
219                    self.tag_rename.get(&tag_name).cloned().unwrap_or(tag_name)
220                };
221                // Scalar records collapse to primitives; skip before lifting nested records.
222                if semantic_scalar_definition(&name, child.kind()).is_some() {
223                    return Ok(());
224                }
225                // Numerics aliases collapse to shared value types; skip before lifting overlays.
226                if numerics_alias(&name).is_some() {
227                    return Ok(());
228                }
229                // Lift nested records first so field type references resolve.
230                self.process_nested_types(child, collector, extern_c)?;
231                if self.unsupported_types.contains(&name) {
232                    return Ok(());
233                }
234                // Inline anonymous records are emitted by their enclosing record.
235                if child.is_anonymous_record() || is_named_instance_record(&child) {
236                    return Ok(());
237                }
238                // No synthetic name means nothing can reference this anonymous type.
239                if is_anonymous_name(&name) {
240                    // nothing to emit
241                } else if child.has_pure_virtual_methods()
242                    || child.extract_uuid(self.tu).is_some()
243                    || (child.has_interface_base() && !child.has_data_fields())
244                {
245                    if !self.ref_map.contains_key(&name) {
246                        collector.insert(Item::Interface(Interface::parse(child, self)?));
247                    }
248                } else if !self.ref_map.contains_key(&name) {
249                    collector.insert(Item::Struct(Struct::parse(child, self, false)?));
250                }
251            }
252            // Pointer-only incomplete records need opaque structs; handle tags stay `*mut void`.
253            CXCursor_StructDecl | CXCursor_UnionDecl
254                if !child.is_definition() && !child.has_definition() =>
255            {
256                let tag_name = child.name();
257                if !is_anonymous_name(&tag_name) && !tag_name.ends_with("__") {
258                    let name = self.tag_rename.get(&tag_name).cloned().unwrap_or(tag_name);
259                    if semantic_scalar_definition(&name, child.kind()).is_some() {
260                        return Ok(());
261                    }
262                    // Do not clobber a real definition aliased by another tag.
263                    if !self.ref_map.contains_key(&name) && !collector.contains_key(&name) {
264                        collector.insert(Item::Struct(Struct::opaque(&name)));
265                    }
266                }
267            }
268            CXCursor_UnionDecl if child.is_definition() => {
269                let tag_name = child.name();
270                let name = if is_anonymous_name(&tag_name) {
271                    self.tag_rename
272                        .get(&child.location_id())
273                        .cloned()
274                        .unwrap_or(tag_name)
275                } else {
276                    self.tag_rename.get(&tag_name).cloned().unwrap_or(tag_name)
277                };
278                // Scalar overlay unions collapse to scalars; skip before lifting overlays.
279                if semantic_scalar_definition(&name, child.kind()).is_some() {
280                    return Ok(());
281                }
282                // Lift nested records first so field type references resolve.
283                self.process_nested_types(child, collector, extern_c)?;
284                if self.unsupported_types.contains(&name) {
285                    return Ok(());
286                }
287                if child.is_anonymous_record() || is_named_instance_record(&child) {
288                    return Ok(());
289                }
290                if !is_anonymous_name(&name) && !self.ref_map.contains_key(&name) {
291                    collector.insert(Item::Struct(Struct::parse(child, self, true)?));
292                }
293            }
294            CXCursor_ClassDecl
295                if child.is_definition()
296                    && (child.has_pure_virtual_methods()
297                        || child.extract_uuid(self.tu).is_some()
298                        || (child.has_interface_base() && !child.has_data_fields())) =>
299            {
300                let tag_name = child.name();
301                let name = self.tag_rename.get(&tag_name).cloned().unwrap_or(tag_name);
302                self.process_nested_types(child, collector, extern_c)?;
303                if self.unsupported_types.contains(&name) {
304                    return Ok(());
305                }
306                if !self.ref_map.contains_key(&name) {
307                    collector.insert(Item::Interface(Interface::parse(child, self)?));
308                }
309            }
310            // Forward-declared `uuid` classes are COM server CLSIDs, not interface types.
311            CXCursor_ClassDecl if !child.is_definition() && !child.has_definition() => {
312                if let Some(uuid) = child.extract_uuid(self.tu) {
313                    let tag_name = child.name();
314                    let name = self.tag_rename.get(&tag_name).cloned().unwrap_or(tag_name);
315                    if !name.is_empty() && !self.ref_map.contains_key(&name) {
316                        collector.insert(Item::GuidConst(GuidConst { name, uuid }));
317                    }
318                }
319            }
320            CXCursor_EnumDecl if child.is_definition() => {
321                let mut e = Enum::parse(child)?;
322                let tag = e.name.clone();
323                // Emit the public typedef alias, matching how references resolve the enum.
324                if !is_anonymous_name(&e.name)
325                    && let Some(alias) = self.tag_rename.get(&e.name)
326                {
327                    e.name.clone_from(alias);
328                }
329                if is_anonymous_name(&e.name) || is_midl_anonymous_enum_name(&e.name) {
330                    // Nameless and MIDL-synthesized enums emit as loose constants.
331                    for (name, value) in e.variants {
332                        let const_value = enum_variant_value(e.repr, value);
333                        collector.insert(Item::Const(Const {
334                            name,
335                            ty: None,
336                            value: const_value,
337                        }));
338                    }
339                } else if !self.ref_map.contains_key(&e.name) {
340                    // The flag macro may have used the internal tag before the rename.
341                    if self.flag_enums.contains(&e.name) || self.flag_enums.contains(&tag) {
342                        e.flags = true;
343                    }
344                    // The flags/enum idiom gets its storage type from the integer typedef.
345                    if let Some(&repr) = self.enum_merge.get(&e.name) {
346                        e.repr = repr;
347                    }
348                    collector.insert(Item::Enum(e));
349                }
350            }
351            CXCursor_TypedefDecl if child.is_definition() => {
352                let name = child.name();
353                if !self.ref_map.contains_key(&name) && !self.unsupported_types.contains(&name) {
354                    if let Some(cb) = Callback::parse(child, self)? {
355                        collector.insert(Item::Callback(cb));
356                    } else if let Some(td) = Typedef::parse(child, self)? {
357                        collector.insert(Item::Typedef(td));
358                    }
359                }
360            }
361            // Skip MIDL marshaling thunks: RPC internals, not public API.
362            CXCursor_FunctionDecl
363                if !child.is_definition()
364                    && !is_midl_proxy_stub(&child, self.libraries)
365                    && !is_midl_user_marshal_stub(&child)
366                    && !self.exclude_symbols.contains(&child.name())
367                    && !function_references_unsupported(
368                        &child,
369                        self.unsupported_types,
370                        self.tag_rename,
371                    ) =>
372            {
373                let item = Fn::parse(child, self, extern_c)?;
374                self.insert_fn(item, collector);
375            }
376            // Linkage blocks may nest; recurse with the per-child language.
377            CXCursor_LinkageSpec => {
378                for inner in child.children() {
379                    let inner_extern_c = inner.language() == CXLanguage_C;
380                    self.process_cursor(inner, collector, inner_extern_c)?;
381                }
382            }
383            CXCursor_MacroDefinition => {
384                if let Some(c) = Const::parse(child, self)? {
385                    collector.insert(Item::Const(c));
386                } else if !child.is_macro_builtin()
387                    && !child.is_macro_function_like()
388                    && !child.name().is_empty()
389                    && (!child.name().starts_with('_')
390                        || self.include_macros.contains(&child.name()))
391                {
392                    // Non-type keywords and string literals are not integer constants.
393                    let tokens = self.tu.tokenize(child.extent());
394                    let body_has_non_type_keyword = tokens
395                        .iter()
396                        .skip(1) // first token is the macro name
397                        .any(|(kind, spelling)| {
398                            *kind == CXToken_Keyword && !is_type_keyword(spelling)
399                        });
400                    let body_has_string_literal = tokens.iter().skip(1).any(|(kind, spelling)| {
401                        *kind == CXToken_Literal
402                            && (spelling.starts_with('"') || spelling.starts_with("L\""))
403                    });
404                    // Metadata has no 128-bit integer value, and clang would truncate it.
405                    let body_has_int128_literal = tokens.iter().skip(1).any(|(kind, spelling)| {
406                        *kind == CXToken_Literal && spelling.to_ascii_lowercase().ends_with("i128")
407                    });
408                    // Unbalanced replacement lists can swallow later synthetic enum entries.
409                    let body_is_balanced = tokens_balanced(tokens.iter().skip(1));
410                    if !body_has_non_type_keyword
411                        && !body_has_string_literal
412                        && !body_has_int128_literal
413                        && body_is_balanced
414                    {
415                        // Defer object-like macro constants to the batch evaluator.
416                        self.pending_macros.push(child.name());
417                    }
418                }
419            }
420            // `DEFINE_ENUM_FLAG_OPERATORS` marks an enum as `#[flags]`.
421            CXCursor_MacroExpansion if child.name() == "DEFINE_ENUM_FLAG_OPERATORS" => {
422                // Tokenize the invocation to extract the enum name argument.
423                let tokens = self.tu.tokenize(child.extent());
424                if let [
425                    _,
426                    (CXToken_Punctuation, lp),
427                    (CXToken_Identifier, enum_name),
428                    ..,
429                ] = tokens.as_slice()
430                    && lp == "("
431                {
432                    let enum_name = enum_name.clone();
433                    // The macro may key on the internal tag; resolve to the emitted name.
434                    let enum_name = self
435                        .tag_rename
436                        .get(&enum_name)
437                        .cloned()
438                        .unwrap_or(enum_name);
439                    // Mark now if the enum was already inserted.
440                    collector.mark_flags(&enum_name);
441                    // Also record for enum definitions seen later.
442                    self.flag_enums.insert(enum_name);
443                }
444            }
445            // GUID macro values live in the arguments unless `INITGUID` is defined.
446            CXCursor_MacroExpansion
447                if matches!(
448                    child.name().as_str(),
449                    "DEFINE_GUID" | "DEFINE_OLEGUID" | "DEFINE_KNOWN_FOLDER"
450                ) =>
451            {
452                let ole = child.name() == "DEFINE_OLEGUID";
453                let tokens = self.tu.tokenize(child.extent());
454                if let Some((name, uuid)) = parse_define_guid_tokens(&tokens, ole)
455                    && !name.is_empty()
456                {
457                    // `IID_<Interface>` fills UUIDs missing from the C++ declaration.
458                    if let Some(iface_name) = name.strip_prefix("IID_") {
459                        self.iid_vars
460                            .entry(iface_name.to_string())
461                            .or_insert_with(|| uuid.clone());
462                    }
463                    if !self.ref_map.contains_key(&name) {
464                        collector.insert(Item::GuidConst(GuidConst { name, uuid }));
465                    }
466                }
467            }
468            // Property key macro arguments carry the GUID plus PID value.
469            CXCursor_MacroExpansion
470                if matches!(
471                    child.name().as_str(),
472                    "DEFINE_PROPERTYKEY" | "DEFINE_DEVPROPKEY"
473                ) =>
474            {
475                let ty = if child.name() == "DEFINE_DEVPROPKEY" {
476                    "DEVPROPKEY"
477                } else {
478                    "PROPERTYKEY"
479                };
480                let tokens = self.tu.tokenize(child.extent());
481                if let Some((name, uuid, pid)) = parse_define_property_key_tokens(&tokens)
482                    && !name.is_empty()
483                    && !self.ref_map.contains_key(&name)
484                    && !collector.contains_key(&name)
485                {
486                    collector.insert(Item::PropertyKeyConst(PropertyKeyConst {
487                        name,
488                        ty: ty.to_string(),
489                        uuid,
490                        pid,
491                    }));
492                }
493            }
494            // `IID_XXX` variables can provide UUIDs missing from interface declarations.
495            CXCursor_VarDecl => {
496                let name = child.name();
497                if let Some(iface_name) = name.strip_prefix("IID_")
498                    && is_guid_type(&child.ty())
499                {
500                    if let Some(uuid) = parse_guid_initializer_ast(&child) {
501                        self.iid_vars.insert(iface_name.to_string(), uuid);
502                    } else {
503                        // Fallback when clang exposes no init-list children.
504                        let tokens = self.tu.tokenize(self.tu.to_expansion_range(child.extent()));
505                        if let Some(uuid) = parse_guid_initializer_tokens(&tokens) {
506                            self.iid_vars.insert(iface_name.to_string(), uuid);
507                        }
508                    }
509                } else if let Some(c) = Const::parse_var_decl(&child)
510                    && !self.ref_map.contains_key(&c.name)
511                    && !collector.contains_key(&c.name)
512                {
513                    collector.insert(Item::Const(c));
514                }
515            }
516            _ => {}
517        }
518        Ok(())
519    }
520
521    /// Lifts nested records before their parent so field type references resolve.
522    fn process_nested_types(
523        &mut self,
524        parent: Cursor,
525        collector: &mut Collector,
526        extern_c: bool,
527    ) -> Result<(), Error> {
528        for nested in parent.children() {
529            if (nested.kind() == CXCursor_StructDecl || nested.kind() == CXCursor_UnionDecl)
530                && nested.is_definition()
531            {
532                self.process_cursor(nested, collector, extern_c)?;
533            } else if nested.kind() == CXCursor_EnumDecl && nested.is_definition() {
534                // Nested anonymous enum members leak into the enclosing C scope.
535                let e = Enum::parse(nested)?;
536                if is_anonymous_name(&e.name) || is_midl_anonymous_enum_name(&e.name) {
537                    for (name, value) in e.variants {
538                        let const_value = enum_variant_value(e.repr, value);
539                        collector.insert(Item::Const(Const {
540                            name,
541                            ty: None,
542                            value: const_value,
543                        }));
544                    }
545                }
546            }
547        }
548        Ok(())
549    }
550}
551
552#[derive(Default, Clone)]
553/// Builder that generates RDL from C/C++ headers using libclang.
554pub struct Clang {
555    input: Vec<PathBuf>,
556    input_text: Vec<String>,
557    reference: Vec<PathBuf>,
558    output: PathBuf,
559    namespace: String,
560    args: Vec<String>,
561    library: String,
562    /// Per-symbol DLL overrides recovered from SDK import libraries.
563    libraries: HashMap<String, String>,
564    /// Per-defining-header library overrides used by flat per-header output.
565    header_libraries: HashMap<String, String>,
566    filter: Vec<String>,
567    target: Option<String>,
568    /// Header directory segments treated as roots for the reachability sweep.
569    scope: Vec<String>,
570    /// Header stems treated as roots even outside the scoped SDK directories.
571    scope_headers: HashSet<String>,
572    /// Root header stems dropped before the reachability sweep.
573    exclude_headers: HashSet<String>,
574    /// Targeted function-symbol allowlist. Empty leaves emission unrestricted.
575    symbols: HashSet<String>,
576    /// Leading-underscore macros explicitly selected for emission.
577    include_macros: HashSet<String>,
578    /// Function symbols explicitly excluded from emission.
579    exclude_symbols: HashSet<String>,
580    /// Drops functions with no resolved import library; off for fixtures without `.lib` inputs.
581    drop_lib_less: bool,
582    /// Winmds used only to classify `ABI::Windows::*` projection declarations.
583    resolution_input: Vec<PathBuf>,
584    reference_default: bool,
585    resolution_default: bool,
586    reference_bytes: Vec<std::sync::Arc<[u8]>>,
587    resolution_bytes: Vec<std::sync::Arc<[u8]>>,
588}
589
590/// Read-only inputs shared by every per-header pass.
591#[derive(Clone, Copy)]
592struct HeaderPass<'a> {
593    /// Flat namespace root every partition emits into (`Windows.Win32`).
594    root: &'a str,
595    /// Types supplied by external metadata references.
596    ref_map: &'a HashMap<String, String>,
597    /// Resolution-winmd type-name membership for `ABI::Windows::*` declarations.
598    winrt_types: &'a HashSet<String>,
599}
600
601impl Clang {
602    /// Creates a builder with default options.
603    pub fn new() -> Self {
604        Self::default()
605    }
606
607    /// Adds an input header (`.h`, `.hpp`, `.hxx`, or `.hh`) file or directory.
608    pub fn input(&mut self, input: impl AsRef<Path>) -> &mut Self {
609        self.input.push(input.as_ref().to_path_buf());
610        self
611    }
612
613    /// Adds input headers.
614    pub fn inputs<I, S>(&mut self, inputs: I) -> &mut Self
615    where
616        I: IntoIterator<Item = S>,
617        S: AsRef<Path>,
618    {
619        for input in inputs {
620            self.input(input);
621        }
622        self
623    }
624
625    /// Adds inline source text to compile instead of a file on disk.
626    pub fn input_text(&mut self, input: &str) -> &mut Self {
627        self.input_text.push(input.to_string());
628        self
629    }
630
631    /// Adds inline source texts to compile instead of files on disk.
632    pub fn input_texts<I, S>(&mut self, inputs: I) -> &mut Self
633    where
634        I: IntoIterator<Item = S>,
635        S: AsRef<str>,
636    {
637        for input in inputs {
638            self.input_text(input.as_ref());
639        }
640        self
641    }
642
643    /// Adds a reference winmd file or directory.
644    pub fn reference(&mut self, input: impl AsRef<Path>) -> &mut Self {
645        self.reference.push(input.as_ref().to_path_buf());
646        self
647    }
648
649    /// Adds multiple reference winmd files or directories.
650    pub fn references<I, S>(&mut self, inputs: I) -> &mut Self
651    where
652        I: IntoIterator<Item = S>,
653        S: AsRef<Path>,
654    {
655        for input in inputs {
656            self.reference(input);
657        }
658        self
659    }
660
661    /// Adds a reference winmd from memory.
662    pub fn reference_bytes(&mut self, input: &[u8]) -> &mut Self {
663        self.reference_bytes.push(input.into());
664        self
665    }
666
667    /// Adds reference winmds from memory.
668    pub fn reference_byte_sets<I, B>(&mut self, inputs: I) -> &mut Self
669    where
670        I: IntoIterator<Item = B>,
671        B: AsRef<[u8]>,
672    {
673        for input in inputs {
674            self.reference_bytes(input.as_ref());
675        }
676        self
677    }
678
679    /// Adds the default Windows metadata as references.
680    pub fn reference_default(&mut self) -> &mut Self {
681        self.reference_default = true;
682        self
683    }
684
685    /// Sets the output `.rdl` file path.
686    pub fn output(&mut self, output: impl AsRef<Path>) -> &mut Self {
687        self.output = output.as_ref().to_path_buf();
688        self
689    }
690
691    /// Sets the namespace for the generated types.
692    pub fn namespace(&mut self, namespace: &str) -> &mut Self {
693        self.namespace = namespace.to_string();
694        self
695    }
696
697    /// Sets the library name recorded for imported functions.
698    pub fn library(&mut self, library: &str) -> &mut Self {
699        self.library = library.to_string();
700        self
701    }
702
703    /// Drops functions with no resolved import library; leave off without `.lib` inputs.
704    pub fn drop_lib_less(&mut self) -> &mut Self {
705        self.drop_lib_less = true;
706        self
707    }
708
709    /// Adds a winmd used only to classify `ABI::Windows::*` projection declarations.
710    pub fn resolution_input(&mut self, input: impl AsRef<Path>) -> &mut Self {
711        self.resolution_input.push(input.as_ref().to_path_buf());
712        self
713    }
714
715    /// Adds winmds used only to classify `ABI::Windows::*` projection declarations.
716    pub fn resolution_inputs<I, S>(&mut self, inputs: I) -> &mut Self
717    where
718        I: IntoIterator<Item = S>,
719        S: AsRef<Path>,
720    {
721        for input in inputs {
722            self.resolution_input(input);
723        }
724        self
725    }
726
727    /// Adds a resolution-only winmd from memory.
728    pub fn resolution_bytes(&mut self, input: &[u8]) -> &mut Self {
729        self.resolution_bytes.push(input.into());
730        self
731    }
732
733    /// Adds resolution-only winmds from memory.
734    pub fn resolution_byte_sets<I, B>(&mut self, inputs: I) -> &mut Self
735    where
736        I: IntoIterator<Item = B>,
737        B: AsRef<[u8]>,
738    {
739        for input in inputs {
740            self.resolution_bytes(input.as_ref());
741        }
742        self
743    }
744
745    /// Adds the default Windows Runtime metadata as a resolution-only input.
746    pub fn resolution_default(&mut self) -> &mut Self {
747        self.resolution_default = true;
748        self
749    }
750
751    /// Adds symbol -> DLL overrides for functions.
752    ///
753    /// Prefer per-DLL `.lib` files over umbrella/apiset libraries for real DLL names.
754    ///
755    /// [`library`]: Self::library
756    /// [`import_library`]: Self::import_library
757    pub fn libraries<I, K, V>(&mut self, libraries: I) -> &mut Self
758    where
759        I: IntoIterator<Item = (K, V)>,
760        K: Into<String>,
761        V: Into<String>,
762    {
763        self.libraries
764            .extend(libraries.into_iter().map(|(k, v)| (k.into(), v.into())));
765        self
766    }
767
768    /// Adds defining-header -> library overrides for flat per-header output.
769    ///
770    /// Explicit per-symbol mappings added with [`libraries`](Self::libraries) take precedence.
771    pub fn header_libraries<I, H, V>(&mut self, libraries: I) -> &mut Self
772    where
773        I: IntoIterator<Item = (H, V)>,
774        H: AsRef<str>,
775        V: Into<String>,
776    {
777        self.header_libraries.extend(
778            libraries.into_iter().map(|(header, library)| {
779                (header_stem_to_namespace(header.as_ref()), library.into())
780            }),
781        );
782        self
783    }
784
785    /// Returns the DLL currently mapped to a function symbol.
786    pub fn resolved_library(&self, symbol: &str) -> Option<&str> {
787        self.libraries.get(symbol).map(String::as_str)
788    }
789
790    /// Reads a COFF import library and adds its symbol -> DLL mappings.
791    pub fn import_library(&mut self, path: impl AsRef<Path>) -> Result<&mut Self, Error> {
792        extend_libraries(&mut self.libraries, path.as_ref())?;
793        Ok(self)
794    }
795
796    /// Adds a normalized header path suffix to the inclusion filter.
797    pub fn filter(&mut self, filter: &str) -> &mut Self {
798        self.filter.push(filter.to_string());
799        self
800    }
801
802    /// Adds multiple header path suffixes to the inclusion filter.
803    pub fn filters<I, S>(&mut self, filters: I) -> &mut Self
804    where
805        I: IntoIterator<Item = S>,
806        S: AsRef<str>,
807    {
808        for filter in filters {
809            self.filter.push(filter.as_ref().to_string());
810        }
811        self
812    }
813
814    /// Adds a compiler argument to pass to libclang.
815    pub fn arg<S: AsRef<str>>(&mut self, arg: S) -> &mut Self {
816        self.args.push(arg.as_ref().to_string());
817        self
818    }
819
820    /// Adds multiple compiler arguments to pass to libclang.
821    pub fn args<I>(&mut self, args: I) -> &mut Self
822    where
823        I: IntoIterator,
824        I::Item: AsRef<str>,
825    {
826        for arg in args {
827            self.args.push(arg.as_ref().to_string());
828        }
829        self
830    }
831
832    /// Sets the target triple used for all clang invocations.
833    pub fn target(&mut self, target: &str) -> &mut Self {
834        self.target = Some(target.to_string());
835        self
836    }
837
838    /// Adds a header directory segment that acts as a root for the reachability sweep.
839    pub fn scope(&mut self, scope: &str) -> &mut Self {
840        self.scope.push(scope.to_string());
841        self
842    }
843
844    /// Adds multiple header directory segments as roots for the reachability sweep.
845    pub fn scopes<I, S>(&mut self, scopes: I) -> &mut Self
846    where
847        I: IntoIterator<Item = S>,
848        S: AsRef<str>,
849    {
850        for scope in scopes {
851            self.scope(scope.as_ref());
852        }
853        self
854    }
855
856    /// Marks a header as a sweep root regardless of SDK directory.
857    pub fn scope_header(&mut self, header: &str) -> &mut Self {
858        let stem = header_stem_to_namespace(header);
859        if !stem.is_empty() {
860            self.scope_headers.insert(stem);
861        }
862        self
863    }
864
865    /// Marks multiple headers as sweep roots regardless of SDK directory.
866    pub fn scope_headers<I, S>(&mut self, headers: I) -> &mut Self
867    where
868        I: IntoIterator<Item = S>,
869        S: AsRef<str>,
870    {
871        for header in headers {
872            self.scope_header(header.as_ref());
873        }
874        self
875    }
876
877    /// Drops a named header partition before the reachability sweep.
878    pub fn exclude_header(&mut self, header: &str) -> &mut Self {
879        let stem = header_stem_to_namespace(header);
880        if !stem.is_empty() {
881            self.exclude_headers.insert(stem);
882        }
883        self
884    }
885
886    /// Drops multiple named header partitions before the reachability sweep.
887    pub fn exclude_headers<I, S>(&mut self, headers: I) -> &mut Self
888    where
889        I: IntoIterator<Item = S>,
890        S: AsRef<str>,
891    {
892        for header in headers {
893            self.exclude_header(header.as_ref());
894        }
895        self
896    }
897
898    /// Restricts root emission to a named function symbol.
899    pub fn symbol(&mut self, symbol: &str) -> &mut Self {
900        self.symbols.insert(symbol.to_string());
901        self
902    }
903
904    /// Restricts root emission to the named function symbols.
905    pub fn symbols<I, S>(&mut self, symbols: I) -> &mut Self
906    where
907        I: IntoIterator<Item = S>,
908        S: AsRef<str>,
909    {
910        for symbol in symbols {
911            self.symbol(symbol.as_ref());
912        }
913        self
914    }
915
916    /// Includes a leading-underscore macro that would otherwise be treated as internal.
917    pub fn include_macro(&mut self, name: &str) -> &mut Self {
918        self.include_macros.insert(name.to_string());
919        self
920    }
921
922    /// Includes leading-underscore macros that would otherwise be treated as internal.
923    pub fn include_macros<I, S>(&mut self, names: I) -> &mut Self
924    where
925        I: IntoIterator<Item = S>,
926        S: AsRef<str>,
927    {
928        for name in names {
929            self.include_macro(name.as_ref());
930        }
931        self
932    }
933
934    /// Excludes a function symbol from emission.
935    pub fn exclude_symbol(&mut self, symbol: &str) -> &mut Self {
936        self.exclude_symbols.insert(symbol.to_string());
937        self
938    }
939
940    /// Excludes function symbols from emission.
941    pub fn exclude_symbols<I, S>(&mut self, symbols: I) -> &mut Self
942    where
943        I: IntoIterator<Item = S>,
944        S: AsRef<str>,
945    {
946        for symbol in symbols {
947            self.exclude_symbol(symbol.as_ref());
948        }
949        self
950    }
951
952    /// Returns the version string reported by the loaded libclang.
953    pub fn version() -> Result<String, Error> {
954        let lib = Library::new()?;
955        Ok(lib.version())
956    }
957
958    /// Generates the RDL and writes it to the configured output.
959    pub fn write(&self) -> Result<(), Error> {
960        self.validate_output()?;
961        let reference = self.load_reference()?;
962        let spec = NamespaceSpec {
963            namespace: &self.namespace,
964            library: &self.library,
965            libraries: &self.libraries,
966            filter: &self.filter,
967            symbols: &self.symbols,
968            include_macros: &self.include_macros,
969            exclude_symbols: &self.exclude_symbols,
970        };
971        let rdl = self.parse_and_emit(&reference, std::slice::from_ref(&spec))?;
972        write_to_file(&self.output, formatter::format(&rdl[0]))?;
973        Ok(())
974    }
975
976    /// Writes one flat-root RDL file per defining header.
977    pub fn write_by_header(&self) -> Result<(), Error> {
978        self.validate_output()?;
979        let outputs = self.parse_and_emit_by_header(&self.namespace)?;
980        for (stem, rdl) in outputs {
981            // File names are lowercased defining-header stems.
982            let leaf = stem.to_lowercase();
983            write_to_file(
984                self.output.join(format!("{leaf}.rdl")),
985                formatter::format(&rdl),
986            )?;
987        }
988        Ok(())
989    }
990
991    fn validate_output(&self) -> Result<(), Error> {
992        if self.output.as_os_str().is_empty() {
993            Err(Error::new("output is required", "", 0, 0))
994        } else {
995            Ok(())
996        }
997    }
998
999    /// Parses inputs once and returns the libclang state that keeps the TUs valid.
1000    fn parse_inputs(&self) -> Result<ParsedInputs, Error> {
1001        let h_paths = expand_header_inputs(&self.input)?;
1002        let library = Library::new()?;
1003        let index = Index::new()?;
1004
1005        // Put `--target=` before user args.
1006        let args: Vec<String> = self
1007            .target
1008            .as_ref()
1009            .map(|t| format!("--target={t}"))
1010            .into_iter()
1011            .chain(self.args.iter().cloned())
1012            .collect();
1013        let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
1014
1015        let mut h_tus = vec![];
1016        for input in &h_paths {
1017            let source = input.to_str().ok_or_else(|| {
1018                Error::new(
1019                    "input path is not valid UTF-8",
1020                    &input.to_string_lossy(),
1021                    0,
1022                    0,
1023                )
1024            })?;
1025            h_tus.push((source.replace('\\', "/"), index.parse(source, &arg_refs)?));
1026        }
1027        let mut str_tus = vec![];
1028        for content in &self.input_text {
1029            str_tus.push((
1030                content.clone(),
1031                index.parse_unsaved(
1032                    ".h",
1033                    content,
1034                    &arg_refs,
1035                    CXTranslationUnit_DetailedPreprocessingRecord,
1036                )?,
1037            ));
1038        }
1039
1040        Ok(ParsedInputs {
1041            args,
1042            h_tus,
1043            str_tus,
1044            index,
1045            _library: library,
1046        })
1047    }
1048
1049    /// Emits one flat-root RDL string per defining-header stem.
1050    fn parse_and_emit_by_header(&self, root: &str) -> Result<BTreeMap<String, String>, Error> {
1051        // Additive scrapes skip entities already defined by input winmds. Split type and
1052        // value names because functions/constants live on `Apis`, not in `iter()`.
1053        let reference = self.load_reference()?;
1054        let mut exclude_types: HashSet<String> = HashSet::new();
1055        let mut exclude_values: HashSet<String> = HashSet::new();
1056        // Reference enums the scrape may carry in full: a reference (`um`) header can truncate
1057        // an enum (for example `winternl.h` cuts `FILE_INFORMATION_CLASS` to one member) while
1058        // the scraped (`km`) headers define it completely. Record each reference enum's member
1059        // set so an enum the scrape extends can be un-excluded below and emitted in full; the
1060        // winmd merge then unions the truncated reference copy with this complete one.
1061        let mut reference_enums: HashMap<String, HashSet<String>> = HashMap::new();
1062        for (_, name, item) in reference.iter_items() {
1063            match item {
1064                metadata::reader::Item::Type(def) => {
1065                    if def.category() == metadata::reader::TypeCategory::Enum {
1066                        reference_enums.insert(
1067                            name.to_string(),
1068                            def.fields()
1069                                .filter(|field| field.constant().is_some())
1070                                .map(|field| field.name().to_string())
1071                                .collect(),
1072                        );
1073                    }
1074                    exclude_types.insert(name.to_string())
1075                }
1076                metadata::reader::Item::Fn(_) | metadata::reader::Item::Const(_) => {
1077                    exclude_values.insert(name.to_string())
1078                }
1079            };
1080        }
1081
1082        let parsed = self.parse_inputs()?;
1083        let arg_refs: Vec<&str> = parsed.args.iter().map(String::as_str).collect();
1084
1085        // Backtick-stripped resolution names classify `ABI::Windows::*` declarations.
1086        let winrt_types = self.load_winrt_types()?;
1087
1088        let mut collectors: BTreeMap<String, Collector> = BTreeMap::new();
1089        // Per-partition root flag for the reachability sweep.
1090        let mut scope_in: BTreeMap<String, bool> = BTreeMap::new();
1091
1092        let ref_map = build_ref_map(&reference, root);
1093        let pass = HeaderPass {
1094            root,
1095            ref_map: &ref_map,
1096            winrt_types: &winrt_types,
1097        };
1098
1099        for (input, tu) in &parsed.h_tus {
1100            self.process_tu_by_header(
1101                tu,
1102                &pass,
1103                &mut collectors,
1104                &mut scope_in,
1105                MacroEval {
1106                    source: MacroSource::File(input),
1107                    args: &arg_refs,
1108                },
1109            )?;
1110        }
1111        for (content, tu) in &parsed.str_tus {
1112            self.process_tu_by_header(
1113                tu,
1114                &pass,
1115                &mut collectors,
1116                &mut scope_in,
1117                MacroEval {
1118                    source: MacroSource::Str(content),
1119                    args: &arg_refs,
1120                },
1121            )?;
1122        }
1123
1124        // Drop excluded root partitions before the sweep.
1125        if !self.exclude_headers.is_empty() {
1126            collectors.retain(|stem, _| !self.exclude_headers.contains(stem));
1127            scope_in.retain(|stem, _| !self.exclude_headers.contains(stem));
1128        }
1129
1130        // Keep out-of-scope declarations only when referenced from an in-scope root.
1131        if !self.scope.is_empty() || !self.scope_headers.is_empty() {
1132            sweep_unreferenced(&mut collectors, &scope_in);
1133        }
1134
1135        // Un-exclude a reference enum the scrape carries with members the reference lacks: emit
1136        // the complete enum so the winmd merge can union it with the truncated reference copy
1137        // into a single enum. An enum the scrape does not extend stays excluded (the reference
1138        // copy already covers it).
1139        if !reference_enums.is_empty() {
1140            let mut keep: HashSet<String> = HashSet::new();
1141            for collector in collectors.values() {
1142                for item in collector.values() {
1143                    let Item::Enum(e) = item else {
1144                        continue;
1145                    };
1146                    let Some(members) = reference_enums.get(&e.name) else {
1147                        continue;
1148                    };
1149                    if e.variants
1150                        .iter()
1151                        .any(|(member, _)| !members.contains(member))
1152                    {
1153                        keep.insert(e.name.clone());
1154                    }
1155                }
1156            }
1157            for name in &keep {
1158                exclude_types.remove(name);
1159            }
1160        }
1161
1162        // Exclude same-category names already in the reference winmd; cross-category clashes
1163        // may still be real dependencies and are handled below.
1164        if !exclude_types.is_empty() || !exclude_values.is_empty() {
1165            for collector in collectors.values_mut() {
1166                collector.retain_items(|name, item| {
1167                    if item.is_type() {
1168                        !exclude_types.contains(name)
1169                    } else {
1170                        !exclude_values.contains(name)
1171                    }
1172                });
1173            }
1174        }
1175
1176        // Drop unreferenced WDK types that collide with Win32 values in the flat root. A
1177        // referenced cross-kind clash stays so its typedefs do not dangle.
1178        if !exclude_values.is_empty() {
1179            let mut referenced: HashSet<String> = HashSet::new();
1180            for collector in collectors.values() {
1181                for item in collector.values() {
1182                    item_refs(item, &mut referenced);
1183                }
1184            }
1185            for collector in collectors.values_mut() {
1186                collector.retain_items(|name, item| {
1187                    !(item.is_type() && exclude_values.contains(name) && !referenced.contains(name))
1188                });
1189            }
1190        }
1191
1192        // Drop `IID_<Interface>` constants when the interface in this scrape already carries
1193        // the GUID; bindgen synthesizes the same constant from the interface GUID.
1194        let interfaces: HashSet<String> = collectors
1195            .values()
1196            .flat_map(|collector| collector.iter())
1197            .filter(|(_, item)| matches!(item, Item::Interface(_)))
1198            .map(|(name, _)| name.clone())
1199            .collect();
1200        if !interfaces.is_empty() {
1201            for collector in collectors.values_mut() {
1202                collector.retain_items(|name, item| {
1203                    !(matches!(item, Item::GuidConst(_))
1204                        && name
1205                            .strip_prefix("IID_")
1206                            .is_some_and(|iface| interfaces.contains(iface)))
1207                });
1208            }
1209        }
1210
1211        // Drop unreferenced loose constants that duplicate enum members by name and value.
1212        let enum_members = enum_member_values(&collectors);
1213        if !enum_members.is_empty() {
1214            let mut referenced = HashSet::new();
1215            for collector in collectors.values() {
1216                for item in collector.values() {
1217                    item_refs(item, &mut referenced);
1218                }
1219            }
1220            for collector in collectors.values_mut() {
1221                collector.retain_items(|name, item| {
1222                    let Item::Const(c) = item else {
1223                        return true;
1224                    };
1225                    if referenced.contains(name) {
1226                        return true;
1227                    }
1228                    let (Some(values), Some(value)) =
1229                        (enum_members.get(name), const_integer_bits(&c.value))
1230                    else {
1231                        return true;
1232                    };
1233                    !values.iter().any(|&member| enum_member_eq(member, value))
1234                });
1235            }
1236        }
1237
1238        // Choose duplicate typedef owners only after every partition and item filter has run.
1239        dedup_typedefs(&mut collectors);
1240
1241        let mut outputs = BTreeMap::new();
1242        for (stem, collector) in &collectors {
1243            // Empty partitions are not written.
1244            if collector.is_empty() {
1245                continue;
1246            }
1247            // Every file emits the same flat root; the stem only names the file.
1248            outputs.insert(stem.clone(), emit_module(root, collector)?);
1249        }
1250        Ok(outputs)
1251    }
1252
1253    /// Routes top-level declarations to collectors keyed by defining-header stem.
1254    fn process_tu_by_header(
1255        &self,
1256        tu: &TranslationUnit,
1257        pass: &HeaderPass<'_>,
1258        collectors: &mut BTreeMap<String, Collector>,
1259        scope_in: &mut BTreeMap<String, bool>,
1260        eval: MacroEval<'_>,
1261    ) -> Result<(), Error> {
1262        let HeaderPass {
1263            root,
1264            ref_map,
1265            winrt_types,
1266        } = *pass;
1267        // Abort on diagnostics in emitted headers; tolerate transitive-only include errors
1268        // so interop headers can survive broken C++/WinRT projection includes.
1269        for diag in tu.diagnostics() {
1270            if !diag.is_err() {
1271                continue;
1272            }
1273            let emitted = self.scope.is_empty()
1274                || diag.file_name.is_empty()
1275                || self
1276                    .scope_headers
1277                    .contains(&header_stem_to_namespace(&diag.file_name))
1278                || header_in_scope(&diag.file_name, &self.scope);
1279            if emitted {
1280                return Err(Error::new(
1281                    &diag.message,
1282                    &diag.file_name,
1283                    diag.line.try_into().unwrap(),
1284                    (diag.column.saturating_sub(1)).try_into().unwrap(),
1285                ));
1286            }
1287        }
1288
1289        let mut tag_rename = build_tag_rename_map(tu);
1290        assign_nested_names(tu, &mut tag_rename);
1291        let enum_merge = merge_enum_typedef_idiom(tu, &mut tag_rename);
1292        // Share TU-wide macro definitions across per-header parsers.
1293        let macro_defs = collect_macro_defs(tu);
1294        let unsupported_types = collect_unrepresentable_typedefs(tu, &tag_rename);
1295
1296        // Flatten linkage blocks and deduplicate by clang identity across repeated SDK
1297        // declarations; the defining header only selects the output file.
1298        let mut decls = Vec::new();
1299        // A resolution winmd lets the ABI namespace walker separate WinRT types from COM interop.
1300        let abi = (!winrt_types.is_empty()).then_some(winrt_types);
1301        flatten_decls(tu.cursor(), false, false, None, abi, &mut decls);
1302
1303        // Prefer definitions over forward declarations so records route to defining headers.
1304        let mut chosen: BTreeMap<String, (Cursor, bool)> = BTreeMap::new();
1305        for (child, extern_c) in decls {
1306            if is_handle_tag_struct(&child) {
1307                continue;
1308            }
1309            if header_stem_of(&child).is_none() {
1310                continue;
1311            }
1312            let usr = child.usr();
1313            let key = if usr.is_empty() {
1314                child.canonical().location_id()
1315            } else {
1316                usr
1317            };
1318            match chosen.entry(key) {
1319                std::collections::btree_map::Entry::Vacant(e) => {
1320                    e.insert((child, extern_c));
1321                }
1322                std::collections::btree_map::Entry::Occupied(mut e) => {
1323                    let existing = &e.get().0;
1324                    // Among forward declarations, keep the `uuid` one so CLSIDs survive.
1325                    let replace = if child.is_definition() {
1326                        !existing.is_definition()
1327                    } else if !existing.is_definition() {
1328                        (child.extract_uuid(tu).is_some() && existing.extract_uuid(tu).is_none())
1329                            || (child.kind() == CXCursor_FunctionDecl
1330                                && asm_import_name(&child).is_some()
1331                                && asm_import_name(existing).is_none())
1332                    } else {
1333                        false
1334                    };
1335                    if replace {
1336                        e.insert((child, extern_c));
1337                    }
1338                }
1339            }
1340        }
1341
1342        let mut buckets: BTreeMap<String, Vec<(Cursor, bool)>> = BTreeMap::new();
1343        for (_, (child, extern_c)) in chosen {
1344            let stem = header_stem_of(&child).expect("filtered above");
1345            // Keep a partition in-scope if any contributing cursor is in-scope.
1346            if !self.scope.is_empty() || !self.scope_headers.is_empty() {
1347                let in_scope = self.scope_headers.contains(&stem)
1348                    || header_path_of(&child).is_none_or(|p| header_in_scope(&p, &self.scope));
1349                scope_in
1350                    .entry(stem.clone())
1351                    .and_modify(|v| *v |= in_scope)
1352                    .or_insert(in_scope);
1353            }
1354            buckets.entry(stem).or_default().push((child, extern_c));
1355        }
1356
1357        let empty_symbols: HashSet<String> = HashSet::new();
1358        let mut all_opaque: Vec<(String, String)> = vec![];
1359        // Macro constants are per-bucket values but are deduplicated globally.
1360        let mut all_consts: Vec<(String, Vec<String>)> = vec![];
1361
1362        for (stem, cursors) in buckets {
1363            let collector = collectors.entry(stem.clone()).or_default();
1364            let mut libraries = self.libraries.clone();
1365            if let Some(library) = self.header_libraries.get(&stem) {
1366                for (cursor, _) in &cursors {
1367                    if cursor.kind() == CXCursor_FunctionDecl {
1368                        libraries
1369                            .entry(cursor.name())
1370                            .or_insert_with(|| library.clone());
1371                    }
1372                }
1373            }
1374            let mut parser = Parser::new(
1375                root,
1376                &self.library,
1377                &libraries,
1378                ref_map,
1379                &tag_rename,
1380                &enum_merge,
1381                &macro_defs,
1382                tu,
1383                &empty_symbols,
1384                &self.include_macros,
1385                &self.exclude_symbols,
1386                &unsupported_types,
1387            );
1388            parser.header_root = Some(root);
1389            parser.drop_lib_less = self.drop_lib_less;
1390            parser.winrt_types = abi;
1391
1392            for (child, extern_c) in cursors {
1393                parser.process_cursor(child, collector, extern_c)?;
1394            }
1395
1396            collector.apply_iid_vars(&parser.iid_vars);
1397
1398            let pending = std::mem::take(&mut parser.pending_macros);
1399            if !pending.is_empty() {
1400                all_consts.push((stem.clone(), pending));
1401            }
1402            for (_ns, name) in std::mem::take(&mut parser.pending_opaque) {
1403                all_opaque.push((stem.clone(), name));
1404            }
1405        }
1406
1407        // Flat enums contribute member names too, since those emit as top-level constants.
1408        let mut global_names: HashSet<String> = collectors
1409            .values()
1410            .flat_map(|c| c.values())
1411            .flat_map(|item| {
1412                let mut names = vec![item.to_string()];
1413                if let Item::Enum(e) = item {
1414                    names.extend(e.variants.iter().map(|(name, _)| name.clone()));
1415                }
1416                names
1417            })
1418            .collect();
1419
1420        // Evaluate buckets in parallel but merge in stable order so first owner wins.
1421        let evaluated = evaluate_macros_parallel(&all_consts, eval.source, eval.args)?;
1422        for ((stem, _pending), consts) in all_consts.into_iter().zip(evaluated) {
1423            let collector = collectors.entry(stem).or_default();
1424            for c in consts {
1425                if global_names.insert(c.name.clone()) {
1426                    collector.insert(Item::Const(c));
1427                }
1428            }
1429        }
1430
1431        // Emit opaque placeholders only when no real definition won globally.
1432        for (stem, name) in all_opaque {
1433            if global_names.insert(name.clone()) {
1434                let collector = collectors.entry(stem).or_default();
1435                collector.insert(Item::Struct(Struct::opaque(&name)));
1436            }
1437        }
1438
1439        Ok(())
1440    }
1441
1442    /// Loads `.winmd` reference inputs for cross-namespace resolution.
1443    fn load_reference(&self) -> Result<metadata::reader::Index, Error> {
1444        let winmd_paths = expand_input_files(&self.reference, "winmd")?;
1445
1446        let mut winmd_files = vec![];
1447        for file_name in &winmd_paths {
1448            let source = file_name.to_string_lossy();
1449            winmd_files.push(
1450                metadata::reader::File::read(file_name)
1451                    .ok_or_else(|| Error::new("invalid reference", &source, 0, 0))?,
1452            );
1453        }
1454        if self.reference_default {
1455            winmd_files.extend(
1456                [windows_default::WINRT, windows_default::WIN32]
1457                    .into_iter()
1458                    .map(|bytes| metadata::reader::File::new(bytes.to_vec()).unwrap()),
1459            );
1460        }
1461        for bytes in &self.reference_bytes {
1462            winmd_files.push(
1463                metadata::reader::File::new(bytes.to_vec())
1464                    .ok_or_else(|| Error::new("invalid reference", "<memory>", 0, 0))?,
1465            );
1466        }
1467
1468        Ok(metadata::reader::Index::new(winmd_files))
1469    }
1470
1471    /// Loads resolution-winmd type names, stripping generic arity for C++ ABI matching.
1472    fn load_winrt_types(&self) -> Result<HashSet<String>, Error> {
1473        let mut winmd_files = vec![];
1474        for file_name in &self.resolution_input {
1475            let source = file_name.to_string_lossy();
1476            winmd_files.push(
1477                metadata::reader::File::read(file_name)
1478                    .ok_or_else(|| Error::new("invalid resolution input", &source, 0, 0))?,
1479            );
1480        }
1481        if self.resolution_default {
1482            winmd_files.push(metadata::reader::File::new(windows_default::WINRT.to_vec()).unwrap());
1483        }
1484        for bytes in &self.resolution_bytes {
1485            winmd_files.push(
1486                metadata::reader::File::new(bytes.to_vec())
1487                    .ok_or_else(|| Error::new("invalid resolution input", "<memory>", 0, 0))?,
1488            );
1489        }
1490        let index = metadata::reader::Index::new(winmd_files);
1491        let mut set = HashSet::new();
1492        for (namespace, name, _) in index.iter() {
1493            let bare = name.split('`').next().unwrap_or(name);
1494            set.insert(format!("{namespace}.{bare}"));
1495        }
1496        Ok(set)
1497    }
1498
1499    /// Emits one RDL string per namespace spec, reusing cached translation units.
1500    fn parse_and_emit(
1501        &self,
1502        reference: &metadata::reader::Index,
1503        specs: &[NamespaceSpec<'_>],
1504    ) -> Result<Vec<String>, Error> {
1505        // Reuse translation units across all specs.
1506        let parsed = self.parse_inputs()?;
1507        let arg_refs: Vec<&str> = parsed.args.iter().map(String::as_str).collect();
1508
1509        // Pass 1: learn unique type-name owners across specs. Shared typedef artifacts stay
1510        // local by being dropped from the owner table.
1511        let mut owners: HashMap<String, Option<String>> = HashMap::new();
1512        for spec in specs {
1513            let ref_map = build_ref_map(reference, spec.namespace);
1514            let mut collector = Collector::new();
1515            for (_, tu) in &parsed.h_tus {
1516                self.process_tu(tu, &mut collector, &ref_map, spec)?;
1517            }
1518            for (_, tu) in &parsed.str_tus {
1519                self.process_tu(tu, &mut collector, &ref_map, spec)?;
1520            }
1521            for name in collector.keys() {
1522                owners
1523                    .entry(name.clone())
1524                    .and_modify(|owner| {
1525                        if owner.as_deref() != Some(spec.namespace) {
1526                            *owner = None;
1527                        }
1528                    })
1529                    .or_insert_with(|| Some(spec.namespace.to_string()));
1530            }
1531        }
1532        let in_house: HashMap<String, String> = owners
1533            .into_iter()
1534            .filter_map(|(name, owner)| owner.map(|ns| (name, ns)))
1535            .collect();
1536
1537        // Pass 2: emit with in-house owners preferred over the upstream reference.
1538        let mut outputs = Vec::with_capacity(specs.len());
1539
1540        for spec in specs {
1541            let ref_map = build_resolution_map(reference, &in_house, spec.namespace);
1542            let mut collector = Collector::new();
1543
1544            for (input, tu) in &parsed.h_tus {
1545                let pending = self.process_tu(tu, &mut collector, &ref_map, spec)?;
1546                for c in Const::evaluate_macros(input, &pending, &parsed.index, &arg_refs)? {
1547                    collector.insert(Item::Const(c));
1548                }
1549            }
1550
1551            for (content, tu) in &parsed.str_tus {
1552                let pending = self.process_tu(tu, &mut collector, &ref_map, spec)?;
1553                for c in Const::evaluate_macros_str(content, &pending, &parsed.index, &arg_refs)? {
1554                    collector.insert(Item::Const(c));
1555                }
1556            }
1557
1558            outputs.push(emit_module(spec.namespace, &collector)?);
1559        }
1560
1561        Ok(outputs)
1562    }
1563
1564    /// Processes one translation unit and returns macros needing batch evaluation.
1565    fn process_tu(
1566        &self,
1567        tu: &TranslationUnit,
1568        collector: &mut Collector,
1569        ref_map: &HashMap<String, String>,
1570        spec: &NamespaceSpec<'_>,
1571    ) -> Result<Vec<String>, Error> {
1572        for diag in tu.diagnostics() {
1573            if diag.is_err() {
1574                return Err(Error::new(
1575                    &diag.message,
1576                    &diag.file_name,
1577                    diag.line.try_into().unwrap(),
1578                    (diag.column.saturating_sub(1)).try_into().unwrap(),
1579                ));
1580            }
1581        }
1582
1583        // Map internal tags to their public typedef aliases.
1584        let mut tag_rename = build_tag_rename_map(tu);
1585
1586        // Give nested records synthetic names keyed by tag or source location.
1587        assign_nested_names(tu, &mut tag_rename);
1588        let enum_merge = merge_enum_typedef_idiom(tu, &mut tag_rename);
1589        let macro_defs = collect_macro_defs(tu);
1590        let unsupported_types = collect_unrepresentable_typedefs(tu, &tag_rename);
1591
1592        let mut parser = Parser::new(
1593            spec.namespace,
1594            spec.library,
1595            spec.libraries,
1596            ref_map,
1597            &tag_rename,
1598            &enum_merge,
1599            &macro_defs,
1600            tu,
1601            spec.symbols,
1602            spec.include_macros,
1603            spec.exclude_symbols,
1604            &unsupported_types,
1605        );
1606
1607        for child in tu.cursor().children() {
1608            // Process main-file cursors plus headers matched by this spec.
1609            if !child.is_from_main_file() {
1610                let passes_filter = !spec.filter.is_empty() && {
1611                    let file = child.file_name();
1612                    spec.filter.iter().any(|f| matches_filter(&file, f))
1613                };
1614                if !passes_filter {
1615                    // Linkage macros often spell in helper headers; filter by expansion too.
1616                    let passes_expansion = child.kind() == CXCursor_LinkageSpec && {
1617                        child.is_expansion_from_main_file(tu) || {
1618                            let file = child.expansion_file_name();
1619                            spec.filter.iter().any(|f| matches_filter(&file, f))
1620                        }
1621                    };
1622                    if !passes_expansion {
1623                        continue;
1624                    }
1625                }
1626            }
1627
1628            parser.process_cursor(child, collector, false)?;
1629        }
1630
1631        // Drain referenced type dependencies; parsing one definition can enqueue more.
1632        let mut seen_typedefs: HashSet<String> = HashSet::new();
1633        let mut seen_records: HashSet<String> = HashSet::new();
1634        let mut typedef_index = 0;
1635        let mut record_index = 0;
1636        while typedef_index < parser.pending_typedefs.len()
1637            || record_index < parser.pending_records.len()
1638        {
1639            while typedef_index < parser.pending_typedefs.len() {
1640                let cursor = parser.pending_typedefs[typedef_index];
1641                typedef_index += 1;
1642                let name = cursor.name();
1643                // Skip anything already resolved.
1644                if !seen_typedefs.insert(name.clone())
1645                    || collector.contains_key(&name)
1646                    || parser.ref_map.contains_key(&name)
1647                {
1648                    continue;
1649                }
1650                if let Some(cb) = Callback::parse(cursor, &mut parser)? {
1651                    collector.insert(Item::Callback(cb));
1652                } else if let Some(td) = Typedef::parse(cursor, &mut parser)? {
1653                    collector.insert(Item::Typedef(td));
1654                }
1655            }
1656
1657            while record_index < parser.pending_records.len() {
1658                let cursor = parser.pending_records[record_index];
1659                record_index += 1;
1660                if seen_records.insert(cursor.usr()) {
1661                    parser.processing_dependency = true;
1662                    let result = parser.process_cursor(cursor, collector, false);
1663                    parser.processing_dependency = false;
1664                    result?;
1665                }
1666            }
1667        }
1668
1669        // Apply `IID_IFoo` variables to interfaces that lack `uuid` attributes.
1670        collector.apply_iid_vars(&parser.iid_vars);
1671
1672        Ok(parser.pending_macros)
1673    }
1674}
1675
1676/// Owns libclang state; field order ensures TUs drop before the library unloads.
1677struct ParsedInputs {
1678    args: Vec<String>,
1679    h_tus: Vec<(String, TranslationUnit)>,
1680    str_tus: Vec<(String, TranslationUnit)>,
1681    index: Index,
1682    _library: Library,
1683}
1684
1685const HEADER_EXTENSIONS: [&str; 4] = ["h", "hpp", "hxx", "hh"];
1686
1687fn expand_header_inputs<P: AsRef<Path>>(inputs: &[P]) -> Result<Vec<PathBuf>, Error> {
1688    let mut paths = vec![];
1689
1690    for input in inputs {
1691        let path = input.as_ref();
1692        let display = path.to_string_lossy();
1693
1694        if path.is_dir() {
1695            let previous_len = paths.len();
1696
1697            for entry_path in path
1698                .read_dir()
1699                .map_err(|_| Error::new("failed to read directory", &display, 0, 0))?
1700                .flatten()
1701                .map(|entry| entry.path())
1702            {
1703                if entry_path.is_file()
1704                    && entry_path.extension().is_some_and(|extension| {
1705                        HEADER_EXTENSIONS
1706                            .iter()
1707                            .any(|expected| extension.eq_ignore_ascii_case(expected))
1708                    })
1709                {
1710                    paths.push(entry_path);
1711                }
1712            }
1713
1714            if paths.len() == previous_len {
1715                return Err(Error::new(
1716                    "failed to find .h, .hpp, .hxx, or .hh files in directory",
1717                    &display,
1718                    0,
1719                    0,
1720                ));
1721            }
1722        } else if path.extension().is_some_and(|extension| {
1723            HEADER_EXTENSIONS
1724                .iter()
1725                .any(|expected| extension.eq_ignore_ascii_case(expected))
1726        }) {
1727            paths.push(path.to_path_buf());
1728        } else {
1729            return Err(Error::new(
1730                "expected .h, .hpp, .hxx, or .hh file",
1731                &display,
1732                0,
1733                0,
1734            ));
1735        }
1736    }
1737
1738    Ok(paths)
1739}
1740
1741/// Keep one stable definition when separate headers repeat an equivalent typedef.
1742///
1743/// The SDK may declare the same public alias through different but compatible spellings, such as
1744/// `PUNICODE_STRING` through `UNICODE_STRING` and its `LSA_UNICODE_STRING` base. Winmd cannot
1745/// represent both rows under one flat name, so a direct `PFOO -> FOO*` alias wins, then the first
1746/// surviving defining-header partition.
1747fn dedup_typedefs(collectors: &mut BTreeMap<String, Collector>) {
1748    let mut owners: HashMap<String, (String, bool)> = HashMap::new();
1749    for (stem, collector) in collectors.iter() {
1750        for (name, item) in collector.iter() {
1751            let Item::Typedef(ty) = item else {
1752                continue;
1753            };
1754            let direct = ty.is_direct_pointer_alias();
1755            match owners.entry(name.clone()) {
1756                std::collections::hash_map::Entry::Vacant(entry) => {
1757                    entry.insert((stem.clone(), direct));
1758                }
1759                std::collections::hash_map::Entry::Occupied(mut entry)
1760                    if direct && !entry.get().1 =>
1761                {
1762                    entry.insert((stem.clone(), true));
1763                }
1764                _ => {}
1765            }
1766        }
1767    }
1768    for (stem, collector) in collectors.iter_mut() {
1769        collector.retain_items(|name, item| {
1770            !matches!(item, Item::Typedef(_))
1771                || owners.get(name).is_some_and(|(owner, _)| owner == stem)
1772        });
1773    }
1774}
1775
1776/// Flattens linkage blocks and, when configured, descends into `ABI::Windows::*`.
1777///
1778/// Resolution-winmd membership separates true WinRT ABI projections from Win32 COM interop
1779/// declarations that live in the same C++ namespace.
1780fn flatten_decls(
1781    parent: Cursor,
1782    in_linkage: bool,
1783    in_interop_ns: bool,
1784    abi_ns: Option<&str>,
1785    winrt_types: Option<&HashSet<String>>,
1786    out: &mut Vec<(Cursor, bool)>,
1787) {
1788    for child in parent.children() {
1789        if child.kind() == CXCursor_LinkageSpec {
1790            flatten_decls(child, true, in_interop_ns, abi_ns, winrt_types, out);
1791        } else if child.kind() == CXCursor_Namespace {
1792            if let Some(path) = abi_ns {
1793                // Accumulate the ABI namespace path below `ABI`.
1794                let name = child.name();
1795                let child_path = if path.is_empty() {
1796                    name
1797                } else {
1798                    format!("{path}.{name}")
1799                };
1800                flatten_decls(
1801                    child,
1802                    in_linkage,
1803                    in_interop_ns,
1804                    Some(&child_path),
1805                    winrt_types,
1806                    out,
1807                );
1808            } else if winrt_types.is_some() && child.name() == "ABI" {
1809                // Strip `ABI` itself from the namespace path.
1810                flatten_decls(child, in_linkage, in_interop_ns, Some(""), winrt_types, out);
1811            } else if in_interop_ns || child.name() == "Windows" {
1812                // Hand-authored `Windows::*` C++ interop declarations route to the flat root.
1813                flatten_decls(child, in_linkage, true, None, winrt_types, out);
1814            }
1815        } else if let (Some(path), Some(set)) = (abi_ns, winrt_types) {
1816            // Capture ABI declarations absent from the resolution winmd; skip open templates.
1817            if matches!(
1818                child.kind(),
1819                CXCursor_ClassTemplate
1820                    | CXCursor_ClassTemplatePartialSpecialization
1821                    | CXCursor_FunctionTemplate
1822            ) {
1823                continue;
1824            }
1825            let name = child.name();
1826            let full = if path.is_empty() {
1827                name
1828            } else {
1829                format!("{path}.{name}")
1830            };
1831            if set.contains(&full) {
1832                continue;
1833            }
1834            let extern_c = in_linkage && child.language() == CXLanguage_C;
1835            out.push((child, extern_c));
1836        } else {
1837            let extern_c = in_linkage && child.language() == CXLanguage_C;
1838            out.push((child, extern_c));
1839        }
1840    }
1841}
1842
1843/// True for dummy handle tags (`X__` or MIDL placeholders) that emit as `*mut void`.
1844/// Real MIDL value structs using the same suffix have payload shape and are kept.
1845fn is_handle_tag_struct(child: &Cursor) -> bool {
1846    if !matches!(child.kind(), CXCursor_StructDecl | CXCursor_UnionDecl) || !child.is_definition() {
1847        return false;
1848    }
1849    let name = child.name();
1850    if !name.ends_with("__") && !is_midl_placeholder_tag(&name) {
1851        return false;
1852    }
1853    is_handle_shape(child)
1854}
1855
1856/// MIDL per-method proxy/stub thunks are RPC plumbing unless a real import library exports them.
1857fn is_midl_proxy_stub(cursor: &Cursor, libraries: &HashMap<String, String>) -> bool {
1858    let name = cursor.name();
1859    if !name.ends_with("_Proxy") && !name.ends_with("_Stub") {
1860        return false;
1861    }
1862
1863    if libraries.contains_key(&name) {
1864        return false;
1865    }
1866    cursor
1867        .children()
1868        .iter()
1869        .find(|c| c.kind() == CXCursor_ParmDecl)
1870        .is_some_and(|p| p.name() == "This")
1871}
1872
1873fn record_name(cursor: &Cursor, tag_rename: &HashMap<String, String>) -> String {
1874    let tag = cursor.name();
1875    if is_anonymous_name(&tag) {
1876        tag_rename
1877            .get(&cursor.location_id())
1878            .cloned()
1879            .unwrap_or(tag)
1880    } else {
1881        tag_rename.get(&tag).cloned().unwrap_or(tag)
1882    }
1883}
1884
1885fn collect_unrepresentable_typedefs(
1886    tu: &TranslationUnit,
1887    tag_rename: &HashMap<String, String>,
1888) -> HashSet<String> {
1889    fn visit(cursor: Cursor, declarations: &mut Vec<Cursor>) {
1890        for child in cursor.children() {
1891            if matches!(
1892                child.kind(),
1893                CXCursor_TypedefDecl
1894                    | CXCursor_StructDecl
1895                    | CXCursor_UnionDecl
1896                    | CXCursor_ClassDecl
1897            ) {
1898                declarations.push(child);
1899            }
1900            if matches!(
1901                child.kind(),
1902                CXCursor_LinkageSpec
1903                    | CXCursor_Namespace
1904                    | CXCursor_TypedefDecl
1905                    | CXCursor_StructDecl
1906                    | CXCursor_UnionDecl
1907                    | CXCursor_ClassDecl
1908            ) {
1909                visit(child, declarations);
1910            }
1911        }
1912    }
1913
1914    let mut declarations = Vec::new();
1915    visit(tu.cursor(), &mut declarations);
1916
1917    let mut result = HashSet::new();
1918    for cursor in &declarations {
1919        if cursor.kind() != CXCursor_TypedefDecl {
1920            continue;
1921        }
1922        let underlying = cursor.typedef_underlying_type();
1923        if matches!(
1924            underlying.canonical_type().kind(),
1925            CXType_Record | CXType_ConstantArray
1926        ) {
1927            let size = underlying.size_of();
1928            let alignment = cursor.ty().align_of();
1929            if size > 0 && alignment > 0 && size % alignment != 0 {
1930                result.insert(cursor.name());
1931            }
1932        }
1933    }
1934
1935    loop {
1936        let previous_len = result.len();
1937        for cursor in &declarations {
1938            let (name, depends_on_unsupported) = match cursor.kind() {
1939                CXCursor_TypedefDecl => {
1940                    let underlying = cursor.typedef_underlying_type();
1941                    let alias_dependency =
1942                        type_references_unsupported(&underlying, &result, tag_rename);
1943                    let direct = if underlying.kind() == CXType_Elaborated {
1944                        underlying.underlying_type()
1945                    } else {
1946                        underlying
1947                    };
1948                    let callback_dependency = direct.function_pointee().is_some_and(|function| {
1949                        type_references_unsupported(&function.fn_result_type(), &result, tag_rename)
1950                            || cursor
1951                                .children()
1952                                .iter()
1953                                .filter(|child| child.kind() == CXCursor_ParmDecl)
1954                                .any(|param| {
1955                                    type_references_unsupported(&param.ty(), &result, tag_rename)
1956                                })
1957                    });
1958                    (cursor.name(), callback_dependency || alias_dependency)
1959                }
1960                CXCursor_StructDecl | CXCursor_UnionDecl | CXCursor_ClassDecl => (
1961                    record_name(cursor, tag_rename),
1962                    record_references_unsupported(cursor, &result, tag_rename),
1963                ),
1964                _ => continue,
1965            };
1966            if depends_on_unsupported && !name.is_empty() {
1967                result.insert(name);
1968            }
1969        }
1970        if result.len() == previous_len {
1971            break;
1972        }
1973    }
1974    result
1975}
1976
1977fn type_references_unsupported(
1978    ty: &Type,
1979    unsupported: &HashSet<String>,
1980    tag_rename: &HashMap<String, String>,
1981) -> bool {
1982    match ty.kind() {
1983        CXType_Typedef => {
1984            let decl = ty.ty();
1985            unsupported.contains(&decl.name())
1986                || type_references_unsupported(
1987                    &decl.typedef_underlying_type(),
1988                    unsupported,
1989                    tag_rename,
1990                )
1991        }
1992        CXType_Record => {
1993            let decl = ty.ty();
1994            unsupported.contains(&record_name(&decl, tag_rename))
1995        }
1996        CXType_Pointer | CXType_LValueReference => {
1997            type_references_unsupported(&ty.pointee_type(), unsupported, tag_rename)
1998        }
1999        CXType_ConstantArray | CXType_IncompleteArray => {
2000            type_references_unsupported(&ty.array_element_type(), unsupported, tag_rename)
2001        }
2002        CXType_FunctionProto | CXType_FunctionNoProto => {
2003            type_references_unsupported(&ty.fn_result_type(), unsupported, tag_rename)
2004                || ty
2005                    .fn_arg_types()
2006                    .iter()
2007                    .any(|argument| type_references_unsupported(argument, unsupported, tag_rename))
2008        }
2009        CXType_Elaborated => {
2010            type_references_unsupported(&ty.underlying_type(), unsupported, tag_rename)
2011        }
2012        _ => false,
2013    }
2014}
2015
2016fn record_references_unsupported(
2017    cursor: &Cursor,
2018    unsupported: &HashSet<String>,
2019    tag_rename: &HashMap<String, String>,
2020) -> bool {
2021    cursor.children().iter().any(|child| match child.kind() {
2022        CXCursor_FieldDecl | CXCursor_CXXBaseSpecifier => {
2023            type_references_unsupported(&child.ty(), unsupported, tag_rename)
2024        }
2025        CXCursor_StructDecl | CXCursor_UnionDecl if child.is_anonymous_record() => {
2026            unsupported.contains(&record_name(child, tag_rename))
2027                || record_references_unsupported(child, unsupported, tag_rename)
2028        }
2029        CXCursor_CXXMethod => function_references_unsupported(child, unsupported, tag_rename),
2030        _ => false,
2031    })
2032}
2033
2034fn function_references_unsupported(
2035    cursor: &Cursor,
2036    unsupported: &HashSet<String>,
2037    tag_rename: &HashMap<String, String>,
2038) -> bool {
2039    type_references_unsupported(&cursor.result_type(), unsupported, tag_rename)
2040        || cursor
2041            .children()
2042            .iter()
2043            .filter(|child| child.kind() == CXCursor_ParmDecl)
2044            .any(|param| type_references_unsupported(&param.ty(), unsupported, tag_rename))
2045}
2046
2047/// MIDL `_User*` wire-marshaling helpers are generated RPC internals, not public API.
2048fn is_midl_user_marshal_stub(cursor: &Cursor) -> bool {
2049    let name = cursor.name();
2050    let base = name.strip_suffix("64").unwrap_or(&name);
2051    if !base.ends_with("_UserSize")
2052        && !base.ends_with("_UserMarshal")
2053        && !base.ends_with("_UserUnmarshal")
2054        && !base.ends_with("_UserFree")
2055    {
2056        return false;
2057    }
2058    cursor
2059        .children()
2060        .iter()
2061        .find(|c| c.kind() == CXCursor_ParmDecl)
2062        .is_some_and(|p| {
2063            let ty = p.ty().canonical_type();
2064            ty.kind() == CXType_Pointer && ty.pointee_type().canonical_type().kind() == CXType_ULong
2065        })
2066}
2067
2068/// Collects enum member values across partitions for duplicate loose-constant pruning.
2069fn enum_member_values(collectors: &BTreeMap<String, Collector>) -> HashMap<String, Vec<i64>> {
2070    let mut members: HashMap<String, Vec<i64>> = HashMap::new();
2071    for collector in collectors.values() {
2072        for item in collector.values() {
2073            if let Item::Enum(e) = item {
2074                for (name, value) in &e.variants {
2075                    members.entry(name.clone()).or_default().push(*value);
2076                }
2077            }
2078        }
2079    }
2080    members
2081}
2082
2083/// Converts integer metadata values to `i128` for enum-member duplicate checks.
2084fn const_integer_bits(value: &metadata::Value) -> Option<i128> {
2085    Some(match value {
2086        metadata::Value::Bool(v) => *v as i128,
2087        metadata::Value::U8(v) => *v as i128,
2088        metadata::Value::I8(v) => *v as i128,
2089        metadata::Value::U16(v) => *v as i128,
2090        metadata::Value::I16(v) => *v as i128,
2091        metadata::Value::U32(v) => *v as i128,
2092        metadata::Value::I32(v) => *v as i128,
2093        metadata::Value::U64(v) => *v as i128,
2094        metadata::Value::I64(v) => *v as i128,
2095        metadata::Value::USize(v) => *v as i128,
2096        metadata::Value::ISize(v) => *v as i128,
2097        metadata::Value::EnumValue(_, inner) => return const_integer_bits(inner),
2098        _ => return None,
2099    })
2100}
2101
2102/// Matches high-bit flags that clang sign-extends on the enum side.
2103fn enum_member_eq(member: i64, constant: i128) -> bool {
2104    member as i128 == constant || member as u32 as i128 == constant
2105}
2106
2107/// Emits a collector under the nested `mod` path for `namespace`.
2108fn emit_module(namespace: &str, collector: &Collector) -> Result<String, Error> {
2109    let parts: Vec<&str> = namespace.split('.').collect();
2110    let mut output = format!("#[win32] mod {} {{", parts[0]);
2111
2112    for part in &parts[1..] {
2113        output.push_str(&format!("mod {part} {{"));
2114    }
2115
2116    for item in collector.values() {
2117        output.push_str(&item.write(namespace)?.to_string());
2118    }
2119
2120    for _ in 0..parts.len() {
2121        output.push('}');
2122    }
2123
2124    Ok(output)
2125}
2126
2127/// Converts an enum value to the metadata value matching its repr.
2128fn enum_variant_value(repr: &str, value: i64) -> metadata::Value {
2129    match repr {
2130        "u8" => metadata::Value::U8(value as u8),
2131        "i8" => metadata::Value::I8(value as i8),
2132        "u16" => metadata::Value::U16(value as u16),
2133        "i16" => metadata::Value::I16(value as i16),
2134        "u32" => metadata::Value::U32(value as u32),
2135        "u64" => metadata::Value::U64(value as u64),
2136        "i64" => metadata::Value::I64(value),
2137        _ => metadata::Value::I32(value as i32),
2138    }
2139}
2140
2141#[cfg(test)]
2142mod tests {
2143    use super::*;
2144
2145    #[test]
2146    fn field_refs_descend_into_anonymous_nested_records() {
2147        // Anonymous nested members carry their refs in `nested`, not `ty`.
2148        let nested = Struct {
2149            name: "Anonymous".to_string(),
2150            fields: vec![Field {
2151                name: "value".to_string(),
2152                ty: metadata::Type::ValueName(metadata::TypeName::named("", "InnerType")),
2153                nested: None,
2154                bitfields: vec![],
2155            }],
2156            is_union: true,
2157            packing: None,
2158            alignment: None,
2159        };
2160        let field = Field {
2161            name: "Anonymous".to_string(),
2162            ty: metadata::Type::Void,
2163            nested: Some(Box::new(nested)),
2164            bitfields: vec![],
2165        };
2166
2167        let mut refs = HashSet::new();
2168        collect_field_refs(std::slice::from_ref(&field), &mut refs);
2169        assert!(refs.contains("InnerType"));
2170    }
2171
2172    #[test]
2173    fn value_refs_name_typed_constants() {
2174        let mut refs = HashSet::new();
2175        collect_value_refs(
2176            &metadata::Value::TypeName(metadata::TypeName::named("", "NamedType")),
2177            &mut refs,
2178        );
2179        assert!(refs.contains("NamedType"));
2180
2181        let mut enum_refs = HashSet::new();
2182        collect_value_refs(
2183            &metadata::Value::EnumValue(
2184                metadata::TypeName::named("", "NamedEnum"),
2185                Box::new(metadata::Value::I32(3)),
2186            ),
2187            &mut enum_refs,
2188        );
2189        assert!(enum_refs.contains("NamedEnum"));
2190    }
2191
2192    #[test]
2193    fn const_integer_bits_reads_integers_only() {
2194        assert_eq!(const_integer_bits(&metadata::Value::U32(22)), Some(22));
2195        assert_eq!(const_integer_bits(&metadata::Value::I32(-1)), Some(-1));
2196        assert_eq!(
2197            const_integer_bits(&metadata::Value::U32(0x8000_0000)),
2198            Some(0x8000_0000)
2199        );
2200        assert_eq!(
2201            const_integer_bits(&metadata::Value::EnumValue(
2202                metadata::TypeName::named("", "E"),
2203                Box::new(metadata::Value::U16(7)),
2204            )),
2205            Some(7)
2206        );
2207        assert_eq!(const_integer_bits(&metadata::Value::F32(1.0)), None);
2208        assert_eq!(
2209            const_integer_bits(&metadata::Value::Utf8("x".to_string())),
2210            None
2211        );
2212    }
2213
2214    #[test]
2215    fn enum_member_eq_matches_value_and_high_bit_flag() {
2216        // Plain equal values match.
2217        assert!(enum_member_eq(22, 22));
2218        assert!(!enum_member_eq(22, 23));
2219        // High-bit signed enum flags can match unsigned macro constants.
2220        assert!(enum_member_eq(-2147483648, 0x8000_0000));
2221        // Wide constants do not match by low 32 bits alone.
2222        assert!(!enum_member_eq(0, 0x1_0000_0000));
2223    }
2224
2225    #[test]
2226    fn enum_member_values_collects_variants_across_partitions() {
2227        let mut a = Collector::new();
2228        a.insert(Item::Enum(Enum {
2229            name: "D3DFORMAT".to_string(),
2230            repr: "i32",
2231            variants: vec![("D3DFMT_X8R8G8B8".to_string(), 22)],
2232            flags: false,
2233            scoped: false,
2234        }));
2235        let mut b = Collector::new();
2236        b.insert(Item::Const(Const {
2237            name: "D3DFMT_X8R8G8B8".to_string(),
2238            ty: None,
2239            value: metadata::Value::U32(22),
2240        }));
2241
2242        let collectors: BTreeMap<String, Collector> =
2243            [("d3d9types".to_string(), a), ("mfapi".to_string(), b)].into();
2244        let members = enum_member_values(&collectors);
2245        assert_eq!(
2246            members.get("D3DFMT_X8R8G8B8").map(Vec::as_slice),
2247            Some([22].as_slice())
2248        );
2249    }
2250}