windows-bindgen 0.101.0

Code generator for Windows metadata
Documentation
use super::*;

#[derive(Clone)]
pub struct Config<'a> {
    pub bindgen: &'a Bindgen,
    pub reader: &'a Reader,
    pub plan: &'a BindingPlan,
    pub implement: Option<&'a Implements>,
    pub derive: &'a Derive,
    pub link: &'a str,
    pub namespace: &'static str,
    pub shadowed_prelude: &'a HashSet<&'static str>,
    /// Event-only delegates whose constructor and `Invoke` can be suppressed in minimal mode.
    pub event_only_delegates: &'a HashSet<TypeName>,
    /// Current `impl` target, used by `TypeName::write` to emit `Self` when possible.
    pub self_ty: Option<TypeName>,
    /// Generics of `self_ty`, used to avoid incorrect `Self` substitutions.
    pub self_generics: Vec<Type>,
    /// Pruned empty namespaces; `Cfg::write` must not emit feature gates for them.
    pub prunable: std::sync::Arc<BTreeSet<&'static str>>,
}

impl Config<'_> {
    pub fn shadowed_prelude(types: &TypeMap) -> HashSet<&'static str> {
        fn collect(record: &CppStruct, names: &mut HashSet<&'static str>) {
            if matches!(record.name, "size_of" | "align_of") {
                names.insert(record.name);
            }
            for nested in record.nested.values() {
                collect(nested, names);
            }
        }

        let mut names = HashSet::new();
        for ty in types.values().flatten() {
            if let Type::CppStruct(record) = ty {
                collect(record, &mut names);
            } else {
                let name = ty.type_name().name();
                if matches!(name, "size_of" | "align_of") {
                    names.insert(name);
                }
            }
        }
        names
    }

    /// Uses the prelude unless a selected declaration may shadow the name.
    pub fn write_mem_function(&self, name: &str) -> TokenStream {
        let ident = to_ident(name);
        if self.shadowed_prelude.contains(name) {
            quote! { ::core::mem::#ident }
        } else {
            quote! { #ident }
        }
    }

    pub fn with_namespace(&self, namespace: &'static str) -> Self {
        let mut clone = self.clone();
        clone.namespace = namespace;
        clone
    }

    /// Returns a clone carrying the given set of pruned namespaces (see [`Config::prunable`]).
    pub fn with_prunable(&self, prunable: std::sync::Arc<BTreeSet<&'static str>>) -> Self {
        let mut clone = self.clone();
        clone.prunable = prunable;
        clone
    }

    /// Returns a clone configured to emit `Self` for references to `name` (with the
    /// given generics) while generating that type's `impl` block.
    pub fn with_self_ty(&self, name: TypeName, generics: &[Type]) -> Self {
        let mut clone = self.clone();
        clone.self_ty = Some(name);
        clone.self_generics = generics.to_vec();
        clone
    }

    /// Writes the metadata architecture gate for `def`. Under `--dead-code`, a definition that
    /// selected items reach on only some architectures allows `dead_code` on the others without
    /// narrowing the gate the metadata declares.
    pub fn write_reached_arches(&self, ty: &Type, def: TypeDef) -> TokenStream {
        let own = def.arches();
        let available = arch_mask(own);
        let arches = write_arch_bits(own);
        let unused = available & !self.plan.types.reached_arches(ty);
        if self.bindgen.dead_code && unused != 0 {
            let condition = write_arch_condition(unused).unwrap();
            quote! { #arches #[cfg_attr(#condition, allow(dead_code))] }
        } else {
            arches
        }
    }

    /// Minimal bindings require `--implement`; other styles use the supplied default.
    pub fn should_implement(&self, name: TypeName, default: bool) -> bool {
        match self.implement {
            None => default && !self.bindgen.style.is_minimal(),
            Some(_) => self.plan.implemented.contains(&name),
        }
    }

    /// Returns whether a class is an explicit minimal-mode composition target.
    pub fn should_compose(&self, name: TypeName) -> bool {
        self.bindgen.compose.iter().any(|target| {
            target
                .strip_prefix(name.namespace())
                .and_then(|name| name.strip_prefix('.'))
                == Some(name.name())
        })
    }

    /// Minimal bindings emit `RuntimeType::NAME` only for implemented interfaces.
    pub fn emit_runtime_name(&self, name: TypeName) -> bool {
        !self.bindgen.style.is_minimal() || self.should_implement(name, false)
    }

    /// Emits the value-type runtime name used by non-minimal generic signatures.
    pub fn write_value_name_const(&self, type_name: TypeName) -> TokenStream {
        let type_name_bytes = Literal::byte_string(format!("{type_name}").as_bytes());
        quote! {
            const NAME: windows_core::imp::ConstBuffer = windows_core::imp::ConstBuffer::from_slice(#type_name_bytes);
        }
    }

    /// Emits `pub(crate)` under `--dead-code` so unused generated items are linted.
    pub fn item_vis(&self) -> TokenStream {
        if self.bindgen.dead_code {
            quote! { pub(crate) }
        } else {
            quote! { pub }
        }
    }

    /// Whether `ty` and its generic arguments are generated here or provided by a reference.
    pub fn provides(&self, ty: &Type) -> bool {
        self.plan.provides(ty)
    }
}

impl Config<'_> {
    #[track_caller]
    pub fn write(&self, tree: TypeTree, output: &Path) {
        if self.bindgen.layout.is_package() {
            self.write_package(&tree, output);
        } else {
            self.write_file(tree, output);
        }
    }

    #[track_caller]
    fn write_file(&self, tree: TypeTree, output: &Path) {
        let tokens = if self.bindgen.layout.is_flat() {
            self.write_flat(tree)
        } else {
            self.write_modules(&tree)
        };
        let formatted = self.format(tokens);

        write_to_file(output, formatted);
    }

    fn write_flat(&self, tree: TypeTree) -> TokenStream {
        let mut tokens = TokenStream::new();

        for ty in tree.flatten_types() {
            tokens.combine(ty.write(self));
        }

        tokens
    }

    fn write_modules(&self, tree: &TypeTree) -> TokenStream {
        let mut tokens = TokenStream::new();

        for ty in &tree.types {
            tokens.combine(ty.write(self));
        }

        for (name, tree) in &tree.nested {
            let name = to_ident(name);
            let nested = self.with_namespace(tree.namespace).write_modules(tree);
            tokens.combine(quote! { pub mod #name { #nested } });
        }

        tokens
    }
}