diff --git a/Cargo.toml b/Cargo.toml index f206b9e62e..92ea139e9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,3 +14,4 @@ exclude = [ [workspace.lints.rust] rust_2018_idioms = "warn" +unused_qualifications = "warn" diff --git a/crates/libs/bindgen/src/rdl/fmt.rs b/crates/libs/bindgen/src/rdl/fmt.rs index 8b2df36aaf..c0fe8bdcb7 100644 --- a/crates/libs/bindgen/src/rdl/fmt.rs +++ b/crates/libs/bindgen/src/rdl/fmt.rs @@ -10,7 +10,7 @@ pub struct Writer { } impl Writer { - pub fn new(file: &rdl::File) -> Self { + pub fn new(file: &File) -> Self { let mut writer = Self::default(); writer.rdl_file(file); writer @@ -37,7 +37,7 @@ impl Writer { self.newline = true; } - fn rdl_file(&mut self, file: &rdl::File) { + fn rdl_file(&mut self, file: &File) { if file.winrt { self.word("#![winrt]\n"); } else { @@ -55,7 +55,7 @@ impl Writer { } } - fn rdl_module(&mut self, module: &rdl::Module) { + fn rdl_module(&mut self, module: &Module) { self.word("mod "); self.word(module.name()); self.word(" {"); @@ -73,19 +73,19 @@ impl Writer { self.newline(); } - fn rdl_module_member(&mut self, member: &rdl::ModuleMember) { + fn rdl_module_member(&mut self, member: &ModuleMember) { match member { - rdl::ModuleMember::Module(member) => self.rdl_module(member), - rdl::ModuleMember::Interface(member) => self.rdl_interface(member), - rdl::ModuleMember::Struct(member) => self.rdl_struct(member), - rdl::ModuleMember::Enum(member) => self.rdl_enum(member), - rdl::ModuleMember::Class(member) => self.rdl_class(member), - rdl::ModuleMember::Constant(member) => self.rdl_constant(member), - rdl::ModuleMember::Function(member) => self.rdl_function(member), + ModuleMember::Module(member) => self.rdl_module(member), + ModuleMember::Interface(member) => self.rdl_interface(member), + ModuleMember::Struct(member) => self.rdl_struct(member), + ModuleMember::Enum(member) => self.rdl_enum(member), + ModuleMember::Class(member) => self.rdl_class(member), + ModuleMember::Constant(member) => self.rdl_constant(member), + ModuleMember::Function(member) => self.rdl_function(member), } } - fn rdl_class(&mut self, member: &rdl::Class) { + fn rdl_class(&mut self, member: &Class) { self.attrs(&member.attributes); self.word("class "); self.word(&member.name); @@ -117,7 +117,7 @@ impl Writer { self.newline(); } - fn rdl_interface(&mut self, member: &rdl::Interface) { + fn rdl_interface(&mut self, member: &Interface) { self.attrs(&member.attributes); self.word("interface "); self.word(&member.name); @@ -167,11 +167,11 @@ impl Writer { self.word("}"); } - fn rdl_constant(&mut self, member: &rdl::Constant) { + fn rdl_constant(&mut self, member: &Constant) { self.item_const(&member.item); } - fn rdl_function(&mut self, member: &rdl::Function) { + fn rdl_function(&mut self, member: &Function) { self.trait_item_fn(&member.item); self.word(";"); self.newline(); @@ -222,7 +222,7 @@ impl Writer { self.expr(&meta.value); } - fn rdl_struct(&mut self, member: &rdl::Struct) { + fn rdl_struct(&mut self, member: &Struct) { self.attrs(&member.attributes); self.word("struct "); @@ -244,7 +244,7 @@ impl Writer { self.word("}"); } - fn rdl_enum(&mut self, member: &rdl::Enum) { + fn rdl_enum(&mut self, member: &Enum) { self.attrs(&member.item.attrs); self.word("enum "); diff --git a/crates/libs/bindgen/src/rdl/from_reader.rs b/crates/libs/bindgen/src/rdl/from_reader.rs index 856e8a131c..e1c0241496 100644 --- a/crates/libs/bindgen/src/rdl/from_reader.rs +++ b/crates/libs/bindgen/src/rdl/from_reader.rs @@ -1,7 +1,6 @@ use super::*; -use crate::tokens::{quote, to_ident, TokenStream}; -use crate::{rdl, Error, Result, Tree}; -use metadata::*; +use crate::Result; +use tokens::{quote, to_ident, TokenStream}; pub fn from_reader(reader: &'static metadata::Reader, mut config: std::collections::BTreeMap<&str, &str>, output: &str) -> Result<()> { let dialect = match config.remove("type") { @@ -30,7 +29,7 @@ pub fn from_reader(reader: &'static metadata::Reader, mut config: std::collectio fn gen_split(writer: &Writer) -> Result<()> { let tree = Tree::new(writer.reader); - let directory = crate::directory(&writer.output); + let directory = directory(&writer.output); // TODO: parallelize for tree in tree.flatten() { @@ -86,8 +85,8 @@ impl Writer { }; let file = rdl::File::parse_str(&tokens.into_string())?; - crate::write_to_file(output, file.fmt()) - //crate::write_to_file(output, tokens.into_string()) + write_to_file(output, file.fmt()) + //write_to_file(output, tokens.into_string()) } fn tree(&self, tree: &Tree) -> TokenStream { @@ -286,8 +285,8 @@ impl Writer { // TODO: then list default interface first // Then everything else - for interface in type_def_interfaces(def, generics) { - if interface.kind == InterfaceKind::Default { + for interface in metadata::type_def_interfaces(def, generics) { + if interface.kind == metadata::InterfaceKind::Default { types.insert(0, self.ty(&interface.ty)); } else { types.push(self.ty(&interface.ty)); diff --git a/crates/libs/bindgen/src/rdl/mod.rs b/crates/libs/bindgen/src/rdl/mod.rs index dec1554cac..c74c8c04f0 100644 --- a/crates/libs/bindgen/src/rdl/mod.rs +++ b/crates/libs/bindgen/src/rdl/mod.rs @@ -68,7 +68,7 @@ pub enum ModuleMember { impl ModuleMember { pub fn name(&self) -> &str { match self { - Self::Module(module) => crate::extension(&module.namespace), + Self::Module(module) => extension(&module.namespace), Self::Interface(member) => &member.name, Self::Struct(member) => &member.name, Self::Enum(member) => &member.name, diff --git a/crates/libs/bindgen/src/rdl/to_winmd.rs b/crates/libs/bindgen/src/rdl/to_winmd.rs index d1dc65b128..efb2321168 100644 --- a/crates/libs/bindgen/src/rdl/to_winmd.rs +++ b/crates/libs/bindgen/src/rdl/to_winmd.rs @@ -1,6 +1,6 @@ use super::*; use crate::winmd::{self, writer}; -use crate::{rdl, Result}; +use crate::Result; // TODO: store span in winmd so that errors resolving type references can be traced back to file/line/column use std::collections::HashMap; @@ -9,7 +9,7 @@ use std::collections::HashMap; // TODO: this creates a temporary in-memory winmd used to treat the IDL content uniformly as metadata. // The winmd_to_winmd does the harder job of validating and producing canonical winmd for public consumption. -pub fn rdl_to_winmd(file: &rdl::File) -> Result> { +pub fn rdl_to_winmd(file: &File) -> Result> { // Local-to-qualified type names found in use declaration - e.g. "IStringable" -> "Windows.Foundation.IStringable" // This is just a convenience for the developer to shorten common references like this but would not support globs or renames. // Note that none of these are verified to be real until much later when the winmd is validated since we don't @@ -20,7 +20,7 @@ pub fn rdl_to_winmd(file: &rdl::File) -> Result> { // Types are collected here in two passes - this allows us to figure out whether a local name points to a relative type // or a type from a use declaration...? - let mut collector = HashMap::>::new(); + let mut collector = HashMap::>::new(); file.modules.iter().for_each(|module| collect_module(&mut collector, module)); @@ -36,14 +36,14 @@ pub fn rdl_to_winmd(file: &rdl::File) -> Result> { Ok(writer.into_stream()) } -fn collect_module<'a>(collector: &mut HashMap>, module: &'a rdl::Module) { +fn collect_module<'a>(collector: &mut HashMap>, module: &'a Module) { module.members.iter().for_each(|member| collect_member(collector, module, member)); } -fn collect_member<'a>(collector: &mut HashMap>, module: &'a rdl::Module, member: &'a rdl::ModuleMember) { +fn collect_member<'a>(collector: &mut HashMap>, module: &'a Module, member: &'a ModuleMember) { match member { - rdl::ModuleMember::Module(module) => collect_module(collector, module), - rdl::ModuleMember::Constant(_) | rdl::ModuleMember::Function(_) => { + ModuleMember::Module(module) => collect_module(collector, module), + ModuleMember::Constant(_) | ModuleMember::Function(_) => { collector.entry(module.namespace.to_string()).or_default().entry("Apis").or_insert(member.clone()); } _ => { @@ -52,17 +52,17 @@ fn collect_member<'a>(collector: &mut HashMap write_interface(writer, namespace, name, member), - rdl::ModuleMember::Struct(member) => write_struct(writer, namespace, name, member), - rdl::ModuleMember::Enum(member) => write_enum(writer, namespace, name, member), - rdl::ModuleMember::Class(member) => write_class(writer, namespace, name, member), + ModuleMember::Interface(member) => write_interface(writer, namespace, name, member), + ModuleMember::Struct(member) => write_struct(writer, namespace, name, member), + ModuleMember::Enum(member) => write_enum(writer, namespace, name, member), + ModuleMember::Class(member) => write_class(writer, namespace, name, member), rest => unimplemented!("{rest:?}"), } } -fn write_interface(writer: &mut winmd::Writer, namespace: &str, name: &str, member: &rdl::Interface) { +fn write_interface(writer: &mut winmd::Writer, namespace: &str, name: &str, member: &Interface) { let mut flags = metadata::TypeAttributes::Public | metadata::TypeAttributes::Interface | metadata::TypeAttributes::Abstract; if member.winrt { @@ -123,7 +123,7 @@ fn write_interface(writer: &mut winmd::Writer, namespace: &str, name: &str, memb } } -fn write_struct(writer: &mut winmd::Writer, namespace: &str, name: &str, member: &rdl::Struct) { +fn write_struct(writer: &mut winmd::Writer, namespace: &str, name: &str, member: &Struct) { let mut flags = metadata::TypeAttributes::Public | metadata::TypeAttributes::Sealed | metadata::TypeAttributes::SequentialLayout; if member.winrt { @@ -150,9 +150,9 @@ fn write_struct(writer: &mut winmd::Writer, namespace: &str, name: &str, member: } } -fn write_enum(_writer: &mut winmd::Writer, _namespace: &str, _name: &str, _member: &rdl::Enum) {} +fn write_enum(_writer: &mut winmd::Writer, _namespace: &str, _name: &str, _member: &Enum) {} -fn write_class(writer: &mut winmd::Writer, namespace: &str, name: &str, member: &rdl::Class) { +fn write_class(writer: &mut winmd::Writer, namespace: &str, name: &str, member: &Class) { let flags = metadata::TypeAttributes::Public | metadata::TypeAttributes::Sealed | metadata::TypeAttributes::WindowsRuntime; let extends = if let Some(base) = &member.base { diff --git a/crates/libs/bindgen/src/rust/cfg.rs b/crates/libs/bindgen/src/rust/cfg.rs index a6d9b47837..0c9b30c738 100644 --- a/crates/libs/bindgen/src/rust/cfg.rs +++ b/crates/libs/bindgen/src/rust/cfg.rs @@ -1,10 +1,11 @@ use super::*; +use metadata::{AsRow, HasAttributes}; #[derive(Default, Clone)] pub struct Cfg { - pub types: BTreeMap<&'static str, BTreeSet>, - pub core_types: BTreeSet, - pub arches: BTreeSet<&'static str>, + pub types: std::collections::BTreeMap<&'static str, std::collections::BTreeSet>, + pub core_types: std::collections::BTreeSet, + pub arches: std::collections::BTreeSet<&'static str>, pub implement: bool, } @@ -30,25 +31,25 @@ impl Cfg { } } -pub fn field_cfg(row: Field) -> Cfg { +pub fn field_cfg(row: metadata::Field) -> Cfg { let mut cfg = Cfg::default(); field_cfg_combine(row, None, &mut cfg); cfg } -fn field_cfg_combine(row: Field, enclosing: Option, cfg: &mut Cfg) { +fn field_cfg_combine(row: metadata::Field, enclosing: Option, cfg: &mut Cfg) { type_cfg_combine(&row.ty(enclosing), cfg) } -pub fn type_def_cfg(row: TypeDef, generics: &[Type]) -> Cfg { +pub fn type_def_cfg(row: metadata::TypeDef, generics: &[metadata::Type]) -> Cfg { let mut cfg = Cfg::default(); type_def_cfg_combine(row, generics, &mut cfg); cfg_add_attributes(&mut cfg, row); cfg } -pub fn type_def_cfg_impl(def: TypeDef, generics: &[Type]) -> Cfg { +pub fn type_def_cfg_impl(def: metadata::TypeDef, generics: &[metadata::Type]) -> Cfg { let mut cfg = Cfg { implement: true, ..Default::default() }; - fn combine(def: TypeDef, generics: &[Type], cfg: &mut Cfg) { + fn combine(def: metadata::TypeDef, generics: &[metadata::Type], cfg: &mut Cfg) { type_def_cfg_combine(def, generics, cfg); for method in def.methods() { @@ -58,8 +59,8 @@ pub fn type_def_cfg_impl(def: TypeDef, generics: &[Type]) -> Cfg { combine(def, generics, &mut cfg); - for interface in type_interfaces(&Type::TypeDef(def, generics.to_vec())) { - if let Type::TypeDef(def, generics) = interface.ty { + for interface in metadata::type_interfaces(&metadata::Type::TypeDef(def, generics.to_vec())) { + if let metadata::Type::TypeDef(def, generics) = interface.ty { combine(def, &generics, &mut cfg); } } @@ -67,7 +68,7 @@ pub fn type_def_cfg_impl(def: TypeDef, generics: &[Type]) -> Cfg { cfg_add_attributes(&mut cfg, def); cfg } -pub fn type_def_cfg_combine(row: TypeDef, generics: &[Type], cfg: &mut Cfg) { +pub fn type_def_cfg_combine(row: metadata::TypeDef, generics: &[metadata::Type], cfg: &mut Cfg) { let type_name = row.type_name(); for generic in generics { @@ -76,21 +77,21 @@ pub fn type_def_cfg_combine(row: TypeDef, generics: &[Type], cfg: &mut Cfg) { if cfg.types.entry(type_name.namespace).or_default().insert(row) { match row.kind() { - TypeKind::Class => { - if let Some(default_interface) = type_def_default_interface(row) { + metadata::TypeKind::Class => { + if let Some(default_interface) = metadata::type_def_default_interface(row) { type_cfg_combine(&default_interface, cfg); } } - TypeKind::Interface => { - if !row.flags().contains(TypeAttributes::WindowsRuntime) { - for def in type_def_vtables(row) { - if let Type::TypeDef(def, _) = def { + metadata::TypeKind::Interface => { + if !row.flags().contains(metadata::TypeAttributes::WindowsRuntime) { + for def in metadata::type_def_vtables(row) { + if let metadata::Type::TypeDef(def, _) = def { cfg.add_feature(def.namespace()); } } } } - TypeKind::Struct => { + metadata::TypeKind::Struct => { row.fields().for_each(|field| field_cfg_combine(field, Some(row), cfg)); if !type_name.namespace.is_empty() { for def in row.reader().get_type_def(type_name.namespace, type_name.name) { @@ -100,29 +101,29 @@ pub fn type_def_cfg_combine(row: TypeDef, generics: &[Type], cfg: &mut Cfg) { } } } - TypeKind::Delegate => signature_cfg_combine(&type_def_invoke_method(row).signature(generics), cfg), + metadata::TypeKind::Delegate => signature_cfg_combine(&metadata::type_def_invoke_method(row).signature(generics), cfg), _ => {} } } } -pub fn signature_cfg(method: MethodDef) -> Cfg { +pub fn signature_cfg(method: metadata::MethodDef) -> Cfg { let mut cfg = Cfg::default(); signature_cfg_combine(&method.signature(&[]), &mut cfg); cfg_add_attributes(&mut cfg, method); cfg } -fn signature_cfg_combine(signature: &MethodDefSig, cfg: &mut Cfg) { +fn signature_cfg_combine(signature: &metadata::MethodDefSig, cfg: &mut Cfg) { type_cfg_combine(&signature.return_type, cfg); signature.params.iter().for_each(|param| type_cfg_combine(param, cfg)); } -fn cfg_add_attributes>(cfg: &mut Cfg, row: R) { +fn cfg_add_attributes>(cfg: &mut Cfg, row: R) { for attribute in row.attributes() { match attribute.name() { "SupportedArchitectureAttribute" => { - if let Some((_, Value::EnumDef(_, value))) = attribute.args().first() { - if let Value::I32(value) = **value { + if let Some((_, metadata::Value::EnumDef(_, value))) = attribute.args().first() { + if let metadata::Value::I32(value) = **value { if value & 1 == 1 { cfg.arches.insert("x86"); } @@ -143,20 +144,20 @@ fn cfg_add_attributes>(cfg: &mut Cfg, row: R) { } } -pub fn type_cfg(ty: &Type) -> Cfg { +pub fn type_cfg(ty: &metadata::Type) -> Cfg { let mut cfg = Cfg::default(); type_cfg_combine(ty, &mut cfg); cfg } -fn type_cfg_combine(ty: &Type, cfg: &mut Cfg) { +fn type_cfg_combine(ty: &metadata::Type, cfg: &mut Cfg) { match ty { - Type::TypeDef(row, generics) => type_def_cfg_combine(*row, generics, cfg), - Type::Win32Array(ty, _) => type_cfg_combine(ty, cfg), - Type::ConstPtr(ty, _) => type_cfg_combine(ty, cfg), - Type::MutPtr(ty, _) => type_cfg_combine(ty, cfg), - Type::WinrtArray(ty) => type_cfg_combine(ty, cfg), - Type::WinrtArrayRef(ty) => type_cfg_combine(ty, cfg), + metadata::Type::TypeDef(row, generics) => type_def_cfg_combine(*row, generics, cfg), + metadata::Type::Win32Array(ty, _) => type_cfg_combine(ty, cfg), + metadata::Type::ConstPtr(ty, _) => type_cfg_combine(ty, cfg), + metadata::Type::MutPtr(ty, _) => type_cfg_combine(ty, cfg), + metadata::Type::WinrtArray(ty) => type_cfg_combine(ty, cfg), + metadata::Type::WinrtArrayRef(ty) => type_cfg_combine(ty, cfg), ty => _ = cfg.core_types.insert(ty.clone()), } } diff --git a/crates/libs/bindgen/src/rust/classes.rs b/crates/libs/bindgen/src/rust/classes.rs index d30cde31a2..bba378a668 100644 --- a/crates/libs/bindgen/src/rust/classes.rs +++ b/crates/libs/bindgen/src/rust/classes.rs @@ -1,6 +1,7 @@ use super::*; +use metadata::HasAttributes; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { if writer.sys { if def.interface_impls().next().is_some() { let name = to_ident(def.name()); @@ -15,22 +16,22 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { } } -fn gen_class(writer: &Writer, def: TypeDef) -> TokenStream { - if def.extends() == Some(TypeName::Attribute) { +fn gen_class(writer: &Writer, def: metadata::TypeDef) -> TokenStream { + if def.extends() == Some(metadata::TypeName::Attribute) { return TokenStream::new(); } let name = to_ident(def.name()); - let interfaces = type_interfaces(&Type::TypeDef(def, Vec::new())); + let interfaces = metadata::type_interfaces(&metadata::Type::TypeDef(def, Vec::new())); let mut methods = quote! {}; let mut method_names = MethodNames::new(); - let cfg = type_def_cfg(def, &[]); + let cfg = cfg::type_def_cfg(def, &[]); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); for interface in &interfaces { - if let Type::TypeDef(def, generics) = &interface.ty { + if let metadata::Type::TypeDef(def, generics) = &interface.ty { let mut virtual_names = MethodNames::new(); for method in def.methods() { @@ -40,11 +41,11 @@ fn gen_class(writer: &Writer, def: TypeDef) -> TokenStream { } let factories = interfaces.iter().filter_map(|interface| match interface.kind { - InterfaceKind::Static => { - if let Type::TypeDef(def, generics) = &interface.ty { + metadata::InterfaceKind::Static => { + if let metadata::Type::TypeDef(def, generics) = &interface.ty { if def.methods().next().is_some() { let interface_type = writer.type_name(&interface.ty); - let features = writer.cfg_features(&type_def_cfg(*def, generics)); + let features = writer.cfg_features(&cfg::type_def_cfg(*def, generics)); return Some(quote! { #[doc(hidden)] @@ -121,7 +122,7 @@ fn gen_class(writer: &Writer, def: TypeDef) -> TokenStream { } } -fn gen_conversions(writer: &Writer, def: TypeDef, name: &TokenStream, interfaces: &[Interface], cfg: &Cfg) -> TokenStream { +fn gen_conversions(writer: &Writer, def: metadata::TypeDef, name: &TokenStream, interfaces: &[metadata::Interface], cfg: &cfg::Cfg) -> TokenStream { let features = writer.cfg_features(cfg); let mut tokens = quote! { #features @@ -133,12 +134,12 @@ fn gen_conversions(writer: &Writer, def: TypeDef, name: &TokenStream, interfaces continue; } - if interface.kind != InterfaceKind::Default && interface.kind != InterfaceKind::None && interface.kind != InterfaceKind::Base { + if interface.kind != metadata::InterfaceKind::Default && interface.kind != metadata::InterfaceKind::None && interface.kind != metadata::InterfaceKind::Base { continue; } let into = writer.type_name(&interface.ty); - let features = writer.cfg_features(&cfg.union(&type_cfg(&interface.ty))); + let features = writer.cfg_features(&cfg.union(&cfg::type_cfg(&interface.ty))); tokens.combine("e! { #features @@ -146,9 +147,9 @@ fn gen_conversions(writer: &Writer, def: TypeDef, name: &TokenStream, interfaces }); } - for def in type_def_bases(def) { + for def in metadata::type_def_bases(def) { let into = writer.type_def_name(def, &[]); - let features = writer.cfg_features(&cfg.union(&type_def_cfg(def, &[]))); + let features = writer.cfg_features(&cfg.union(&cfg::type_def_cfg(def, &[]))); tokens.combine("e! { #features @@ -159,10 +160,10 @@ fn gen_conversions(writer: &Writer, def: TypeDef, name: &TokenStream, interfaces tokens } -fn type_def_has_default_constructor(row: TypeDef) -> bool { +fn type_def_has_default_constructor(row: metadata::TypeDef) -> bool { for attribute in row.attributes() { if attribute.name() == "ActivatableAttribute" { - if attribute.args().iter().any(|arg| matches!(arg.1, Value::TypeName(_))) { + if attribute.args().iter().any(|arg| matches!(arg.1, metadata::Value::TypeName(_))) { continue; } else { return true; @@ -172,9 +173,9 @@ fn type_def_has_default_constructor(row: TypeDef) -> bool { false } -fn type_is_exclusive(ty: &Type) -> bool { +fn type_is_exclusive(ty: &metadata::Type) -> bool { match ty { - Type::TypeDef(row, _) => type_def_is_exclusive(*row), + metadata::Type::TypeDef(row, _) => metadata::type_def_is_exclusive(*row), _ => false, } } diff --git a/crates/libs/bindgen/src/rust/com_methods.rs b/crates/libs/bindgen/src/rust/com_methods.rs index 7a9e64d74d..15a438cd7b 100644 --- a/crates/libs/bindgen/src/rust/com_methods.rs +++ b/crates/libs/bindgen/src/rust/com_methods.rs @@ -1,18 +1,18 @@ use super::*; -pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: MethodDef, method_names: &mut MethodNames, virtual_names: &mut MethodNames, base_count: usize) -> TokenStream { - let signature = method_def_signature(def.namespace(), method, &[]); +pub fn writer(writer: &Writer, def: metadata::TypeDef, kind: metadata::InterfaceKind, method: metadata::MethodDef, method_names: &mut MethodNames, virtual_names: &mut MethodNames, base_count: usize) -> TokenStream { + let signature = metadata::method_def_signature(def.namespace(), method, &[]); let name = method_names.add(method); let vname = virtual_names.add(method); let generics = writer.constraint_generics(&signature.params); let where_clause = writer.where_clause(&signature.params); - let mut cfg = signature_cfg(method); + let mut cfg = cfg::signature_cfg(method); cfg.add_feature(def.namespace()); let doc = writer.cfg_method_doc(&cfg); let features = writer.cfg_features(&cfg); - if kind == InterfaceKind::None { + if kind == metadata::InterfaceKind::None { return quote! {}; } @@ -24,7 +24,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method let kind = signature.kind(); match kind { - SignatureKind::Query(_) => { + metadata::SignatureKind::Query(_) => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let generics = expand_generics(generics, quote!(T)); @@ -39,7 +39,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::QueryOptional(_) => { + metadata::SignatureKind::QueryOptional(_) => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let generics = expand_generics(generics, quote!(T)); @@ -53,7 +53,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::ResultValue => { + metadata::SignatureKind::ResultValue => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let return_type = signature.params[signature.params.len() - 1].ty.deref(); @@ -68,7 +68,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::ResultVoid => { + metadata::SignatureKind::ResultVoid => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); @@ -80,11 +80,11 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::ReturnValue => { + metadata::SignatureKind::ReturnValue => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let return_type = signature.params[signature.params.len() - 1].ty.deref(); - let is_nullable = type_is_nullable(&return_type); + let is_nullable = metadata::type_is_nullable(&return_type); let return_type = writer.type_name(&return_type); if is_nullable { @@ -109,7 +109,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::ReturnStruct => { + metadata::SignatureKind::ReturnStruct => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let return_type = writer.type_name(&signature.return_type); @@ -124,7 +124,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::PreserveSig => { + metadata::SignatureKind::PreserveSig => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let return_type = writer.return_sig(&signature); @@ -137,7 +137,7 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } } - SignatureKind::ReturnVoid => { + metadata::SignatureKind::ReturnVoid => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); @@ -152,9 +152,9 @@ pub fn writer(writer: &Writer, def: TypeDef, kind: InterfaceKind, method: Method } } -pub fn gen_upcall(writer: &Writer, sig: &Signature, inner: TokenStream) -> TokenStream { +pub fn gen_upcall(writer: &Writer, sig: &metadata::Signature, inner: TokenStream) -> TokenStream { match sig.kind() { - SignatureKind::ResultValue => { + metadata::SignatureKind::ResultValue => { let invoke_args = sig.params[..sig.params.len() - 1].iter().map(|param| gen_win32_invoke_arg(writer, param)); let result = writer.param_name(sig.params[sig.params.len() - 1].def); @@ -170,14 +170,14 @@ pub fn gen_upcall(writer: &Writer, sig: &Signature, inner: TokenStream) -> Token } } } - SignatureKind::Query(_) | SignatureKind::QueryOptional(_) | SignatureKind::ResultVoid => { + metadata::SignatureKind::Query(_) | metadata::SignatureKind::QueryOptional(_) | metadata::SignatureKind::ResultVoid => { let invoke_args = sig.params.iter().map(|param| gen_win32_invoke_arg(writer, param)); quote! { #inner(#(#invoke_args,)*).into() } } - SignatureKind::ReturnStruct => { + metadata::SignatureKind::ReturnStruct => { let invoke_args = sig.params.iter().map(|param| gen_win32_invoke_arg(writer, param)); quote! { @@ -194,12 +194,12 @@ pub fn gen_upcall(writer: &Writer, sig: &Signature, inner: TokenStream) -> Token } } -fn gen_win32_invoke_arg(writer: &Writer, param: &SignatureParam) -> TokenStream { +fn gen_win32_invoke_arg(writer: &Writer, param: &metadata::SignatureParam) -> TokenStream { let name = writer.param_name(param.def); - if param.def.flags().contains(ParamAttributes::In) && type_is_nullable(¶m.ty) { + if param.def.flags().contains(metadata::ParamAttributes::In) && metadata::type_is_nullable(¶m.ty) { quote! { ::windows_core::from_raw_borrowed(&#name) } - } else if (!param.ty.is_pointer() && type_is_nullable(¶m.ty)) || (param.def.flags().contains(ParamAttributes::In) && !type_is_primitive(¶m.ty)) { + } else if (!param.ty.is_pointer() && metadata::type_is_nullable(¶m.ty)) || (param.def.flags().contains(metadata::ParamAttributes::In) && !metadata::type_is_primitive(¶m.ty)) { quote! { ::core::mem::transmute(&#name) } } else { quote! { ::core::mem::transmute_copy(&#name) } diff --git a/crates/libs/bindgen/src/rust/constants.rs b/crates/libs/bindgen/src/rust/constants.rs index e537c84a77..3d5e4dd845 100644 --- a/crates/libs/bindgen/src/rust/constants.rs +++ b/crates/libs/bindgen/src/rust/constants.rs @@ -1,9 +1,10 @@ use super::*; +use metadata::HasAttributes; -pub fn writer(writer: &Writer, def: Field) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::Field) -> TokenStream { let name = to_ident(def.name()); let ty = def.ty(None).to_const_type(); - let cfg = field_cfg(def); + let cfg = cfg::field_cfg(def); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); @@ -11,7 +12,7 @@ pub fn writer(writer: &Writer, def: Field) -> TokenStream { let constant_type = constant.ty(); if ty == constant_type { - if ty == Type::String { + if ty == metadata::Type::String { let crate_name = writer.crate_name(); if field_is_ansi(def) { let value = writer.value(&constant.value()); @@ -63,7 +64,7 @@ pub fn writer(writer: &Writer, def: Field) -> TokenStream { } } else if let Some(guid) = field_guid(def) { let value = writer.guid(&guid); - let guid = writer.type_name(&Type::GUID); + let guid = writer.type_name(&metadata::Type::GUID); quote! { #doc pub const #name: #guid = #value; @@ -81,14 +82,14 @@ pub fn writer(writer: &Writer, def: Field) -> TokenStream { } } -fn initializer(writer: &Writer, def: Field) -> Option { +fn initializer(writer: &Writer, def: metadata::Field) -> Option { let Some(value) = constant(def) else { return None; }; let mut input = value.as_str(); - let Type::TypeDef(def, _) = def.ty(None) else { + let metadata::Type::TypeDef(def, _) = def.ty(None) else { unimplemented!(); }; @@ -103,16 +104,16 @@ fn initializer(writer: &Writer, def: Field) -> Option { Some(result) } -fn field_initializer<'a>(writer: &Writer, field: Field, input: &'a str) -> (TokenStream, &'a str) { +fn field_initializer<'a>(writer: &Writer, field: metadata::Field, input: &'a str) -> (TokenStream, &'a str) { let name = to_ident(field.name()); match field.ty(None) { - Type::GUID => { + metadata::Type::GUID => { let (literals, rest) = read_literal_array(input, 11); - let value = writer.guid(&Guid::from_string_args(&literals)); + let value = writer.guid(&metadata::Guid::from_string_args(&literals)); (quote! { #name: #value, }, rest) } - Type::Win32Array(_, len) => { + metadata::Type::Win32Array(_, len) => { let (literals, rest) = read_literal_array(input, len); let literals = literals.iter().map(|literal| TokenStream::from(*literal)); (quote! { #name: [#(#literals,)*], }, rest) @@ -125,11 +126,11 @@ fn field_initializer<'a>(writer: &Writer, field: Field, input: &'a str) -> (Toke } } -fn constant(def: Field) -> Option { +fn constant(def: metadata::Field) -> Option { def.find_attribute("ConstantAttribute").map(|attribute| { let args = attribute.args(); match &args[0].1 { - Value::String(value) => value.clone(), + metadata::Value::String(value) => value.clone(), rest => unimplemented!("{rest:?}"), } }) @@ -182,26 +183,26 @@ fn read_literal_array(input: &str, len: usize) -> (Vec<&str>, &str) { (result, read_token(input, b'}')) } -fn field_guid(row: Field) -> Option { - row.find_attribute("GuidAttribute").map(|attribute| Guid::from_args(&attribute.args())) +fn field_guid(row: metadata::Field) -> Option { + row.find_attribute("GuidAttribute").map(|attribute| metadata::Guid::from_args(&attribute.args())) } -fn field_is_ansi(row: Field) -> bool { - row.find_attribute("NativeEncodingAttribute").is_some_and(|attribute| matches!(attribute.args().first(), Some((_, Value::String(encoding))) if encoding == "ansi")) +fn field_is_ansi(row: metadata::Field) -> bool { + row.find_attribute("NativeEncodingAttribute").is_some_and(|attribute| matches!(attribute.args().first(), Some((_, metadata::Value::String(encoding))) if encoding == "ansi")) } -fn type_has_replacement(ty: &Type) -> bool { +fn type_has_replacement(ty: &metadata::Type) -> bool { match ty { - Type::HRESULT | Type::PCSTR | Type::PCWSTR => true, - Type::TypeDef(row, _) => type_def_is_handle(*row) || row.kind() == TypeKind::Enum, + metadata::Type::HRESULT | metadata::Type::PCSTR | metadata::Type::PCWSTR => true, + metadata::Type::TypeDef(row, _) => metadata::type_def_is_handle(*row) || row.kind() == metadata::TypeKind::Enum, _ => false, } } -fn type_underlying_type(ty: &Type) -> Type { +fn type_underlying_type(ty: &metadata::Type) -> metadata::Type { match ty { - Type::TypeDef(row, _) => row.underlying_type(), - Type::HRESULT => Type::I32, + metadata::Type::TypeDef(row, _) => row.underlying_type(), + metadata::Type::HRESULT => metadata::Type::I32, _ => ty.clone(), } } diff --git a/crates/libs/bindgen/src/rust/delegates.rs b/crates/libs/bindgen/src/rust/delegates.rs index 479d8db622..36f3f8a560 100644 --- a/crates/libs/bindgen/src/rust/delegates.rs +++ b/crates/libs/bindgen/src/rust/delegates.rs @@ -1,21 +1,21 @@ use super::*; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { - if def.flags().contains(TypeAttributes::WindowsRuntime) { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { gen_delegate(writer, def) } else { gen_callback(writer, def) } } -fn gen_callback(writer: &Writer, def: TypeDef) -> TokenStream { +fn gen_callback(writer: &Writer, def: metadata::TypeDef) -> TokenStream { let name = to_ident(def.name()); - let method = type_def_invoke_method(def); + let method = metadata::type_def_invoke_method(def); - let signature = method_def_signature(def.namespace(), method, &[]); + let signature = metadata::method_def_signature(def.namespace(), method, &[]); let return_type = writer.return_sig(&signature); - let cfg = type_def_cfg(def, &[]); + let cfg = cfg::type_def_cfg(def, &[]); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); @@ -32,7 +32,7 @@ fn gen_callback(writer: &Writer, def: TypeDef) -> TokenStream { } } -fn gen_delegate(writer: &Writer, def: TypeDef) -> TokenStream { +fn gen_delegate(writer: &Writer, def: metadata::TypeDef) -> TokenStream { if writer.sys { let name = to_ident(def.name()); quote! { @@ -43,29 +43,29 @@ fn gen_delegate(writer: &Writer, def: TypeDef) -> TokenStream { } } -fn gen_win_delegate(writer: &Writer, def: TypeDef) -> TokenStream { +fn gen_win_delegate(writer: &Writer, def: metadata::TypeDef) -> TokenStream { let name = to_ident(def.name()); let vtbl = name.join("_Vtbl"); let boxed = name.join("Box"); - let generics = &type_def_generics(def); + let generics = &metadata::type_def_generics(def); let phantoms = writer.generic_phantoms(generics); let named_phantoms = writer.generic_named_phantoms(generics); let constraints = writer.generic_constraints(generics); let generic_names = writer.generic_names(generics); let ident = writer.type_def_name(def, generics); - let method = type_def_invoke_method(def); + let method = metadata::type_def_invoke_method(def); - let signature = method_def_signature(def.namespace(), method, generics); + let signature = metadata::method_def_signature(def.namespace(), method, generics); let fn_constraint = gen_fn_constraint(writer, def, &signature); - let cfg = type_def_cfg(def, generics); + let cfg = cfg::type_def_cfg(def, generics); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); let vtbl_signature = writer.vtbl_signature(def, generics, &signature); - let invoke = winrt_methods::writer(writer, def, generics, InterfaceKind::Default, method, &mut MethodNames::new(), &mut MethodNames::new()); + let invoke = winrt_methods::writer(writer, def, generics, metadata::InterfaceKind::Default, method, &mut MethodNames::new(), &mut MethodNames::new()); let invoke_upcall = winrt_methods::gen_upcall(writer, &signature, quote! { ((*this).invoke) }); let mut tokens = quote! { @@ -153,7 +153,7 @@ fn gen_win_delegate(writer: &Writer, def: TypeDef) -> TokenStream { tokens } -fn gen_fn_constraint(writer: &Writer, def: TypeDef, signature: &Signature) -> TokenStream { +fn gen_fn_constraint(writer: &Writer, def: metadata::TypeDef, signature: &metadata::Signature) -> TokenStream { let signature = writer.impl_signature(def, signature); quote! { F: FnMut #signature + ::core::marker::Send + 'static } diff --git a/crates/libs/bindgen/src/rust/enums.rs b/crates/libs/bindgen/src/rust/enums.rs index 3039aebd0a..86dbc854ff 100644 --- a/crates/libs/bindgen/src/rust/enums.rs +++ b/crates/libs/bindgen/src/rust/enums.rs @@ -1,22 +1,23 @@ use super::*; +use metadata::HasAttributes; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { let type_name = def.type_name(); let ident = to_ident(type_name.name); let underlying_type = def.underlying_type(); let underlying_type = writer.type_name(&underlying_type); // TODO: unscoped enums should be removed from metadata - let is_scoped = def.flags().contains(TypeAttributes::WindowsRuntime) || def.has_attribute("ScopedEnumAttribute"); + let is_scoped = def.flags().contains(metadata::TypeAttributes::WindowsRuntime) || def.has_attribute("ScopedEnumAttribute"); - let cfg = type_def_cfg(def, &[]); + let cfg = cfg::type_def_cfg(def, &[]); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); let fields: Vec<(TokenStream, TokenStream)> = def .fields() .filter_map(|field| { - if field.flags().contains(FieldAttributes::Literal) { + if field.flags().contains(metadata::FieldAttributes::Literal) { let field_name = to_ident(field.name()); let constant = field.constant().unwrap(); let value = writer.value(&constant.value()); @@ -110,7 +111,7 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { // Win32 enums use the Flags attribute. WinRT enums don't have the Flags attribute but are paritioned merely based // on whether they are signed. // TODO: Win32 metadata should just follow WinRT's example here. - let type_def_is_flags = def.has_attribute("FlagsAttribute") || (def.flags().contains(TypeAttributes::WindowsRuntime) && def.underlying_type() == Type::U32); + let type_def_is_flags = def.has_attribute("FlagsAttribute") || (def.flags().contains(metadata::TypeAttributes::WindowsRuntime) && def.underlying_type() == metadata::Type::U32); if type_def_is_flags { tokens.combine("e! { @@ -159,8 +160,8 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { }); } - if def.flags().contains(TypeAttributes::WindowsRuntime) { - let signature = Literal::byte_string(type_def_signature(def, &[]).as_bytes()); + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { + let signature = Literal::byte_string(metadata::type_def_signature(def, &[]).as_bytes()); tokens.combine("e! { #features diff --git a/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/Iterable.rs b/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/Iterable.rs index 6bed10d68f..f004131c94 100644 --- a/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/Iterable.rs +++ b/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/Iterable.rs @@ -2,15 +2,15 @@ struct StockIterable where T: ::windows_core::RuntimeType + 'static, - >::Default: ::std::clone::Clone, + >::Default: Clone, { - values: std::vec::Vec, + values: Vec, } impl IIterable_Impl for StockIterable where T: ::windows_core::RuntimeType, - >::Default: ::std::clone::Clone, + >::Default: Clone, { fn First(&self) -> ::windows_core::Result> { unsafe { @@ -29,7 +29,7 @@ where struct StockIterator where T: ::windows_core::RuntimeType + 'static, - >::Default: ::std::clone::Clone, + >::Default: Clone, { owner: IIterable, current: ::std::sync::atomic::AtomicUsize, @@ -38,7 +38,7 @@ where impl IIterator_Impl for StockIterator where T: ::windows_core::RuntimeType, - >::Default: ::std::clone::Clone, + >::Default: Clone, { fn Current(&self) -> ::windows_core::Result { let owner: &StockIterable = unsafe { ::windows_core::AsImpl::as_impl(&self.owner) }; @@ -83,13 +83,13 @@ where } } -impl ::core::convert::TryFrom<::std::vec::Vec> for IIterable +impl ::core::convert::TryFrom> for IIterable where T: ::windows_core::RuntimeType, - >::Default: ::std::clone::Clone, + >::Default: Clone, { type Error = ::windows_core::Error; - fn try_from(values: ::std::vec::Vec) -> ::windows_core::Result { + fn try_from(values: Vec) -> ::windows_core::Result { // TODO: should provide a fallible try_into or more explicit allocator Ok(StockIterable { values }.into()) } diff --git a/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/MapView.rs b/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/MapView.rs index 9176b5d903..ec11504d54 100644 --- a/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/MapView.rs +++ b/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/MapView.rs @@ -3,8 +3,8 @@ struct StockMapView where K: ::windows_core::RuntimeType + 'static, V: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { map: std::collections::BTreeMap, } @@ -13,8 +13,8 @@ impl IIterable_Impl> for StockMapView where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { fn First(&self) -> ::windows_core::Result>> { unsafe { @@ -33,8 +33,8 @@ impl IMapView_Impl for StockMapView where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { fn Lookup(&self, key: &K::Default) -> ::windows_core::Result { let value = self @@ -51,8 +51,8 @@ where } fn Split( &self, - first: &mut std::option::Option>, - second: &mut std::option::Option>, + first: &mut Option>, + second: &mut Option>, ) -> ::windows_core::Result<()> { *first = None; *second = None; @@ -65,8 +65,8 @@ struct StockMapViewIterator<'a, K, V> where K: ::windows_core::RuntimeType + 'static, V: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { _owner: IIterable>, current: ::std::sync::RwLock>, @@ -76,8 +76,8 @@ impl<'a, K, V> IIterator_Impl> for StockMapViewIterator<'a, where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { fn Current(&self) -> ::windows_core::Result> { let mut current = self.current.read().unwrap().clone().peekable(); @@ -134,8 +134,8 @@ struct StockKeyValuePair where K: ::windows_core::RuntimeType + 'static, V: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone, - >::Default: std::clone::Clone, + >::Default: Clone, + >::Default: Clone, { key: K::Default, value: V::Default, @@ -145,8 +145,8 @@ impl IKeyValuePair_Impl for StockKeyValuePair where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone, - >::Default: std::clone::Clone, + >::Default: Clone, + >::Default: Clone, { fn Key(&self) -> ::windows_core::Result { K::from_default(&self.key) @@ -161,8 +161,8 @@ impl ::core::convert::TryFrom>::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { type Error = ::windows_core::Error; fn try_from( diff --git a/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/VectorView.rs b/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/VectorView.rs index 561681b167..f247cc16b2 100644 --- a/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/VectorView.rs +++ b/crates/libs/bindgen/src/rust/extensions/impl/Foundation/Collections/VectorView.rs @@ -2,15 +2,15 @@ struct StockVectorView where T: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { - values: std::vec::Vec, + values: Vec, } impl IIterable_Impl for StockVectorView where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { fn First(&self) -> ::windows_core::Result> { unsafe { @@ -28,7 +28,7 @@ where impl IVectorView_Impl for StockVectorView where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { fn GetAt(&self, index: u32) -> ::windows_core::Result { let item = self @@ -65,7 +65,7 @@ where struct StockVectorViewIterator where T: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { owner: IIterable, current: ::std::sync::atomic::AtomicUsize, @@ -74,7 +74,7 @@ where impl IIterator_Impl for StockVectorViewIterator where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { fn Current(&self) -> ::windows_core::Result { let owner: &StockVectorView = unsafe { ::windows_core::AsImpl::as_impl(&self.owner) }; @@ -119,13 +119,13 @@ where } } -impl ::core::convert::TryFrom<::std::vec::Vec> for IVectorView +impl ::core::convert::TryFrom> for IVectorView where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { type Error = ::windows_core::Error; - fn try_from(values: ::std::vec::Vec) -> ::windows_core::Result { + fn try_from(values: Vec) -> ::windows_core::Result { // TODO: should provide a fallible try_into or more explicit allocator Ok(StockVectorView { values }.into()) } diff --git a/crates/libs/bindgen/src/rust/functions.rs b/crates/libs/bindgen/src/rust/functions.rs index 82199866a1..17ed31021f 100644 --- a/crates/libs/bindgen/src/rust/functions.rs +++ b/crates/libs/bindgen/src/rust/functions.rs @@ -1,6 +1,7 @@ use super::*; +use metadata::HasAttributes; -pub fn writer(writer: &Writer, namespace: &str, def: MethodDef) -> TokenStream { +pub fn writer(writer: &Writer, namespace: &str, def: metadata::MethodDef) -> TokenStream { // TODO: remove inline functions from metadata if def.module_name() == "forceinline" { return quote! {}; @@ -20,28 +21,28 @@ pub fn writer(writer: &Writer, namespace: &str, def: MethodDef) -> TokenStream { } } -fn gen_sys_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenStream { - let signature = method_def_signature(namespace, def, &[]); - let cfg = signature_cfg(def); +fn gen_sys_function(writer: &Writer, namespace: &str, def: metadata::MethodDef) -> TokenStream { + let signature = metadata::method_def_signature(namespace, def, &[]); + let cfg = cfg::signature_cfg(def); let mut tokens = writer.cfg_features(&cfg); tokens.combine(&gen_link(writer, namespace, &signature, &cfg)); tokens } -fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenStream { +fn gen_win_function(writer: &Writer, namespace: &str, def: metadata::MethodDef) -> TokenStream { let name = to_ident(def.name()); - let signature = method_def_signature(namespace, def, &[]); + let signature = metadata::method_def_signature(namespace, def, &[]); let generics = writer.constraint_generics(&signature.params); let where_clause = writer.where_clause(&signature.params); let abi_return_type = writer.return_sig(&signature); - let cfg = signature_cfg(def); + let cfg = cfg::signature_cfg(def); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); let link = gen_link(writer, namespace, &signature, &cfg); let kind = signature.kind(); match kind { - SignatureKind::Query(_) => { + metadata::SignatureKind::Query(_) => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let generics = expand_generics(generics, quote!(T)); @@ -58,7 +59,7 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } } - SignatureKind::QueryOptional(_) => { + metadata::SignatureKind::QueryOptional(_) => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let generics = expand_generics(generics, quote!(T)); @@ -74,7 +75,7 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } } - SignatureKind::ResultValue => { + metadata::SignatureKind::ResultValue => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let return_type = signature.params[signature.params.len() - 1].ty.deref(); @@ -91,7 +92,7 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } } - SignatureKind::ResultVoid => { + metadata::SignatureKind::ResultVoid => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); @@ -105,11 +106,11 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } } - SignatureKind::ReturnValue => { + metadata::SignatureKind::ReturnValue => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let return_type = signature.params[signature.params.len() - 1].ty.deref(); - let is_nullable = type_is_nullable(&return_type); + let is_nullable = metadata::type_is_nullable(&return_type); let return_type = writer.type_name(&return_type); if is_nullable { @@ -138,7 +139,7 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } } - SignatureKind::ReturnStruct | SignatureKind::PreserveSig => { + metadata::SignatureKind::ReturnStruct | metadata::SignatureKind::PreserveSig => { if handle_last_error(def, &signature) { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); @@ -169,7 +170,7 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } } - SignatureKind::ReturnVoid => { + metadata::SignatureKind::ReturnVoid => { let args = writer.win32_args(&signature.params, kind); let params = writer.win32_params(&signature.params, kind); let does_not_return = does_not_return(def); @@ -187,7 +188,7 @@ fn gen_win_function(writer: &Writer, namespace: &str, def: MethodDef) -> TokenSt } } -fn gen_link(writer: &Writer, namespace: &str, signature: &Signature, cfg: &Cfg) -> TokenStream { +fn gen_link(writer: &Writer, namespace: &str, signature: &metadata::Signature, cfg: &cfg::Cfg) -> TokenStream { let name = signature.def.name(); let ident = to_ident(name); let library = signature.def.module_name(); @@ -203,13 +204,13 @@ fn gen_link(writer: &Writer, namespace: &str, signature: &Signature, cfg: &Cfg) let params = signature.params.iter().map(|p| { let name = writer.param_name(p.def); - let tokens = if p.kind == SignatureParamKind::ValueType { writer.type_default_name(&p.ty) } else { writer.type_abi_name(&p.ty) }; + let tokens = if p.kind == metadata::SignatureParamKind::ValueType { writer.type_default_name(&p.ty) } else { writer.type_abi_name(&p.ty) }; quote! { #name: #tokens } }); let return_type = writer.return_sig(signature); - let vararg = if writer.sys && signature.call_flags.contains(MethodCallAttributes::VARARG) { + let vararg = if writer.sys && signature.call_flags.contains(metadata::MethodCallAttributes::VARARG) { "...".into() } else { quote! {} @@ -240,7 +241,7 @@ fn gen_link(writer: &Writer, namespace: &str, signature: &Signature, cfg: &Cfg) } } -fn does_not_return(def: MethodDef) -> TokenStream { +fn does_not_return(def: metadata::MethodDef) -> TokenStream { if def.has_attribute("DoesNotReturnAttribute") { quote! { -> ! } } else { @@ -248,15 +249,15 @@ fn does_not_return(def: MethodDef) -> TokenStream { } } -fn handle_last_error(def: MethodDef, signature: &Signature) -> bool { +fn handle_last_error(def: metadata::MethodDef, signature: &metadata::Signature) -> bool { if let Some(map) = def.impl_map() { - if map.flags().contains(PInvokeAttributes::SupportsLastError) { - if let Type::TypeDef(return_type, _) = &signature.return_type { - if type_def_is_handle(*return_type) { + if map.flags().contains(metadata::PInvokeAttributes::SupportsLastError) { + if let metadata::Type::TypeDef(return_type, _) = &signature.return_type { + if metadata::type_def_is_handle(*return_type) { if return_type.underlying_type().is_pointer() { return true; } - if !type_def_invalid_values(*return_type).is_empty() { + if !metadata::type_def_invalid_values(*return_type).is_empty() { return true; } } @@ -266,13 +267,13 @@ fn handle_last_error(def: MethodDef, signature: &Signature) -> bool { false } -fn method_def_extern_abi(def: MethodDef) -> &'static str { +fn method_def_extern_abi(def: metadata::MethodDef) -> &'static str { let impl_map = def.impl_map().expect("ImplMap not found"); let flags = impl_map.flags(); - if flags.contains(PInvokeAttributes::CallConvPlatformapi) { + if flags.contains(metadata::PInvokeAttributes::CallConvPlatformapi) { "system" - } else if flags.contains(PInvokeAttributes::CallConvCdecl) { + } else if flags.contains(metadata::PInvokeAttributes::CallConvCdecl) { "cdecl" } else { unimplemented!() diff --git a/crates/libs/bindgen/src/rust/handles.rs b/crates/libs/bindgen/src/rust/handles.rs index ef06b8bbcb..42c9e82643 100644 --- a/crates/libs/bindgen/src/rust/handles.rs +++ b/crates/libs/bindgen/src/rust/handles.rs @@ -1,6 +1,7 @@ use super::*; +use metadata::{AsRow, HasAttributes}; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { if writer.sys { gen_sys_handle(writer, def) } else { @@ -8,10 +9,10 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { } } -pub fn gen_sys_handle(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn gen_sys_handle(writer: &Writer, def: metadata::TypeDef) -> TokenStream { let ident = to_ident(def.name()); match def.underlying_type() { - Type::ISize if writer.std => quote! { + metadata::Type::ISize if writer.std => quote! { pub type #ident = *mut ::core::ffi::c_void; }, underlying_type => { @@ -24,7 +25,7 @@ pub fn gen_sys_handle(writer: &Writer, def: TypeDef) -> TokenStream { } } -pub fn gen_win_handle(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn gen_win_handle(writer: &Writer, def: metadata::TypeDef) -> TokenStream { let name = def.name(); let ident = to_ident(name); let underlying_type = def.underlying_type(); @@ -38,7 +39,7 @@ pub fn gen_win_handle(writer: &Writer, def: TypeDef) -> TokenStream { } } } else { - let invalid = type_def_invalid_values(def); + let invalid = metadata::type_def_invalid_values(def); if !invalid.is_empty() { let invalid = invalid.iter().map(|value| { @@ -107,9 +108,9 @@ pub fn gen_win_handle(writer: &Writer, def: TypeDef) -> TokenStream { tokens } -fn type_def_usable_for(row: TypeDef) -> Option { +fn type_def_usable_for(row: metadata::TypeDef) -> Option { if let Some(attribute) = row.find_attribute("AlsoUsableForAttribute") { - if let Some((_, Value::String(name))) = attribute.args().first() { + if let Some((_, metadata::Value::String(name))) = attribute.args().first() { return row.reader().get_type_def(row.namespace(), name.as_str()).next(); } } diff --git a/crates/libs/bindgen/src/rust/implements.rs b/crates/libs/bindgen/src/rust/implements.rs index d06d8f8f1b..f16473d259 100644 --- a/crates/libs/bindgen/src/rust/implements.rs +++ b/crates/libs/bindgen/src/rust/implements.rs @@ -1,11 +1,12 @@ use super::*; +use metadata::HasAttributes; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { - if def.kind() != TypeKind::Interface || (!writer.implement && def.has_attribute("ExclusiveToAttribute")) { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { + if def.kind() != metadata::TypeKind::Interface || (!writer.implement && def.has_attribute("ExclusiveToAttribute")) { return quote! {}; } - let generics = &type_def_generics(def); + let generics = &metadata::type_def_generics(def); let type_ident = to_ident(def.name()); let impl_ident = type_ident.join("_Impl"); let vtbl_ident = type_ident.join("_Vtbl"); @@ -13,15 +14,15 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { let constraints = writer.generic_constraints(generics); let generic_names = writer.generic_names(generics); let named_phantoms = writer.generic_named_phantoms(generics); - let cfg = type_def_cfg_impl(def, generics); + let cfg = cfg::type_def_cfg_impl(def, generics); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); let mut requires = quote! {}; let type_ident = quote! { #type_ident<#generic_names> }; - let vtables = type_def_vtables(def); - let has_unknown_base = matches!(vtables.first(), Some(Type::IUnknown)); + let vtables = metadata::type_def_vtables(def); + let has_unknown_base = matches!(vtables.first(), Some(metadata::Type::IUnknown)); - fn gen_required_trait(writer: &Writer, def: TypeDef, generics: &[Type]) -> TokenStream { + fn gen_required_trait(writer: &Writer, def: metadata::TypeDef, generics: &[metadata::Type]) -> TokenStream { let name = writer.type_def_name_imp(def, generics, "_Impl"); quote! { + #name @@ -30,12 +31,12 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { let mut matches = quote! { *iid == <#type_ident as ::windows_core::ComInterface>::IID }; - if let Some(Type::TypeDef(def, _)) = vtables.last() { + if let Some(metadata::Type::TypeDef(def, _)) = vtables.last() { requires.combine(&gen_required_trait(writer, *def, &[])) } for def in &vtables { - if let Type::TypeDef(def, generics) = def { + if let metadata::Type::TypeDef(def, generics) = def { let name = writer.type_def_name(*def, generics); matches.combine("e! { @@ -44,10 +45,10 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { } } - if def.flags().contains(TypeAttributes::WindowsRuntime) { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { // TODO: this awkward wrapping of TypeDefs needs fixing - for interface in type_interfaces(&Type::TypeDef(def, generics.to_vec())) { - if let Type::TypeDef(def, generics) = interface.ty { + for interface in metadata::type_interfaces(&metadata::Type::TypeDef(def, generics.to_vec())) { + if let metadata::Type::TypeDef(def, generics) = interface.ty { requires.combine(&gen_required_trait(writer, def, &generics)); } } @@ -61,7 +62,7 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { let method_traits = def.methods().map(|method| { let name = method_names.add(method); - let signature = method_def_signature(def.namespace(), method, generics); + let signature = metadata::method_def_signature(def.namespace(), method, generics); let signature_tokens = writer.impl_signature(def, &signature); quote! { fn #name #signature_tokens; } @@ -72,10 +73,10 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { let method_impls = def.methods().map(|method| { let name = method_names.add(method); - let signature = method_def_signature(def.namespace(), method, generics); + let signature = metadata::method_def_signature(def.namespace(), method, generics); let vtbl_signature = writer.vtbl_signature(def, generics, &signature); - let invoke_upcall = if def.flags().contains(TypeAttributes::WindowsRuntime) { winrt_methods::gen_upcall(writer, &signature, quote! { this.#name }) } else { com_methods::gen_upcall(writer, &signature, quote! { this.#name }) }; + let invoke_upcall = if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { winrt_methods::gen_upcall(writer, &signature, quote! { this.#name }) } else { com_methods::gen_upcall(writer, &signature, quote! { this.#name }) }; if has_unknown_base { quote! { @@ -100,9 +101,9 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { let mut methods = quote! {}; match vtables.last() { - Some(Type::IUnknown) => methods.combine("e! { base__: ::windows_core::IUnknown_Vtbl::new::(), }), - Some(Type::IInspectable) => methods.combine("e! { base__: ::windows_core::IInspectable_Vtbl::new::(), }), - Some(Type::TypeDef(def, generics)) => { + Some(metadata::Type::IUnknown) => methods.combine("e! { base__: ::windows_core::IUnknown_Vtbl::new::(), }), + Some(metadata::Type::IInspectable) => methods.combine("e! { base__: ::windows_core::IInspectable_Vtbl::new::(), }), + Some(metadata::Type::TypeDef(def, generics)) => { let name = writer.type_def_name_imp(*def, generics, "_Vtbl"); if has_unknown_base { methods.combine("e! { base__: #name::new::(), }); diff --git a/crates/libs/bindgen/src/rust/interfaces.rs b/crates/libs/bindgen/src/rust/interfaces.rs index 05ef63e016..2152707a6f 100644 --- a/crates/libs/bindgen/src/rust/interfaces.rs +++ b/crates/libs/bindgen/src/rust/interfaces.rs @@ -1,6 +1,6 @@ use super::*; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { if writer.sys { gen_sys_interface(def) } else { @@ -8,11 +8,11 @@ pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { } } -fn gen_sys_interface(def: TypeDef) -> TokenStream { +fn gen_sys_interface(def: metadata::TypeDef) -> TokenStream { let name = def.name(); let ident = to_ident(name); - if type_def_is_exclusive(def) { + if metadata::type_def_is_exclusive(def) { quote! {} } else { quote! { @@ -21,18 +21,18 @@ fn gen_sys_interface(def: TypeDef) -> TokenStream { } } -fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { - let generics = &type_def_generics(def); +fn gen_win_interface(writer: &Writer, def: metadata::TypeDef) -> TokenStream { + let generics = &metadata::type_def_generics(def); let ident = writer.type_def_name(def, generics); - let is_exclusive = type_def_is_exclusive(def); + let is_exclusive = metadata::type_def_is_exclusive(def); let phantoms = writer.generic_phantoms(generics); let constraints = writer.generic_constraints(generics); - let cfg = type_def_cfg(def, &[]); + let cfg = cfg::type_def_cfg(def, &[]); let doc = writer.cfg_doc(&cfg); let features = writer.cfg_features(&cfg); - let interfaces = type_interfaces(&Type::TypeDef(def, generics.to_vec())); - let vtables = type_def_vtables(def); - let has_unknown_base = matches!(vtables.first(), Some(Type::IUnknown)); + let interfaces = metadata::type_interfaces(&metadata::Type::TypeDef(def, generics.to_vec())); + let vtables = metadata::type_def_vtables(def); + let has_unknown_base = matches!(vtables.first(), Some(metadata::Type::IUnknown)); let mut tokens = if is_exclusive { quote! { #[doc(hidden)] } @@ -63,14 +63,14 @@ fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { let method_names = &mut MethodNames::new(); let virtual_names = &mut MethodNames::new(); - if def.flags().contains(TypeAttributes::WindowsRuntime) { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { for method in def.methods() { - methods.combine(&winrt_methods::writer(writer, def, generics, InterfaceKind::Default, method, method_names, virtual_names)); + methods.combine(&winrt_methods::writer(writer, def, generics, metadata::InterfaceKind::Default, method, method_names, virtual_names)); } for interface in &interfaces { - if let Type::TypeDef(def, generics) = &interface.ty { + if let metadata::Type::TypeDef(def, generics) = &interface.ty { for method in def.methods() { - methods.combine(&winrt_methods::writer(writer, *def, generics, InterfaceKind::None, method, method_names, virtual_names)); + methods.combine(&winrt_methods::writer(writer, *def, generics, metadata::InterfaceKind::None, method, method_names, virtual_names)); } } } @@ -78,9 +78,9 @@ fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { let mut bases = vtables.len(); for ty in &vtables { match ty { - Type::IUnknown | Type::IInspectable => {} - Type::TypeDef(def, _) => { - let kind = if def.type_name() == TypeName::IDispatch { InterfaceKind::None } else { InterfaceKind::Default }; + metadata::Type::IUnknown | metadata::Type::IInspectable => {} + metadata::Type::TypeDef(def, _) => { + let kind = if def.type_name() == metadata::TypeName::IDispatch { metadata::InterfaceKind::None } else { metadata::InterfaceKind::Default }; for method in def.methods() { methods.combine(&com_methods::writer(writer, *def, kind, method, method_names, virtual_names, bases)); } @@ -91,7 +91,7 @@ fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { bases -= 1; } for method in def.methods() { - methods.combine(&com_methods::writer(writer, def, InterfaceKind::Default, method, method_names, virtual_names, 0)); + methods.combine(&com_methods::writer(writer, def, metadata::InterfaceKind::Default, method, method_names, virtual_names, 0)); } } @@ -110,7 +110,7 @@ fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { let into = writer.type_name(ty); write!(&mut hierarchy, ", {into}").unwrap(); - hierarchy_cfg = hierarchy_cfg.union(&type_cfg(ty)); + hierarchy_cfg = hierarchy_cfg.union(&cfg::type_cfg(ty)); } hierarchy.push_str(");"); @@ -119,7 +119,7 @@ fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { } else { for ty in &vtables { let into = writer.type_name(ty); - let cfg = writer.cfg_features(&cfg.union(&type_cfg(ty))); + let cfg = writer.cfg_features(&cfg.union(&cfg::type_cfg(ty))); tokens.combine("e! { #cfg impl<#constraints> ::windows_core::CanInto<#into> for #ident {} @@ -127,10 +127,10 @@ fn gen_win_interface(writer: &Writer, def: TypeDef) -> TokenStream { } } - if def.flags().contains(TypeAttributes::WindowsRuntime) { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { for interface in &interfaces { let into = writer.type_name(&interface.ty); - let cfg = writer.cfg_features(&cfg.union(&type_cfg(&interface.ty))); + let cfg = writer.cfg_features(&cfg.union(&cfg::type_cfg(&interface.ty))); tokens.combine("e! { #cfg impl<#constraints> ::windows_core::CanTryInto<#into> for #ident {} diff --git a/crates/libs/bindgen/src/rust/iterators.rs b/crates/libs/bindgen/src/rust/iterators.rs index 76483129c6..bc1a0f9c52 100644 --- a/crates/libs/bindgen/src/rust/iterators.rs +++ b/crates/libs/bindgen/src/rust/iterators.rs @@ -1,9 +1,9 @@ use super::*; -pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStream, constraints: &TokenStream, _phantoms: &TokenStream, cfg: &Cfg) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::TypeDef, generics: &[metadata::Type], ident: &TokenStream, constraints: &TokenStream, _phantoms: &TokenStream, cfg: &cfg::Cfg) -> TokenStream { match def.type_name() { // If the type is IIterator then simply implement the Iterator trait over top. - TypeName::IIterator => { + metadata::TypeName::IIterator => { return quote! { impl ::core::iter::Iterator for IIterator { type Item = T; @@ -22,7 +22,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr } // If the type is IIterable then implement the IntoIterator trait and rely on the resulting // IIterator returned by first() to implement the Iterator trait. - TypeName::IIterable => { + metadata::TypeName::IIterable => { return quote! { impl ::core::iter::IntoIterator for IIterable { type Item = T; @@ -44,7 +44,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr }; } // If the type is IVectorView then provide the VectorViewIterator fast iterator. - TypeName::IVectorView => { + metadata::TypeName::IVectorView => { return quote! { pub struct VectorViewIterator { vector: ::core::option::Option>, @@ -91,7 +91,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr } }; } - TypeName::IVector => { + metadata::TypeName::IVector => { return quote! { pub struct VectorIterator { vector: ::core::option::Option>, @@ -143,17 +143,17 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr let wfc = writer.namespace("Windows.Foundation.Collections"); let mut iterable = None; - let interfaces = type_interfaces(&Type::TypeDef(def, generics.to_vec())); + let interfaces = metadata::type_interfaces(&metadata::Type::TypeDef(def, generics.to_vec())); // If the class or interface is not one of the well-known collection interfaces, we then see whether it // implements any one of them. Here is where we favor IVectorView/IVector over IIterable. for interface in interfaces { - if let Type::TypeDef(interface, interface_generics) = &interface.ty { + if let metadata::Type::TypeDef(interface, interface_generics) = &interface.ty { match interface.type_name() { - TypeName::IVectorView => { + metadata::TypeName::IVectorView => { let item = writer.type_name(&interface_generics[0]); let mut cfg = cfg.clone(); - type_def_cfg_combine(*interface, interface_generics, &mut cfg); + cfg::type_def_cfg_combine(*interface, interface_generics, &mut cfg); let features = writer.cfg_features(&cfg); return quote! { @@ -177,10 +177,10 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr } }; } - TypeName::IVector => { + metadata::TypeName::IVector => { let item = writer.type_name(&interface_generics[0]); let mut cfg = cfg.clone(); - type_def_cfg_combine(*interface, interface_generics, &mut cfg); + cfg::type_def_cfg_combine(*interface, interface_generics, &mut cfg); let features = writer.cfg_features(&cfg); return quote! { @@ -204,7 +204,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr } }; } - TypeName::IIterable => { + metadata::TypeName::IIterable => { iterable = Some((*interface, interface_generics.to_vec())); } _ => {} @@ -217,7 +217,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generics: &[Type], ident: &TokenStr Some((interface, interface_generics)) => { let item = writer.type_name(&interface_generics[0]); let mut cfg = cfg.clone(); - type_def_cfg_combine(interface, &interface_generics, &mut cfg); + cfg::type_def_cfg_combine(interface, &interface_generics, &mut cfg); let features = writer.cfg_features(&cfg); quote! { diff --git a/crates/libs/bindgen/src/rust/method_names.rs b/crates/libs/bindgen/src/rust/method_names.rs index 14a9d6501e..70c40d8bfb 100644 --- a/crates/libs/bindgen/src/rust/method_names.rs +++ b/crates/libs/bindgen/src/rust/method_names.rs @@ -1,13 +1,14 @@ use super::*; +use metadata::HasAttributes; -pub struct MethodNames(BTreeMap); +pub struct MethodNames(std::collections::BTreeMap); impl MethodNames { pub fn new() -> Self { - Self(BTreeMap::new()) + Self(std::collections::BTreeMap::new()) } - pub fn add(&mut self, method: MethodDef) -> TokenStream { + pub fn add(&mut self, method: metadata::MethodDef) -> TokenStream { let name = method_def_special_name(method); let overload = self.0.entry(name.to_string()).or_insert(0); *overload += 1; @@ -18,9 +19,9 @@ impl MethodNames { } } - pub fn add_vtable_types(&mut self, def: TypeDef) { - for def in type_def_vtables(def) { - if let Type::TypeDef(def, _) = def { + pub fn add_vtable_types(&mut self, def: metadata::TypeDef) { + for def in metadata::type_def_vtables(def) { + if let metadata::Type::TypeDef(def, _) = def { for method in def.methods() { self.add(method); } @@ -29,9 +30,9 @@ impl MethodNames { } } -fn method_def_special_name(row: MethodDef) -> String { +fn method_def_special_name(row: metadata::MethodDef) -> String { let name = row.name(); - if row.flags().contains(MethodAttributes::SpecialName) { + if row.flags().contains(metadata::MethodAttributes::SpecialName) { if name.starts_with("get") { name[4..].to_string() } else if name.starts_with("put") { @@ -46,7 +47,7 @@ fn method_def_special_name(row: MethodDef) -> String { } else { if let Some(attribute) = row.find_attribute("OverloadAttribute") { for (_, arg) in attribute.args() { - if let Value::String(name) = arg { + if let metadata::Value::String(name) = arg { return name; } } diff --git a/crates/libs/bindgen/src/rust/mod.rs b/crates/libs/bindgen/src/rust/mod.rs index db98d3d8bc..2ddc2515a8 100644 --- a/crates/libs/bindgen/src/rust/mod.rs +++ b/crates/libs/bindgen/src/rust/mod.rs @@ -17,8 +17,7 @@ mod try_format; mod winrt_methods; mod writer; use super::*; -use crate::{Error, Result, Tree}; -use cfg::*; +use crate::Result; use rayon::prelude::*; pub fn from_reader(reader: &'static metadata::Reader, mut config: std::collections::BTreeMap<&str, &str>, output: &str) -> Result<()> { @@ -56,7 +55,7 @@ fn gen_file(writer: &Writer) -> Result<()> { if writer.flatten { let tokens = standalone::standalone_imp(writer); - crate::write_to_file(&writer.output, try_format(writer, &tokens)) + write_to_file(&writer.output, try_format(writer, &tokens)) } else { let mut tokens = String::new(); let root = Tree::new(writer.reader); @@ -65,12 +64,12 @@ fn gen_file(writer: &Writer) -> Result<()> { tokens.push_str(&namespace(writer, tree)); } - crate::write_to_file(&writer.output, try_format(writer, &tokens)) + write_to_file(&writer.output, try_format(writer, &tokens)) } } fn gen_package(writer: &Writer) -> Result<()> { - let directory = crate::directory(&writer.output); + let directory = directory(&writer.output); let root = Tree::new(writer.reader); let mut root_len = 0; @@ -92,20 +91,20 @@ fn gen_package(writer: &Writer) -> Result<()> { } let output = format!("{directory}/mod.rs"); - crate::write_to_file(&output, try_format(writer, &tokens))?; + write_to_file(&output, try_format(writer, &tokens))?; if !writer.sys && !tokens_impl.is_empty() { let output = format!("{directory}/impl.rs"); - crate::write_to_file(&output, try_format(writer, &tokens_impl))?; + write_to_file(&output, try_format(writer, &tokens_impl))?; } Ok::<(), Error>(()) })?; - let cargo_toml = format!("{}/Cargo.toml", crate::directory(directory)); + let cargo_toml = format!("{}/Cargo.toml", super::directory(directory)); let mut toml = String::new(); - for line in crate::read_file_lines(&cargo_toml)? { + for line in read_file_lines(&cargo_toml)? { toml.push_str(&line); toml.push('\n'); @@ -130,14 +129,12 @@ fn gen_package(writer: &Writer) -> Result<()> { } } - crate::write_to_file(&cargo_toml, toml) + write_to_file(&cargo_toml, toml) } -use crate::tokens::*; -use metadata::*; use method_names::*; -use std::collections::*; use std::fmt::Write; +use tokens::*; use try_format::*; use writer::*; @@ -164,57 +161,57 @@ fn namespace(writer: &Writer, tree: &Tree) -> String { } } - let mut functions = BTreeMap::<&str, TokenStream>::new(); - let mut types = BTreeMap::>::new(); + let mut functions = std::collections::BTreeMap::<&str, TokenStream>::new(); + let mut types = std::collections::BTreeMap::>::new(); for item in writer.reader.namespace_items(writer.namespace) { match item { - Item::Type(def) => { + metadata::Item::Type(def) => { let type_name = def.type_name(); - if REMAP_TYPES.iter().any(|(x, _)| x == &type_name) { + if metadata::REMAP_TYPES.iter().any(|(x, _)| x == &type_name) { continue; } - if CORE_TYPES.iter().any(|(x, _)| x == &type_name) { + if metadata::CORE_TYPES.iter().any(|(x, _)| x == &type_name) { continue; } let name = type_name.name; let kind = def.kind(); match kind { - TypeKind::Class => { - if def.flags().contains(TypeAttributes::WindowsRuntime) { + metadata::TypeKind::Class => { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { types.entry(kind).or_default().insert(name, classes::writer(writer, def)); } } - TypeKind::Interface => types.entry(kind).or_default().entry(name).or_default().combine(&interfaces::writer(writer, def)), - TypeKind::Enum => types.entry(kind).or_default().entry(name).or_default().combine(&enums::writer(writer, def)), - TypeKind::Struct => { + metadata::TypeKind::Interface => types.entry(kind).or_default().entry(name).or_default().combine(&interfaces::writer(writer, def)), + metadata::TypeKind::Enum => types.entry(kind).or_default().entry(name).or_default().combine(&enums::writer(writer, def)), + metadata::TypeKind::Struct => { if def.fields().next().is_none() { - if let Some(guid) = type_def_guid(def) { + if let Some(guid) = metadata::type_def_guid(def) { let ident = to_ident(name); let value = writer.guid(&guid); - let guid = writer.type_name(&Type::GUID); - let cfg = type_def_cfg(def, &[]); + let guid = writer.type_name(&metadata::Type::GUID); + let cfg = cfg::type_def_cfg(def, &[]); let doc = writer.cfg_doc(&cfg); let constant = quote! { #doc pub const #ident: #guid = #value; }; - types.entry(TypeKind::Class).or_default().entry(name).or_default().combine(&constant); + types.entry(metadata::TypeKind::Class).or_default().entry(name).or_default().combine(&constant); continue; } } types.entry(kind).or_default().entry(name).or_default().combine(&structs::writer(writer, def)); } - TypeKind::Delegate => types.entry(kind).or_default().entry(name).or_default().combine(&delegates::writer(writer, def)), + metadata::TypeKind::Delegate => types.entry(kind).or_default().entry(name).or_default().combine(&delegates::writer(writer, def)), } } - Item::Fn(def, namespace) => { + metadata::Item::Fn(def, namespace) => { let name = def.name(); functions.entry(name).or_default().combine(&functions::writer(writer, namespace, def)); } - Item::Const(def) => { + metadata::Item::Const(def) => { let name = def.name(); - types.entry(TypeKind::Class).or_default().entry(name).or_default().combine(&constants::writer(writer, def)); + types.entry(metadata::TypeKind::Class).or_default().entry(name).or_default().combine(&constants::writer(writer, def)); } } } @@ -239,15 +236,15 @@ fn namespace(writer: &Writer, tree: &Tree) -> String { fn namespace_impl(writer: &Writer, tree: &Tree) -> String { let writer = &mut writer.clone(); writer.namespace = tree.namespace; - let mut types = BTreeMap::<&str, TokenStream>::new(); + let mut types = std::collections::BTreeMap::<&str, TokenStream>::new(); for item in writer.reader.namespace_items(tree.namespace) { - if let Item::Type(def) = item { + if let metadata::Item::Type(def) = item { let type_name = def.type_name(); - if CORE_TYPES.iter().any(|(x, _)| x == &type_name) { + if metadata::CORE_TYPES.iter().any(|(x, _)| x == &type_name) { continue; } - if def.kind() != TypeKind::Interface { + if def.kind() != metadata::TypeKind::Interface { continue; } let tokens = implements::writer(writer, def); diff --git a/crates/libs/bindgen/src/rust/standalone.rs b/crates/libs/bindgen/src/rust/standalone.rs index 7ac9e0a55f..21daa55180 100644 --- a/crates/libs/bindgen/src/rust/standalone.rs +++ b/crates/libs/bindgen/src/rust/standalone.rs @@ -1,17 +1,18 @@ use super::*; +use metadata::AsRow; pub fn standalone_imp(writer: &Writer) -> String { - let mut types = BTreeSet::new(); - let mut functions = BTreeSet::new(); - let mut constants = BTreeSet::new(); + let mut types = std::collections::BTreeSet::new(); + let mut functions = std::collections::BTreeSet::new(); + let mut constants = std::collections::BTreeSet::new(); for item in writer.reader.items() { item_collect_standalone(item.clone(), &mut types); match item { - Item::Type(_) => {} - Item::Fn(def, namespace) => _ = functions.insert((def, namespace)), - Item::Const(def) => _ = constants.insert(def), + metadata::Item::Type(_) => {} + metadata::Item::Fn(def, namespace) => _ = functions.insert((def, namespace)), + metadata::Item::Const(def) => _ = constants.insert(def), } } @@ -19,16 +20,16 @@ pub fn standalone_imp(writer: &Writer) -> String { for ty in types { match ty { - Type::HRESULT if writer.sys => sorted.insert("HRESULT", quote! { pub type HRESULT = i32; }), - Type::String if writer.sys => sorted.insert("HSTRING", quote! { pub type HSTRING = *mut ::core::ffi::c_void; }), - Type::IUnknown if writer.sys => sorted.insert("IUnknown", quote! { pub type IUnknown = *mut ::core::ffi::c_void; }), - Type::IInspectable if writer.sys => sorted.insert("IInspectable", quote! { pub type IInspectable = *mut ::core::ffi::c_void; }), - Type::PSTR if writer.sys => sorted.insert("PSTR", quote! { pub type PSTR = *mut u8; }), - Type::PWSTR if writer.sys => sorted.insert("PWSTR", quote! { pub type PWSTR = *mut u16; }), - Type::PCSTR if writer.sys => sorted.insert("PCSTR", quote! { pub type PCSTR = *const u8; }), - Type::PCWSTR if writer.sys => sorted.insert("PCWSTR", quote! { pub type PCWSTR = *const u16; }), - Type::BSTR if writer.sys => sorted.insert("BSTR", quote! { pub type BSTR = *const u16; }), - Type::GUID if writer.sys => { + metadata::Type::HRESULT if writer.sys => sorted.insert("HRESULT", quote! { pub type HRESULT = i32; }), + metadata::Type::String if writer.sys => sorted.insert("HSTRING", quote! { pub type HSTRING = *mut ::core::ffi::c_void; }), + metadata::Type::IUnknown if writer.sys => sorted.insert("IUnknown", quote! { pub type IUnknown = *mut ::core::ffi::c_void; }), + metadata::Type::IInspectable if writer.sys => sorted.insert("IInspectable", quote! { pub type IInspectable = *mut ::core::ffi::c_void; }), + metadata::Type::PSTR if writer.sys => sorted.insert("PSTR", quote! { pub type PSTR = *mut u8; }), + metadata::Type::PWSTR if writer.sys => sorted.insert("PWSTR", quote! { pub type PWSTR = *mut u16; }), + metadata::Type::PCSTR if writer.sys => sorted.insert("PCSTR", quote! { pub type PCSTR = *const u8; }), + metadata::Type::PCWSTR if writer.sys => sorted.insert("PCWSTR", quote! { pub type PCWSTR = *const u16; }), + metadata::Type::BSTR if writer.sys => sorted.insert("BSTR", quote! { pub type BSTR = *const u16; }), + metadata::Type::GUID if writer.sys => { sorted.insert( "GUID", quote! { @@ -53,10 +54,10 @@ pub fn standalone_imp(writer: &Writer) -> String { }, ); } - Type::TypeDef(def, _) => { + metadata::Type::TypeDef(def, _) => { let kind = def.kind(); match kind { - TypeKind::Class => { + metadata::TypeKind::Class => { let name = def.name(); if writer.sys { let ident = to_ident(name); @@ -65,7 +66,7 @@ pub fn standalone_imp(writer: &Writer) -> String { sorted.insert(name, classes::writer(writer, def)); } } - TypeKind::Interface => { + metadata::TypeKind::Interface => { let name = def.name(); if writer.sys { let ident = to_ident(name); @@ -74,16 +75,16 @@ pub fn standalone_imp(writer: &Writer) -> String { sorted.insert(name, interfaces::writer(writer, def)); } } - TypeKind::Enum => { + metadata::TypeKind::Enum => { sorted.insert(def.name(), enums::writer(writer, def)); } - TypeKind::Struct => { + metadata::TypeKind::Struct => { let name = def.name(); if def.fields().next().is_none() { - if let Some(guid) = type_def_guid(def) { + if let Some(guid) = metadata::type_def_guid(def) { let ident = to_ident(name); let value = writer.guid(&guid); - let guid = writer.type_name(&Type::GUID); + let guid = writer.type_name(&metadata::Type::GUID); sorted.insert( name, quote! { @@ -95,7 +96,7 @@ pub fn standalone_imp(writer: &Writer) -> String { } sorted.insert(name, structs::writer(writer, def)); } - TypeKind::Delegate => { + metadata::TypeKind::Delegate => { sorted.insert(def.name(), delegates::writer(writer, def)); } } @@ -118,7 +119,7 @@ pub fn standalone_imp(writer: &Writer) -> String { } #[derive(Default)] -struct SortedTokens(BTreeMap); +struct SortedTokens(std::collections::BTreeMap); impl SortedTokens { fn insert(&mut self, key: &str, tokens: TokenStream) { @@ -126,25 +127,25 @@ impl SortedTokens { } } -fn item_collect_standalone(item: Item, set: &mut BTreeSet) { +fn item_collect_standalone(item: metadata::Item, set: &mut std::collections::BTreeSet) { match item { - Item::Type(def) => type_collect_standalone(&Type::TypeDef(def, vec![]), set), - Item::Const(def) => type_collect_standalone(&def.ty(None).to_const_type(), set), - Item::Fn(def, namespace) => { - let signature = method_def_signature(namespace, def, &[]); + metadata::Item::Type(def) => type_collect_standalone(&metadata::Type::TypeDef(def, vec![]), set), + metadata::Item::Const(def) => type_collect_standalone(&def.ty(None).to_const_type(), set), + metadata::Item::Fn(def, namespace) => { + let signature = metadata::method_def_signature(namespace, def, &[]); type_collect_standalone(&signature.return_type, set); signature.params.iter().for_each(|param| type_collect_standalone(¶m.ty, set)); } } } // TODO: remove or move to riddle -fn type_collect_standalone(ty: &Type, set: &mut BTreeSet) { +fn type_collect_standalone(ty: &metadata::Type, set: &mut std::collections::BTreeSet) { let ty = ty.to_underlying_type(); if !set.insert(ty.clone()) { return; } - let Type::TypeDef(def, generics) = &ty else { + let metadata::Type::TypeDef(def, generics) = &ty else { return; }; @@ -161,7 +162,7 @@ fn type_collect_standalone(ty: &Type, set: &mut BTreeSet) { if !type_name.namespace.is_empty() { for row in def.reader().get_type_def(type_name.namespace, type_name.name) { if def != row { - type_collect_standalone(&Type::TypeDef(row, Vec::new()), set); + type_collect_standalone(&metadata::Type::TypeDef(row, Vec::new()), set); } } } @@ -171,7 +172,7 @@ fn type_collect_standalone(ty: &Type, set: &mut BTreeSet) { } for field in def.fields() { let ty = field.ty(Some(def)); - if let Type::TypeDef(def, _) = &ty { + if let metadata::Type::TypeDef(def, _) = &ty { if def.namespace().is_empty() { continue; } @@ -183,27 +184,27 @@ fn type_collect_standalone(ty: &Type, set: &mut BTreeSet) { if method.name() == ".ctor" { continue; } - let signature = method_def_signature(def.namespace(), method, generics); + let signature = metadata::method_def_signature(def.namespace(), method, generics); type_collect_standalone(&signature.return_type, set); signature.params.iter().for_each(|param| type_collect_standalone(¶m.ty, set)); } - for interface in type_interfaces(&ty) { + for interface in metadata::type_interfaces(&ty) { type_collect_standalone(&interface.ty, set); } - if def.kind() == TypeKind::Struct && def.fields().next().is_none() && type_def_guid(def).is_some() { - set.insert(Type::GUID); + if def.kind() == metadata::TypeKind::Struct && def.fields().next().is_none() && metadata::type_def_guid(def).is_some() { + set.insert(metadata::Type::GUID); } type_collect_standalone_nested(def, set); } -fn type_collect_standalone_nested(td: TypeDef, set: &mut BTreeSet) { +fn type_collect_standalone_nested(td: metadata::TypeDef, set: &mut std::collections::BTreeSet) { for nested in td.reader().nested_types(td) { type_collect_standalone_nested(nested, set); for field in nested.fields() { let ty = field.ty(Some(nested)); - if let Type::TypeDef(def, _) = &ty { + if let metadata::Type::TypeDef(def, _) = &ty { // Skip the fields that actually refer to the anonymous nested // type, otherwise it will get added to the typeset and emitted if def.namespace().is_empty() { diff --git a/crates/libs/bindgen/src/rust/structs.rs b/crates/libs/bindgen/src/rust/structs.rs index dda7fc21b0..e589c1de95 100644 --- a/crates/libs/bindgen/src/rust/structs.rs +++ b/crates/libs/bindgen/src/rust/structs.rs @@ -1,18 +1,19 @@ use super::*; +use metadata::HasAttributes; -pub fn writer(writer: &Writer, def: TypeDef) -> TokenStream { +pub fn writer(writer: &Writer, def: metadata::TypeDef) -> TokenStream { if def.has_attribute("ApiContractAttribute") { return quote! {}; } - if type_def_is_handle(def) { + if metadata::type_def_is_handle(def) { return handles::writer(writer, def); } - gen_struct_with_name(writer, def, def.name(), &Cfg::default()) + gen_struct_with_name(writer, def, def.name(), &cfg::Cfg::default()) } -fn gen_struct_with_name(writer: &Writer, def: TypeDef, struct_name: &str, cfg: &Cfg) -> TokenStream { +fn gen_struct_with_name(writer: &Writer, def: metadata::TypeDef, struct_name: &str, cfg: &cfg::Cfg) -> TokenStream { let name = to_ident(struct_name); if def.fields().next().is_none() { @@ -37,7 +38,7 @@ fn gen_struct_with_name(writer: &Writer, def: TypeDef, struct_name: &str, cfg: & } let flags = def.flags(); - let cfg = cfg.union(&type_def_cfg(def, &[])); + let cfg = cfg.union(&cfg::type_def_cfg(def, &[])); let repr = if let Some(layout) = def.class_layout() { let packing = Literal::usize_unsuffixed(layout.packing_size()); @@ -50,13 +51,13 @@ fn gen_struct_with_name(writer: &Writer, def: TypeDef, struct_name: &str, cfg: & let name = to_ident(f.name()); let ty = f.ty(Some(def)); - if f.flags().contains(FieldAttributes::Literal) { + if f.flags().contains(metadata::FieldAttributes::Literal) { quote! {} - } else if !writer.sys && flags.contains(TypeAttributes::ExplicitLayout) && !field_is_copyable(f, def) { + } else if !writer.sys && flags.contains(metadata::TypeAttributes::ExplicitLayout) && !metadata::field_is_copyable(f, def) { let ty = writer.type_default_name(&ty); quote! { pub #name: ::std::mem::ManuallyDrop<#ty>, } - } else if !writer.sys && !flags.contains(TypeAttributes::WindowsRuntime) && !field_is_blittable(f, def) { - if let Type::Win32Array(ty, len) = ty { + } else if !writer.sys && !flags.contains(metadata::TypeAttributes::WindowsRuntime) && !metadata::field_is_blittable(f, def) { + if let metadata::Type::Win32Array(ty, len) = ty { let ty = writer.type_default_name(&ty); quote! { pub #name: [::std::mem::ManuallyDrop<#ty>; #len], } } else { @@ -69,7 +70,7 @@ fn gen_struct_with_name(writer: &Writer, def: TypeDef, struct_name: &str, cfg: & } }); - let struct_or_union = if flags.contains(TypeAttributes::ExplicitLayout) { + let struct_or_union = if flags.contains(metadata::TypeAttributes::ExplicitLayout) { quote! { union } } else { quote! { struct } @@ -110,12 +111,12 @@ fn gen_struct_with_name(writer: &Writer, def: TypeDef, struct_name: &str, cfg: & tokens } -fn gen_windows_traits(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &Cfg) -> TokenStream { +fn gen_windows_traits(writer: &Writer, def: metadata::TypeDef, name: &TokenStream, cfg: &cfg::Cfg) -> TokenStream { if writer.sys { quote! {} } else { let features = writer.cfg_features(cfg); - let is_copy = type_def_is_blittable(def); + let is_copy = metadata::type_def_is_blittable(def); let type_kind = if is_copy { quote! { CopyType } @@ -130,8 +131,8 @@ fn gen_windows_traits(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &C } }; - if def.flags().contains(TypeAttributes::WindowsRuntime) { - let signature = Literal::byte_string(type_def_signature(def, &[]).as_bytes()); + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { + let signature = Literal::byte_string(metadata::type_def_signature(def, &[]).as_bytes()); tokens.combine("e! { #features @@ -145,15 +146,15 @@ fn gen_windows_traits(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &C } } -fn gen_compare_traits(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &Cfg) -> TokenStream { +fn gen_compare_traits(writer: &Writer, def: metadata::TypeDef, name: &TokenStream, cfg: &cfg::Cfg) -> TokenStream { let features = writer.cfg_features(cfg); - if writer.sys || type_def_has_explicit_layout(def) || type_def_has_packing(def) || type_def_has_callback(def) { + if writer.sys || metadata::type_def_has_explicit_layout(def) || metadata::type_def_has_packing(def) || metadata::type_def_has_callback(def) { quote! {} } else { let fields = def.fields().filter_map(|f| { let name = to_ident(f.name()); - if f.flags().contains(FieldAttributes::Literal) { + if f.flags().contains(metadata::FieldAttributes::Literal) { None } else { Some(quote! { self.#name == other.#name }) @@ -173,21 +174,21 @@ fn gen_compare_traits(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &C } } -fn gen_debug(writer: &Writer, def: TypeDef, ident: &TokenStream, cfg: &Cfg) -> TokenStream { - if writer.sys || type_def_has_explicit_layout(def) || type_def_has_packing(def) { +fn gen_debug(writer: &Writer, def: metadata::TypeDef, ident: &TokenStream, cfg: &cfg::Cfg) -> TokenStream { + if writer.sys || metadata::type_def_has_explicit_layout(def) || metadata::type_def_has_packing(def) { quote! {} } else { let name = ident.as_str(); let features = writer.cfg_features(cfg); let fields = def.fields().filter_map(|f| { - if f.flags().contains(FieldAttributes::Literal) { + if f.flags().contains(metadata::FieldAttributes::Literal) { None } else { let name = f.name(); let ident = to_ident(name); let ty = f.ty(Some(def)); - if type_has_callback(&ty) { + if metadata::type_has_callback(&ty) { None } else { Some(quote! { .field(#name, &self.#ident) }) @@ -206,10 +207,10 @@ fn gen_debug(writer: &Writer, def: TypeDef, ident: &TokenStream, cfg: &Cfg) -> T } } -fn gen_copy_clone(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &Cfg) -> TokenStream { +fn gen_copy_clone(writer: &Writer, def: metadata::TypeDef, name: &TokenStream, cfg: &cfg::Cfg) -> TokenStream { let features = writer.cfg_features(cfg); - if writer.sys || type_def_is_copyable(def) { + if writer.sys || metadata::type_def_is_copyable(def) { quote! { #features impl ::core::marker::Copy for #name {} @@ -223,7 +224,7 @@ fn gen_copy_clone(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &Cfg) } else if def.class_layout().is_some() { // Don't support copy/clone of packed structs: https://github.com/rust-lang/rust/issues/82523 quote! {} - } else if !def.flags().contains(TypeAttributes::WindowsRuntime) { + } else if !def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { quote! { #features impl ::core::clone::Clone for #name { @@ -235,9 +236,9 @@ fn gen_copy_clone(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &Cfg) } else { let fields = def.fields().map(|f| { let name = to_ident(f.name()); - if f.flags().contains(FieldAttributes::Literal) { + if f.flags().contains(metadata::FieldAttributes::Literal) { quote! {} - } else if field_is_blittable(f, def) { + } else if metadata::field_is_blittable(f, def) { quote! { #name: self.#name } } else { quote! { #name: self.#name.clone() } @@ -255,11 +256,11 @@ fn gen_copy_clone(writer: &Writer, def: TypeDef, name: &TokenStream, cfg: &Cfg) } } -fn gen_struct_constants(writer: &Writer, def: TypeDef, struct_name: &TokenStream, cfg: &Cfg) -> TokenStream { +fn gen_struct_constants(writer: &Writer, def: metadata::TypeDef, struct_name: &TokenStream, cfg: &cfg::Cfg) -> TokenStream { let features = writer.cfg_features(cfg); let constants = def.fields().filter_map(|f| { - if f.flags().contains(FieldAttributes::Literal) { + if f.flags().contains(metadata::FieldAttributes::Literal) { if let Some(constant) = f.constant() { let name = to_ident(f.name()); let value = writer.typed_value(&constant.value()); diff --git a/crates/libs/bindgen/src/rust/winrt_methods.rs b/crates/libs/bindgen/src/rust/winrt_methods.rs index a43594fb7e..eeb62ccc71 100644 --- a/crates/libs/bindgen/src/rust/winrt_methods.rs +++ b/crates/libs/bindgen/src/rust/winrt_methods.rs @@ -1,23 +1,23 @@ use super::*; // TODO take Signature instead of MethodDef (wherever MethodDef is found) -pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: InterfaceKind, method: MethodDef, method_names: &mut MethodNames, virtual_names: &mut MethodNames) -> TokenStream { - let signature = method_def_signature(def.namespace(), method, generic_types); +pub fn writer(writer: &Writer, def: metadata::TypeDef, generic_types: &[metadata::Type], kind: metadata::InterfaceKind, method: metadata::MethodDef, method_names: &mut MethodNames, virtual_names: &mut MethodNames) -> TokenStream { + let signature = metadata::method_def_signature(def.namespace(), method, generic_types); let params = &signature.params; let name = method_names.add(method); let interface_name = writer.type_def_name(def, generic_types); let vname = virtual_names.add(method); let generics = writer.constraint_generics(params); let where_clause = writer.where_clause(params); - let mut cfg = signature_cfg(method); - type_def_cfg_combine(def, generic_types, &mut cfg); + let mut cfg = cfg::signature_cfg(method); + cfg::type_def_cfg_combine(def, generic_types, &mut cfg); let doc = writer.cfg_method_doc(&cfg); let features = writer.cfg_features(&cfg); let args = gen_winrt_abi_args(writer, params); let params = gen_winrt_params(writer, params); let return_type_tokens = match &signature.return_type { - Type::Void => quote! { () }, + metadata::Type::Void => quote! { () }, _ => { let tokens = writer.type_name(&signature.return_type); if signature.return_type.is_winrt_array() { @@ -29,7 +29,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: Inter }; let return_arg = match &signature.return_type { - Type::Void => quote! {}, + metadata::Type::Void => quote! {}, _ => { if signature.return_type.is_winrt_array() { let return_type = writer.type_name(&signature.return_type); @@ -41,7 +41,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: Inter }; let vcall = match &signature.return_type { - Type::Void => { + metadata::Type::Void => { quote! { (::windows_core::Interface::vtable(this).#vname)(::windows_core::Interface::as_raw(this), #args).ok() } @@ -63,7 +63,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: Inter }; match kind { - InterfaceKind::Default => quote! { + metadata::InterfaceKind::Default => quote! { #doc #features pub fn #name<#generics>(&self, #params) -> ::windows_core::Result<#return_type_tokens> #where_clause { @@ -73,7 +73,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: Inter } } }, - InterfaceKind::None | InterfaceKind::Base | InterfaceKind::Overridable => { + metadata::InterfaceKind::None | metadata::InterfaceKind::Base | metadata::InterfaceKind::Overridable => { quote! { #doc #features @@ -85,7 +85,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: Inter } } } - InterfaceKind::Static => { + metadata::InterfaceKind::Static => { quote! { #doc #features @@ -97,7 +97,7 @@ pub fn writer(writer: &Writer, def: TypeDef, generic_types: &[Type], kind: Inter } } -fn gen_winrt_params(writer: &Writer, params: &[SignatureParam]) -> TokenStream { +fn gen_winrt_params(writer: &Writer, params: &[metadata::SignatureParam]) -> TokenStream { let mut result = quote! {}; let mut generic_params = writer.generic_params(params); @@ -106,14 +106,14 @@ fn gen_winrt_params(writer: &Writer, params: &[SignatureParam]) -> TokenStream { let kind = writer.type_name(¶m.ty); let default_type = writer.type_default_name(¶m.ty); - if param.def.flags().contains(ParamAttributes::In) { + if param.def.flags().contains(metadata::ParamAttributes::In) { if param.ty.is_winrt_array() { result.combine("e! { #name: &[#default_type], }); } else if param.is_convertible() { let (position, _) = generic_params.next().unwrap(); let kind: TokenStream = format!("P{position}").into(); result.combine("e! { #name: #kind, }); - } else if type_is_blittable(¶m.ty) { + } else if metadata::type_is_blittable(¶m.ty) { result.combine("e! { #name: #kind, }); } else { result.combine("e! { #name: &#kind, }); @@ -130,23 +130,23 @@ fn gen_winrt_params(writer: &Writer, params: &[SignatureParam]) -> TokenStream { result } -fn gen_winrt_abi_args(writer: &Writer, params: &[SignatureParam]) -> TokenStream { +fn gen_winrt_abi_args(writer: &Writer, params: &[metadata::SignatureParam]) -> TokenStream { let mut tokens = TokenStream::new(); for param in params { let name = writer.param_name(param.def); - let param = if param.def.flags().contains(ParamAttributes::In) { + let param = if param.def.flags().contains(metadata::ParamAttributes::In) { if param.ty.is_winrt_array() { - if type_is_blittable(¶m.ty) { + if metadata::type_is_blittable(¶m.ty) { quote! { #name.len().try_into().unwrap(), #name.as_ptr(), } } else { quote! { #name.len().try_into().unwrap(), ::core::mem::transmute(#name.as_ptr()), } } - } else if type_is_non_exclusive_winrt_interface(¶m.ty) { + } else if metadata::type_is_non_exclusive_winrt_interface(¶m.ty) { quote! { #name.try_into_param()?.abi(), } - } else if type_is_borrowed(¶m.ty) { + } else if metadata::type_is_borrowed(¶m.ty) { quote! { #name.into_param().abi(), } - } else if type_is_blittable(¶m.ty) { + } else if metadata::type_is_blittable(¶m.ty) { if param.ty.is_const_ref() { quote! { &#name, } } else { @@ -156,14 +156,14 @@ fn gen_winrt_abi_args(writer: &Writer, params: &[SignatureParam]) -> TokenStream quote! { ::core::mem::transmute_copy(#name), } } } else if param.ty.is_winrt_array() { - if type_is_blittable(¶m.ty) { + if metadata::type_is_blittable(¶m.ty) { quote! { #name.len().try_into().unwrap(), #name.as_mut_ptr(), } } else { quote! { #name.len().try_into().unwrap(), ::core::mem::transmute_copy(&#name), } } } else if param.ty.is_winrt_array_ref() { quote! { #name.set_abi_len(), #name as *mut _ as _, } - } else if type_is_blittable(¶m.ty) { + } else if metadata::type_is_blittable(¶m.ty) { quote! { #name, } } else { quote! { #name as *mut _ as _, } @@ -173,11 +173,11 @@ fn gen_winrt_abi_args(writer: &Writer, params: &[SignatureParam]) -> TokenStream tokens } -pub fn gen_upcall(writer: &Writer, sig: &Signature, inner: TokenStream) -> TokenStream { +pub fn gen_upcall(writer: &Writer, sig: &metadata::Signature, inner: TokenStream) -> TokenStream { let invoke_args = sig.params.iter().map(|param| gen_winrt_invoke_arg(writer, param)); match &sig.return_type { - Type::Void => quote! { + metadata::Type::Void => quote! { #inner(#(#invoke_args,)*).into() }, _ if sig.return_type.is_winrt_array() => { @@ -195,7 +195,7 @@ pub fn gen_upcall(writer: &Writer, sig: &Signature, inner: TokenStream) -> Token } } _ => { - let forget = if type_is_blittable(&sig.return_type) { + let forget = if metadata::type_is_blittable(&sig.return_type) { quote! {} } else { quote! { ::core::mem::forget(ok__); } @@ -216,18 +216,18 @@ pub fn gen_upcall(writer: &Writer, sig: &Signature, inner: TokenStream) -> Token } } -fn gen_winrt_invoke_arg(writer: &Writer, param: &SignatureParam) -> TokenStream { +fn gen_winrt_invoke_arg(writer: &Writer, param: &metadata::SignatureParam) -> TokenStream { let name = writer.param_name(param.def); let abi_size_name: TokenStream = format!("{}_array_size", param.def.name()).into(); - if param.def.flags().contains(ParamAttributes::In) { + if param.def.flags().contains(metadata::ParamAttributes::In) { if param.ty.is_winrt_array() { quote! { ::core::slice::from_raw_parts(::core::mem::transmute_copy(&#name), #abi_size_name as usize) } - } else if type_is_primitive(¶m.ty) { + } else if metadata::type_is_primitive(¶m.ty) { quote! { #name } } else if param.ty.is_const_ref() { quote! { ::core::mem::transmute_copy(&#name) } - } else if type_is_nullable(¶m.ty) { + } else if metadata::type_is_nullable(¶m.ty) { quote! { ::windows_core::from_raw_borrowed(&#name) } } else { quote! { ::core::mem::transmute(&#name) } diff --git a/crates/libs/bindgen/src/rust/writer.rs b/crates/libs/bindgen/src/rust/writer.rs index 9132953e9d..5e4572efc0 100644 --- a/crates/libs/bindgen/src/rust/writer.rs +++ b/crates/libs/bindgen/src/rust/writer.rs @@ -1,8 +1,9 @@ use super::*; +use metadata::HasAttributes; #[derive(Clone)] pub struct Writer { - pub reader: &'static Reader, + pub reader: &'static metadata::Reader, pub output: String, pub namespace: &'static str, pub implement: bool, // TODO: ideally we can use this to generate implementation traits on the fly and @@ -21,7 +22,7 @@ pub struct Writer { } impl Writer { - pub fn new(reader: &'static Reader, output: &str) -> Self { + pub fn new(reader: &'static metadata::Reader, output: &str) -> Self { Self { reader, output: output.to_string(), @@ -37,16 +38,16 @@ impl Writer { } // - // TypeDef + // metadata::TypeDef // - pub fn type_def_name(&self, def: TypeDef, generics: &[Type]) -> TokenStream { + pub fn type_def_name(&self, def: metadata::TypeDef, generics: &[metadata::Type]) -> TokenStream { self.type_def_name_imp(def, generics, "") } - pub fn type_def_vtbl_name(&self, def: TypeDef, generics: &[Type]) -> TokenStream { + pub fn type_def_vtbl_name(&self, def: metadata::TypeDef, generics: &[metadata::Type]) -> TokenStream { self.type_def_name_imp(def, generics, "_Vtbl") } - pub fn type_def_name_imp(&self, def: TypeDef, generics: &[Type], suffix: &str) -> TokenStream { + pub fn type_def_name_imp(&self, def: metadata::TypeDef, generics: &[metadata::Type], suffix: &str) -> TokenStream { let type_name = def.type_name(); if type_name.namespace.is_empty() { @@ -76,15 +77,15 @@ impl Writer { // Type // - pub fn type_default_name(&self, ty: &Type) -> TokenStream { - if let Type::WinrtArray(ty) = ty { + pub fn type_default_name(&self, ty: &metadata::Type) -> TokenStream { + if let metadata::Type::WinrtArray(ty) = ty { self.type_default_name(ty) } else { let kind = self.type_name(ty); if ty.is_generic() { quote! { <#kind as ::windows_core::Type<#kind>>::Default } - } else if type_is_nullable(ty) && !self.sys { + } else if metadata::type_is_nullable(ty) && !self.sys { quote! { ::core::option::Option<#kind> } } else { kind @@ -92,132 +93,132 @@ impl Writer { } } - pub(crate) fn type_name(&self, ty: &Type) -> TokenStream { + pub(crate) fn type_name(&self, ty: &metadata::Type) -> TokenStream { match ty { - Type::Void => quote! { ::core::ffi::c_void }, - Type::Bool => quote! { bool }, - Type::Char => quote! { u16 }, - Type::I8 => quote! { i8 }, - Type::U8 => quote! { u8 }, - Type::I16 => quote! { i16 }, - Type::U16 => quote! { u16 }, - Type::I32 => quote! { i32 }, - Type::U32 => quote! { u32 }, - Type::I64 => quote! { i64 }, - Type::U64 => quote! { u64 }, - Type::F32 => quote! { f32 }, - Type::F64 => quote! { f64 }, - Type::ISize => quote! { isize }, - Type::USize => quote! { usize }, - Type::String => { + metadata::Type::Void => quote! { ::core::ffi::c_void }, + metadata::Type::Bool => quote! { bool }, + metadata::Type::Char => quote! { u16 }, + metadata::Type::I8 => quote! { i8 }, + metadata::Type::U8 => quote! { u8 }, + metadata::Type::I16 => quote! { i16 }, + metadata::Type::U16 => quote! { u16 }, + metadata::Type::I32 => quote! { i32 }, + metadata::Type::U32 => quote! { u32 }, + metadata::Type::I64 => quote! { i64 }, + metadata::Type::U64 => quote! { u64 }, + metadata::Type::F32 => quote! { f32 }, + metadata::Type::F64 => quote! { f64 }, + metadata::Type::ISize => quote! { isize }, + metadata::Type::USize => quote! { usize }, + metadata::Type::String => { let crate_name = self.crate_name(); quote! { #crate_name HSTRING } } - Type::BSTR => { + metadata::Type::BSTR => { let crate_name = self.crate_name(); quote! { #crate_name BSTR } } - Type::IInspectable => { + metadata::Type::IInspectable => { let crate_name = self.crate_name(); quote! { #crate_name IInspectable } } - Type::GUID => { + metadata::Type::GUID => { let crate_name = self.crate_name(); quote! { #crate_name GUID } } - Type::IUnknown => { + metadata::Type::IUnknown => { let crate_name = self.crate_name(); quote! { #crate_name IUnknown } } - Type::HRESULT => { + metadata::Type::HRESULT => { let crate_name = self.crate_name(); quote! { #crate_name HRESULT } } - Type::PSTR => { + metadata::Type::PSTR => { let crate_name = self.crate_name(); quote! { #crate_name PSTR } } - Type::PWSTR => { + metadata::Type::PWSTR => { let crate_name = self.crate_name(); quote! { #crate_name PWSTR } } - Type::PCSTR => { + metadata::Type::PCSTR => { let crate_name = self.crate_name(); quote! { #crate_name PCSTR } } - Type::PCWSTR => { + metadata::Type::PCWSTR => { let crate_name = self.crate_name(); quote! { #crate_name PCWSTR } } - Type::Win32Array(ty, len) => { + metadata::Type::Win32Array(ty, len) => { let name = self.type_default_name(ty); let len = Literal::usize_unsuffixed(*len); quote! { [#name; #len] } } - Type::GenericParam(generic) => generic.name().into(), - Type::TypeDef(def, generics) => self.type_def_name(*def, generics), - Type::MutPtr(ty, pointers) => { + metadata::Type::GenericParam(generic) => generic.name().into(), + metadata::Type::TypeDef(def, generics) => self.type_def_name(*def, generics), + metadata::Type::MutPtr(ty, pointers) => { let pointers = mut_ptrs(*pointers); let ty = self.type_default_name(ty); quote! { #pointers #ty } } - Type::ConstPtr(ty, pointers) => { + metadata::Type::ConstPtr(ty, pointers) => { let pointers = const_ptrs(*pointers); let ty = self.type_default_name(ty); quote! { #pointers #ty } } - Type::WinrtArray(ty) => self.type_name(ty), - Type::WinrtArrayRef(ty) => self.type_name(ty), - Type::ConstRef(ty) => self.type_name(ty), - Type::PrimitiveOrEnum(_, ty) => self.type_name(ty), + metadata::Type::WinrtArray(ty) => self.type_name(ty), + metadata::Type::WinrtArrayRef(ty) => self.type_name(ty), + metadata::Type::ConstRef(ty) => self.type_name(ty), + metadata::Type::PrimitiveOrEnum(_, ty) => self.type_name(ty), rest => unimplemented!("{rest:?}"), } } - pub fn type_vtbl_name(&self, ty: &Type) -> TokenStream { + pub fn type_vtbl_name(&self, ty: &metadata::Type) -> TokenStream { match ty { - Type::TypeDef(def, generics) => self.type_def_vtbl_name(*def, generics), + metadata::Type::TypeDef(def, generics) => self.type_def_vtbl_name(*def, generics), rest => unimplemented!("{rest:?}"), } } - pub fn type_abi_name(&self, ty: &Type) -> TokenStream { + pub fn type_abi_name(&self, ty: &metadata::Type) -> TokenStream { if self.sys { return match ty { - Type::PrimitiveOrEnum(ty, _) => self.type_default_name(ty), + metadata::Type::PrimitiveOrEnum(ty, _) => self.type_default_name(ty), _ => self.type_default_name(ty), }; } match ty { - Type::IUnknown | Type::IInspectable => { + metadata::Type::IUnknown | metadata::Type::IInspectable => { quote! { *mut ::core::ffi::c_void } } - Type::String => { + metadata::Type::String => { quote! { ::std::mem::MaybeUninit<::windows_core::HSTRING> } } - Type::BSTR => { + metadata::Type::BSTR => { quote! { ::std::mem::MaybeUninit<::windows_core::BSTR> } } - Type::Win32Array(kind, len) => { + metadata::Type::Win32Array(kind, len) => { let name = self.type_abi_name(kind); let len = Literal::usize_unsuffixed(*len); quote! { [#name; #len] } } - Type::GenericParam(generic) => { + metadata::Type::GenericParam(generic) => { let name = to_ident(generic.name()); quote! { ::windows_core::AbiType<#name> } } - Type::TypeDef(def, _) => match def.kind() { - TypeKind::Enum => self.type_def_name(*def, &[]), - TypeKind::Struct => { + metadata::Type::TypeDef(def, _) => match def.kind() { + metadata::TypeKind::Enum => self.type_def_name(*def, &[]), + metadata::TypeKind::Struct => { let tokens = self.type_def_name(*def, &[]); - if type_def_is_blittable(*def) { + if metadata::type_def_is_blittable(*def) { tokens } else { quote! { ::std::mem::MaybeUninit<#tokens> } } } - TypeKind::Delegate => { - if def.flags().contains(TypeAttributes::WindowsRuntime) { + metadata::TypeKind::Delegate => { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { quote! { *mut ::core::ffi::c_void } } else { self.type_def_name(*def, &[]) @@ -225,19 +226,19 @@ impl Writer { } _ => quote! { *mut ::core::ffi::c_void }, }, - Type::MutPtr(kind, pointers) => { + metadata::Type::MutPtr(kind, pointers) => { let pointers_tokens = gen_mut_ptrs(*pointers); let kind = if *pointers > 1 { self.type_name(kind) } else { self.type_abi_name(kind) }; quote! { #pointers_tokens #kind } } - Type::ConstPtr(kind, pointers) => { + metadata::Type::ConstPtr(kind, pointers) => { let pointers_tokens = gen_const_ptrs(*pointers); let kind = if *pointers > 1 { self.type_name(kind) } else { self.type_abi_name(kind) }; quote! { #pointers_tokens #kind } } - Type::WinrtArray(kind) => self.type_abi_name(kind), - Type::WinrtArrayRef(kind) => self.type_abi_name(kind), - Type::PrimitiveOrEnum(ty, _) => self.type_name(ty), + metadata::Type::WinrtArray(kind) => self.type_abi_name(kind), + metadata::Type::WinrtArrayRef(kind) => self.type_abi_name(kind), + metadata::Type::PrimitiveOrEnum(ty, _) => self.type_name(ty), _ => self.type_name(ty), } } @@ -246,7 +247,7 @@ impl Writer { // Constraints // - pub fn generic_phantoms(&self, generics: &[Type]) -> TokenStream { + pub fn generic_phantoms(&self, generics: &[metadata::Type]) -> TokenStream { let mut tokens = TokenStream::new(); for generic in generics { let generic = self.type_name(generic); @@ -254,7 +255,7 @@ impl Writer { } tokens } - pub fn generic_named_phantoms(&self, generics: &[Type]) -> Vec { + pub fn generic_named_phantoms(&self, generics: &[metadata::Type]) -> Vec { generics .iter() .map(|generic| { @@ -263,7 +264,7 @@ impl Writer { }) .collect() } - pub fn generic_constraints(&self, generics: &[Type]) -> TokenStream { + pub fn generic_constraints(&self, generics: &[metadata::Type]) -> TokenStream { let mut tokens = TokenStream::new(); for generic in generics { let generic = self.type_name(generic); @@ -271,7 +272,7 @@ impl Writer { } tokens } - pub fn generic_names(&self, generics: &[Type]) -> TokenStream { + pub fn generic_names(&self, generics: &[metadata::Type]) -> TokenStream { let mut tokens = TokenStream::new(); for generic in generics { let generic = self.type_name(generic); @@ -280,11 +281,11 @@ impl Writer { tokens } /// The signature params which are generic (along with their relative index) - pub fn generic_params<'b>(&'b self, params: &'b [SignatureParam]) -> impl Iterator + 'b { + pub fn generic_params<'b>(&'b self, params: &'b [metadata::SignatureParam]) -> impl Iterator + 'b { params.iter().filter(move |param| param.is_convertible()).enumerate() } /// The generic param names (i.e., `T` in `fn foo()`) - pub fn constraint_generics(&self, params: &[SignatureParam]) -> TokenStream { + pub fn constraint_generics(&self, params: &[metadata::SignatureParam]) -> TokenStream { let mut generics = self.generic_params(params).map(|(position, _)| -> TokenStream { format!("P{position}").into() }).peekable(); if generics.peek().is_some() { @@ -294,7 +295,7 @@ impl Writer { } } /// A `where` clause for some constrained generic params - pub fn where_clause(&self, params: &[SignatureParam]) -> TokenStream { + pub fn where_clause(&self, params: &[metadata::SignatureParam]) -> TokenStream { let constraints = self.param_constraints(params); if !constraints.is_empty() { @@ -303,7 +304,7 @@ impl Writer { quote!() } } - fn param_constraints(&self, params: &[SignatureParam]) -> TokenStream { + fn param_constraints(&self, params: &[metadata::SignatureParam]) -> TokenStream { let mut tokens = TokenStream::new(); let gen_name = |position| { let name: TokenStream = format!("P{position}").into(); @@ -311,12 +312,12 @@ impl Writer { }; for (position, param) in self.generic_params(params) { match param.kind { - SignatureParamKind::TryInto => { + metadata::SignatureParamKind::TryInto => { let name: TokenStream = gen_name(position); let into = self.type_name(¶m.ty); tokens.combine("e! { #name: ::windows_core::TryIntoParam<#into>, }); } - SignatureParamKind::IntoParam => { + metadata::SignatureParamKind::IntoParam => { let name: TokenStream = gen_name(position); let into = self.type_name(¶m.ty); tokens.combine("e! { #name: ::windows_core::IntoParam<#into>, }); @@ -332,7 +333,7 @@ impl Writer { // /// Generates doc comments for types, free functions, and constants. - pub(crate) fn cfg_doc(&self, cfg: &Cfg) -> TokenStream { + pub(crate) fn cfg_doc(&self, cfg: &cfg::Cfg) -> TokenStream { if !self.package { quote! {} } else { @@ -353,7 +354,7 @@ impl Writer { /// Generates doc comments for member functions (methods) and avoids redundantly declaring the /// enclosing module feature required by the method's type. - pub(crate) fn cfg_method_doc(&self, cfg: &Cfg) -> TokenStream { + pub(crate) fn cfg_method_doc(&self, cfg: &cfg::Cfg) -> TokenStream { if !self.package { quote! {} } else { @@ -374,7 +375,7 @@ impl Writer { } } - pub(crate) fn cfg_features(&self, cfg: &Cfg) -> TokenStream { + pub(crate) fn cfg_features(&self, cfg: &cfg::Cfg) -> TokenStream { let arches = &cfg.arches; let arch = match arches.len() { 0 => quote! {}, @@ -403,7 +404,7 @@ impl Writer { quote! { #arch #features } } - fn cfg_features_imp(&self, cfg: &Cfg, namespace: &str) -> Vec<&'static str> { + fn cfg_features_imp(&self, cfg: &cfg::Cfg, namespace: &str) -> Vec<&'static str> { let mut compact = Vec::<&'static str>::new(); if self.package { for feature in cfg.types.keys() { @@ -421,7 +422,7 @@ impl Writer { compact } - fn cfg_not_features(&self, cfg: &Cfg) -> TokenStream { + fn cfg_not_features(&self, cfg: &cfg::Cfg) -> TokenStream { let features = self.cfg_features_imp(cfg, self.namespace); if features.is_empty() { quote! {} @@ -490,7 +491,7 @@ impl Writer { "::windows_core::".into() } } - fn scoped_name(&self, def: TypeDef) -> String { + fn scoped_name(&self, def: metadata::TypeDef) -> String { if let Some(enclosing_type) = def.enclosing_type() { for (index, nested_type) in self.reader.nested_types(enclosing_type).enumerate() { if nested_type.name() == def.name() { @@ -500,20 +501,20 @@ impl Writer { } def.name().to_string() } - pub fn value(&self, value: &Value) -> TokenStream { + pub fn value(&self, value: &metadata::Value) -> TokenStream { match value { - Value::Bool(value) => quote! { #value }, - Value::U8(value) => quote! { #value }, - Value::I8(value) => quote! { #value }, - Value::U16(value) => quote! { #value }, - Value::I16(value) => quote! { #value }, - Value::U32(value) => quote! { #value }, - Value::I32(value) => quote! { #value }, - Value::U64(value) => quote! { #value }, - Value::I64(value) => quote! { #value }, - Value::F32(value) => quote! { #value }, - Value::F64(value) => quote! { #value }, - Value::String(value) => { + metadata::Value::Bool(value) => quote! { #value }, + metadata::Value::U8(value) => quote! { #value }, + metadata::Value::I8(value) => quote! { #value }, + metadata::Value::U16(value) => quote! { #value }, + metadata::Value::I16(value) => quote! { #value }, + metadata::Value::U32(value) => quote! { #value }, + metadata::Value::I32(value) => quote! { #value }, + metadata::Value::U64(value) => quote! { #value }, + metadata::Value::I64(value) => quote! { #value }, + metadata::Value::F32(value) => quote! { #value }, + metadata::Value::F64(value) => quote! { #value }, + metadata::Value::String(value) => { let mut tokens = "\"".to_string(); for u in value.chars() { @@ -526,32 +527,32 @@ impl Writer { rest => unimplemented!("{rest:?}"), } } - pub fn typed_value(&self, value: &Value) -> TokenStream { + pub fn typed_value(&self, value: &metadata::Value) -> TokenStream { let literal = self.value(value); match value { - Value::Bool(_) => quote! { bool = #literal }, - Value::U8(_) => quote! { u8 = #literal }, - Value::I8(_) => quote! { i8 = #literal }, - Value::U16(_) => quote! { u16 = #literal }, - Value::I16(_) => quote! { i16 = #literal }, - Value::U32(_) => quote! { u32 = #literal }, - Value::I32(_) => quote! { i32 = #literal }, - Value::U64(_) => quote! { u64 = #literal }, - Value::I64(_) => quote! { i64 = #literal }, - Value::F32(_) => quote! { f32 = #literal }, - Value::F64(_) => quote! { f64 = #literal }, - Value::String(_) => { + metadata::Value::Bool(_) => quote! { bool = #literal }, + metadata::Value::U8(_) => quote! { u8 = #literal }, + metadata::Value::I8(_) => quote! { i8 = #literal }, + metadata::Value::U16(_) => quote! { u16 = #literal }, + metadata::Value::I16(_) => quote! { i16 = #literal }, + metadata::Value::U32(_) => quote! { u32 = #literal }, + metadata::Value::I32(_) => quote! { i32 = #literal }, + metadata::Value::U64(_) => quote! { u64 = #literal }, + metadata::Value::I64(_) => quote! { i64 = #literal }, + metadata::Value::F32(_) => quote! { f32 = #literal }, + metadata::Value::F64(_) => quote! { f64 = #literal }, + metadata::Value::String(_) => { quote! { &str = #literal } } rest => unimplemented!("{rest:?}"), } } - pub fn guid(&self, value: &Guid) -> TokenStream { - let guid = self.type_name(&Type::GUID); + pub fn guid(&self, value: &metadata::Guid) -> TokenStream { + let guid = self.type_name(&metadata::Type::GUID); format!("{}::from_u128(0x{:08x?}_{:04x?}_{:04x?}_{:02x?}{:02x?}_{:02x?}{:02x?}{:02x?}{:02x?}{:02x?}{:02x?})", guid.into_string(), value.0, value.1, value.2, value.3, value.4, value.5, value.6, value.7, value.8, value.9, value.10).into() } - pub fn agile(&self, def: TypeDef, ident: &TokenStream, constraints: &TokenStream, features: &TokenStream) -> TokenStream { + pub fn agile(&self, def: metadata::TypeDef, ident: &TokenStream, constraints: &TokenStream, features: &TokenStream) -> TokenStream { if type_def_is_agile(def) { quote! { #features @@ -563,15 +564,15 @@ impl Writer { quote! {} } } - pub fn async_get(&self, def: TypeDef, generics: &[Type], ident: &TokenStream, constraints: &TokenStream, _phantoms: &TokenStream, features: &TokenStream) -> TokenStream { + pub fn async_get(&self, def: metadata::TypeDef, generics: &[metadata::Type], ident: &TokenStream, constraints: &TokenStream, _phantoms: &TokenStream, features: &TokenStream) -> TokenStream { let mut kind = type_def_async_kind(def); let mut async_generics = generics.to_vec(); - if kind == AsyncKind::None { + if kind == metadata::AsyncKind::None { for interface in def.interface_impls().map(move |imp| imp.ty(generics)) { - if let Type::TypeDef(interface_def, interface_generics) = &interface { + if let metadata::Type::TypeDef(interface_def, interface_generics) = &interface { kind = type_def_async_kind(*interface_def); - if kind != AsyncKind::None { + if kind != metadata::AsyncKind::None { async_generics = interface_generics.to_vec(); break; } @@ -579,19 +580,19 @@ impl Writer { } } - if kind == AsyncKind::None { + if kind == metadata::AsyncKind::None { quote! {} } else { let return_type = match kind { - AsyncKind::Operation | AsyncKind::OperationWithProgress => self.type_name(&async_generics[0]), + metadata::AsyncKind::Operation | metadata::AsyncKind::OperationWithProgress => self.type_name(&async_generics[0]), _ => quote! { () }, }; let handler = match kind { - AsyncKind::Action => quote! { AsyncActionCompletedHandler }, - AsyncKind::ActionWithProgress => quote! { AsyncActionWithProgressCompletedHandler }, - AsyncKind::Operation => quote! { AsyncOperationCompletedHandler }, - AsyncKind::OperationWithProgress => { + metadata::AsyncKind::Action => quote! { AsyncActionCompletedHandler }, + metadata::AsyncKind::ActionWithProgress => quote! { AsyncActionWithProgressCompletedHandler }, + metadata::AsyncKind::Operation => quote! { AsyncOperationCompletedHandler }, + metadata::AsyncKind::OperationWithProgress => { quote! { AsyncOperationWithProgressCompletedHandler } } rest => unimplemented!("{rest:?}"), @@ -636,16 +637,16 @@ impl Writer { } } } - pub fn interface_winrt_trait(&self, def: TypeDef, generics: &[Type], ident: &TokenStream, constraints: &TokenStream, _phantoms: &TokenStream, features: &TokenStream) -> TokenStream { - if def.flags().contains(TypeAttributes::WindowsRuntime) { - let type_signature = if def.kind() == TypeKind::Class { + pub fn interface_winrt_trait(&self, def: metadata::TypeDef, generics: &[metadata::Type], ident: &TokenStream, constraints: &TokenStream, _phantoms: &TokenStream, features: &TokenStream) -> TokenStream { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { + let type_signature = if def.kind() == metadata::TypeKind::Class { quote! { ::windows_core::imp::ConstBuffer::for_class::() } } else if generics.is_empty() { quote! { ::windows_core::imp::ConstBuffer::for_interface::() } } else { let signature = Literal::byte_string( // TODO: workaround for riddle winmd generation (no attribute support) - if let Some(guid) = type_def_guid(def) { format!("{{{:#?}}}", guid) } else { "TODO".to_string() }.as_bytes(), + if let Some(guid) = metadata::type_def_guid(def) { format!("{{{:#?}}}", guid) } else { "TODO".to_string() }.as_bytes(), ); let generics = generics.iter().enumerate().map(|(index, g)| { @@ -686,8 +687,8 @@ impl Writer { quote! {} } } - pub fn runtime_name_trait(&self, def: TypeDef, _generics: &[Type], name: &TokenStream, constraints: &TokenStream, features: &TokenStream) -> TokenStream { - if def.flags().contains(TypeAttributes::WindowsRuntime) { + pub fn runtime_name_trait(&self, def: metadata::TypeDef, _generics: &[metadata::Type], name: &TokenStream, constraints: &TokenStream, features: &TokenStream) -> TokenStream { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { // TODO: this needs to use a ConstBuffer-like facility to accomodate generics let runtime_name = format!("{}", def.type_name()); @@ -705,8 +706,8 @@ impl Writer { } } - pub fn interface_trait(&self, def: TypeDef, generics: &[Type], ident: &TokenStream, constraints: &TokenStream, features: &TokenStream, has_unknown_base: bool) -> TokenStream { - if let Some(default) = type_def_default_interface(def) { + pub fn interface_trait(&self, def: metadata::TypeDef, generics: &[metadata::Type], ident: &TokenStream, constraints: &TokenStream, features: &TokenStream, has_unknown_base: bool) -> TokenStream { + if let Some(default) = metadata::type_def_default_interface(def) { let default_name = self.type_name(&default); let vtbl = self.type_vtbl_name(&default); quote! { @@ -722,7 +723,7 @@ impl Writer { } else { let vtbl = self.type_def_vtbl_name(def, generics); let guid = if generics.is_empty() { - match type_def_guid(def) { + match metadata::type_def_guid(def) { Some(guid) => self.guid(&guid), None => { quote! { @@ -755,17 +756,17 @@ impl Writer { tokens } } - pub fn interface_vtbl(&self, def: TypeDef, generics: &[Type], _ident: &TokenStream, constraints: &TokenStream, features: &TokenStream) -> TokenStream { + pub fn interface_vtbl(&self, def: metadata::TypeDef, generics: &[metadata::Type], _ident: &TokenStream, constraints: &TokenStream, features: &TokenStream) -> TokenStream { let vtbl = self.type_def_vtbl_name(def, generics); let mut methods = quote! {}; let mut method_names = MethodNames::new(); method_names.add_vtable_types(def); let phantoms = self.generic_named_phantoms(generics); - match type_def_vtables(def).last() { - Some(Type::IUnknown) => methods.combine("e! { pub base__: ::windows_core::IUnknown_Vtbl, }), - Some(Type::IInspectable) => methods.combine("e! { pub base__: ::windows_core::IInspectable_Vtbl, }), - Some(Type::TypeDef(def, _)) => { + match metadata::type_def_vtables(def).last() { + Some(metadata::Type::IUnknown) => methods.combine("e! { pub base__: ::windows_core::IUnknown_Vtbl, }), + Some(metadata::Type::IInspectable) => methods.combine("e! { pub base__: ::windows_core::IInspectable_Vtbl, }), + Some(metadata::Type::TypeDef(def, _)) => { let vtbl = self.type_def_vtbl_name(*def, &[]); methods.combine("e! { pub base__: #vtbl, }); } @@ -777,8 +778,8 @@ impl Writer { continue; } let name = method_names.add(method); - let signature = method_def_signature(def.namespace(), method, generics); - let mut cfg = signature_cfg(method); + let signature = metadata::method_def_signature(def.namespace(), method, generics); + let mut cfg = cfg::signature_cfg(method); let signature = self.vtbl_signature(def, generics, &signature); cfg.add_feature(def.namespace()); let cfg_all = self.cfg_features(&cfg); @@ -806,15 +807,15 @@ impl Writer { } } } - pub fn vtbl_signature(&self, def: TypeDef, _generics: &[Type], signature: &Signature) -> TokenStream { - let is_winrt = def.flags().contains(TypeAttributes::WindowsRuntime); + pub fn vtbl_signature(&self, def: metadata::TypeDef, _generics: &[metadata::Type], signature: &metadata::Signature) -> TokenStream { + let is_winrt = def.flags().contains(metadata::TypeAttributes::WindowsRuntime); let crate_name = self.crate_name(); let (trailing_return_type, return_type, udt_return_type) = match &signature.return_type { - Type::Void if is_winrt => (quote! {}, quote! { -> #crate_name HRESULT }, quote! {}), - Type::Void => (quote! {}, quote! {}, quote! {}), - Type::WinrtArray(kind) => { + metadata::Type::Void if is_winrt => (quote! {}, quote! { -> #crate_name HRESULT }, quote! {}), + metadata::Type::Void => (quote! {}, quote! {}, quote! {}), + metadata::Type::WinrtArray(kind) => { let tokens = self.type_abi_name(kind); (quote! { result_size__: *mut u32, result__: *mut *mut #tokens }, quote! { -> #crate_name HRESULT }, quote! {}) } @@ -822,7 +823,7 @@ impl Writer { let tokens = self.type_abi_name(&signature.return_type); (quote! { result__: *mut #tokens }, quote! { -> #crate_name HRESULT }, quote! {}) } - _ if type_is_struct(&signature.return_type) => { + _ if metadata::type_is_struct(&signature.return_type) => { let tokens = self.type_abi_name(&signature.return_type); (quote! {}, quote! {}, quote! { result__: *mut #tokens, }) } @@ -838,7 +839,7 @@ impl Writer { let abi = self.type_abi_name(&p.ty); let abi_size_name: TokenStream = format!("{}_array_size", p.def.name()).into(); - if p.def.flags().contains(ParamAttributes::In) { + if p.def.flags().contains(metadata::ParamAttributes::In) { if p.ty.is_winrt_array() { quote! { #abi_size_name: u32, #name: *const #abi, } } else if p.ty.is_const_ref() { @@ -855,7 +856,7 @@ impl Writer { } } else { match p.kind { - SignatureParamKind::ValueType => { + metadata::SignatureParamKind::ValueType => { let abi = self.type_default_name(&p.ty); quote! { #name: #abi, } } @@ -869,83 +870,83 @@ impl Writer { quote! { (this: *mut ::core::ffi::c_void, #udt_return_type #(#params)* #trailing_return_type) #return_type } } - pub fn param_name(&self, param: Param) -> TokenStream { + pub fn param_name(&self, param: metadata::Param) -> TokenStream { // In Rust, function parameters cannot be named the same as structs. This avoids some collisions that occur in the win32 metadata. // See Icmp6SendEcho2 for an example. to_ident(¶m.name().to_lowercase()) } - pub fn return_sig(&self, signature: &Signature) -> TokenStream { + pub fn return_sig(&self, signature: &metadata::Signature) -> TokenStream { match &signature.return_type { - Type::Void if signature.def.has_attribute("DoesNotReturnAttribute") => " -> !".into(), - Type::Void => TokenStream::new(), + metadata::Type::Void if signature.def.has_attribute("DoesNotReturnAttribute") => " -> !".into(), + metadata::Type::Void => TokenStream::new(), _ => { let tokens = self.type_default_name(&signature.return_type); format!(" -> {}", tokens.as_str()).into() } } } - pub fn win32_args(&self, params: &[SignatureParam], kind: SignatureKind) -> TokenStream { + pub fn win32_args(&self, params: &[metadata::SignatureParam], kind: metadata::SignatureKind) -> TokenStream { let mut tokens = quote! {}; for (position, param) in params.iter().enumerate() { let new = match kind { - SignatureKind::Query(query) if query.object == position => { + metadata::SignatureKind::Query(query) if query.object == position => { quote! { &mut result__, } } - SignatureKind::ReturnValue | SignatureKind::ResultValue if params.len() - 1 == position => { + metadata::SignatureKind::ReturnValue | metadata::SignatureKind::ResultValue if params.len() - 1 == position => { quote! { &mut result__, } } - SignatureKind::QueryOptional(query) if query.object == position => { + metadata::SignatureKind::QueryOptional(query) if query.object == position => { quote! { result__ as *mut _ as *mut _, } } - SignatureKind::Query(query) | SignatureKind::QueryOptional(query) if query.guid == position => { + metadata::SignatureKind::Query(query) | metadata::SignatureKind::QueryOptional(query) if query.guid == position => { quote! { &::IID, } } _ => { let name = self.param_name(param.def); let flags = param.def.flags(); match param.kind { - SignatureParamKind::ArrayFixed(_) | SignatureParamKind::ArrayRelativeLen(_) | SignatureParamKind::ArrayRelativeByteLen(_) => { - let map = if flags.contains(ParamAttributes::Optional) { + metadata::SignatureParamKind::ArrayFixed(_) | metadata::SignatureParamKind::ArrayRelativeLen(_) | metadata::SignatureParamKind::ArrayRelativeByteLen(_) => { + let map = if flags.contains(metadata::ParamAttributes::Optional) { quote! { #name.as_deref().map_or(::core::ptr::null(), |slice|slice.as_ptr()) } } else { quote! { #name.as_ptr() } }; quote! { ::core::mem::transmute(#map), } } - SignatureParamKind::ArrayRelativePtr(relative) => { + metadata::SignatureParamKind::ArrayRelativePtr(relative) => { let name = self.param_name(params[relative].def); let flags = params[relative].def.flags(); - if flags.contains(ParamAttributes::Optional) { + if flags.contains(metadata::ParamAttributes::Optional) { quote! { #name.as_deref().map_or(0, |slice|slice.len().try_into().unwrap()), } } else { quote! { #name.len().try_into().unwrap(), } } } - SignatureParamKind::TryInto => { + metadata::SignatureParamKind::TryInto => { quote! { #name.try_into_param()?.abi(), } } - SignatureParamKind::IntoParam => { + metadata::SignatureParamKind::IntoParam => { quote! { #name.into_param().abi(), } } - SignatureParamKind::OptionalPointer => { - if flags.contains(ParamAttributes::Out) { + metadata::SignatureParamKind::OptionalPointer => { + if flags.contains(metadata::ParamAttributes::Out) { quote! { ::core::mem::transmute(#name.unwrap_or(::std::ptr::null_mut())), } } else { quote! { ::core::mem::transmute(#name.unwrap_or(::std::ptr::null())), } } } - SignatureParamKind::ValueType => { + metadata::SignatureParamKind::ValueType => { quote! { #name, } } - SignatureParamKind::Blittable => { - if matches!(param.ty, Type::PrimitiveOrEnum(_, _)) { + metadata::SignatureParamKind::Blittable => { + if matches!(param.ty, metadata::Type::PrimitiveOrEnum(_, _)) { quote! { #name.0 as _, } } else { quote! { ::core::mem::transmute(#name), } } } - SignatureParamKind::Other => { + metadata::SignatureParamKind::Other => { quote! { ::core::mem::transmute_copy(#name), } } } @@ -956,18 +957,18 @@ impl Writer { tokens } - pub fn win32_params(&self, params: &[SignatureParam], kind: SignatureKind) -> TokenStream { + pub fn win32_params(&self, params: &[metadata::SignatureParam], kind: metadata::SignatureKind) -> TokenStream { let mut tokens = quote! {}; let mut generic_params = self.generic_params(params); for (position, param) in params.iter().enumerate() { match kind { - SignatureKind::Query(query) | SignatureKind::QueryOptional(query) => { + metadata::SignatureKind::Query(query) | metadata::SignatureKind::QueryOptional(query) => { if query.object == position || query.guid == position { continue; } } - SignatureKind::ReturnValue | SignatureKind::ResultValue if params.len() - 1 == position => { + metadata::SignatureKind::ReturnValue | metadata::SignatureKind::ResultValue if params.len() - 1 == position => { continue; } _ => {} @@ -976,62 +977,62 @@ impl Writer { let name = self.param_name(param.def); match param.kind { - SignatureParamKind::ArrayFixed(fixed) => { + metadata::SignatureParamKind::ArrayFixed(fixed) => { let ty = param.ty.deref(); let ty = self.type_default_name(&ty); let len = Literal::u32_unsuffixed(fixed as u32); - let ty = if param.def.flags().contains(ParamAttributes::Out) { + let ty = if param.def.flags().contains(metadata::ParamAttributes::Out) { quote! { &mut [#ty; #len] } } else { quote! { &[#ty; #len] } }; - if param.def.flags().contains(ParamAttributes::Optional) { + if param.def.flags().contains(metadata::ParamAttributes::Optional) { tokens.combine("e! { #name: ::core::option::Option<#ty>, }); } else { tokens.combine("e! { #name: #ty, }); } } - SignatureParamKind::ArrayRelativeLen(_) => { + metadata::SignatureParamKind::ArrayRelativeLen(_) => { let ty = param.ty.deref(); let ty = self.type_default_name(&ty); - let ty = if param.def.flags().contains(ParamAttributes::Out) { + let ty = if param.def.flags().contains(metadata::ParamAttributes::Out) { quote! { &mut [#ty] } } else { quote! { &[#ty] } }; - if param.def.flags().contains(ParamAttributes::Optional) { + if param.def.flags().contains(metadata::ParamAttributes::Optional) { tokens.combine("e! { #name: ::core::option::Option<#ty>, }); } else { tokens.combine("e! { #name: #ty, }); } } - SignatureParamKind::ArrayRelativeByteLen(_) => { - let ty = if param.def.flags().contains(ParamAttributes::Out) { + metadata::SignatureParamKind::ArrayRelativeByteLen(_) => { + let ty = if param.def.flags().contains(metadata::ParamAttributes::Out) { quote! { &mut [u8] } } else { quote! { &[u8] } }; - if param.def.flags().contains(ParamAttributes::Optional) { + if param.def.flags().contains(metadata::ParamAttributes::Optional) { tokens.combine("e! { #name: ::core::option::Option<#ty>, }); } else { tokens.combine("e! { #name: #ty, }); } } - SignatureParamKind::ArrayRelativePtr(_) => {} - SignatureParamKind::TryInto | SignatureParamKind::IntoParam => { + metadata::SignatureParamKind::ArrayRelativePtr(_) => {} + metadata::SignatureParamKind::TryInto | metadata::SignatureParamKind::IntoParam => { let (position, _) = generic_params.next().unwrap(); let kind: TokenStream = format!("P{position}").into(); tokens.combine("e! { #name: #kind, }); } - SignatureParamKind::OptionalPointer => { + metadata::SignatureParamKind::OptionalPointer => { let kind = self.type_default_name(¶m.ty); tokens.combine("e! { #name: ::core::option::Option<#kind>, }); } - SignatureParamKind::ValueType | SignatureParamKind::Blittable => { + metadata::SignatureParamKind::ValueType | metadata::SignatureParamKind::Blittable => { let kind = self.type_default_name(¶m.ty); tokens.combine("e! { #name: #kind, }); } - SignatureParamKind::Other => { + metadata::SignatureParamKind::Other => { let kind = self.type_default_name(¶m.ty); tokens.combine("e! { #name: &#kind, }); } @@ -1041,13 +1042,13 @@ impl Writer { tokens } - pub fn impl_signature(&self, def: TypeDef, signature: &Signature) -> TokenStream { - if def.flags().contains(TypeAttributes::WindowsRuntime) { - let is_delegate = def.kind() == TypeKind::Delegate; + pub fn impl_signature(&self, def: metadata::TypeDef, signature: &metadata::Signature) -> TokenStream { + if def.flags().contains(metadata::TypeAttributes::WindowsRuntime) { + let is_delegate = def.kind() == metadata::TypeKind::Delegate; let params = signature.params.iter().map(|p| self.winrt_produce_type(p, !is_delegate)); let return_type = match &signature.return_type { - Type::Void => quote! { () }, + metadata::Type::Void => quote! { () }, _ => { let tokens = self.type_name(&signature.return_type); @@ -1070,7 +1071,7 @@ impl Writer { let signature_kind = signature.kind(); let mut params = quote! {}; - if signature_kind == SignatureKind::ResultValue { + if signature_kind == metadata::SignatureKind::ResultValue { for param in &signature.params[..signature.params.len() - 1] { params.combine(&self.win32_produce_type(param)); } @@ -1081,9 +1082,9 @@ impl Writer { } let return_type = match signature_kind { - SignatureKind::ReturnVoid => quote! {}, - SignatureKind::Query(_) | SignatureKind::QueryOptional(_) | SignatureKind::ResultVoid => quote! { -> ::windows_core::Result<()> }, - SignatureKind::ResultValue => { + metadata::SignatureKind::ReturnVoid => quote! {}, + metadata::SignatureKind::Query(_) | metadata::SignatureKind::QueryOptional(_) | metadata::SignatureKind::ResultVoid => quote! { -> ::windows_core::Result<()> }, + metadata::SignatureKind::ResultValue => { let return_type = signature.params[signature.params.len() - 1].ty.deref(); let return_type = self.type_name(&return_type); @@ -1095,15 +1096,15 @@ impl Writer { quote! { (&self, #params) #return_type } } } - fn winrt_produce_type(&self, param: &SignatureParam, include_param_names: bool) -> TokenStream { + fn winrt_produce_type(&self, param: &metadata::SignatureParam, include_param_names: bool) -> TokenStream { let default_type = self.type_default_name(¶m.ty); - let sig = if param.def.flags().contains(ParamAttributes::In) { + let sig = if param.def.flags().contains(metadata::ParamAttributes::In) { if param.ty.is_winrt_array() { quote! { &[#default_type] } - } else if type_is_primitive(¶m.ty) { + } else if metadata::type_is_primitive(¶m.ty) { quote! { #default_type } - } else if type_is_nullable(¶m.ty) { + } else if metadata::type_is_nullable(¶m.ty) { let type_name = self.type_name(¶m.ty); quote! { ::core::option::Option<&#type_name> } } else { @@ -1125,14 +1126,14 @@ impl Writer { sig } } - fn win32_produce_type(&self, param: &SignatureParam) -> TokenStream { + fn win32_produce_type(&self, param: &metadata::SignatureParam) -> TokenStream { let name = self.param_name(param.def); let kind = self.type_default_name(¶m.ty); - if param.def.flags().contains(ParamAttributes::In) { - if type_is_primitive(¶m.ty) { + if param.def.flags().contains(metadata::ParamAttributes::In) { + if metadata::type_is_primitive(¶m.ty) { quote! { #name: #kind, } - } else if type_is_nullable(¶m.ty) { + } else if metadata::type_is_nullable(¶m.ty) { let kind = self.type_name(¶m.ty); quote! { #name: ::core::option::Option<&#kind>, } } else { @@ -1199,23 +1200,23 @@ fn gen_const_ptrs(pointers: usize) -> TokenStream { "*const ".repeat(pointers).into() } -fn type_def_async_kind(row: TypeDef) -> AsyncKind { +fn type_def_async_kind(row: metadata::TypeDef) -> metadata::AsyncKind { match row.type_name() { - TypeName::IAsyncAction => AsyncKind::Action, - TypeName::IAsyncActionWithProgress => AsyncKind::ActionWithProgress, - TypeName::IAsyncOperation => AsyncKind::Operation, - TypeName::IAsyncOperationWithProgress => AsyncKind::OperationWithProgress, - _ => AsyncKind::None, + metadata::TypeName::IAsyncAction => metadata::AsyncKind::Action, + metadata::TypeName::IAsyncActionWithProgress => metadata::AsyncKind::ActionWithProgress, + metadata::TypeName::IAsyncOperation => metadata::AsyncKind::Operation, + metadata::TypeName::IAsyncOperationWithProgress => metadata::AsyncKind::OperationWithProgress, + _ => metadata::AsyncKind::None, } } -fn type_def_is_agile(row: TypeDef) -> bool { +fn type_def_is_agile(row: metadata::TypeDef) -> bool { for attribute in row.attributes() { match attribute.name() { "AgileAttribute" => return true, "MarshalingBehaviorAttribute" => { - if let Some((_, Value::EnumDef(_, value))) = attribute.args().first() { - if let Value::I32(2) = **value { + if let Some((_, metadata::Value::EnumDef(_, value))) = attribute.args().first() { + if let metadata::Value::I32(2) = **value { return true; } } @@ -1223,7 +1224,7 @@ fn type_def_is_agile(row: TypeDef) -> bool { _ => {} } } - matches!(row.type_name(), TypeName::IAsyncAction | TypeName::IAsyncActionWithProgress | TypeName::IAsyncOperation | TypeName::IAsyncOperationWithProgress) + matches!(row.type_name(), metadata::TypeName::IAsyncAction | metadata::TypeName::IAsyncActionWithProgress | metadata::TypeName::IAsyncOperation | metadata::TypeName::IAsyncOperationWithProgress) } #[cfg(test)] diff --git a/crates/libs/bindgen/src/tokens/token_stream.rs b/crates/libs/bindgen/src/tokens/token_stream.rs index 3b3a09bdd8..0218a3bb69 100644 --- a/crates/libs/bindgen/src/tokens/token_stream.rs +++ b/crates/libs/bindgen/src/tokens/token_stream.rs @@ -85,7 +85,7 @@ impl Default for TokenStream { } } -impl core::iter::FromIterator for TokenStream { +impl FromIterator for TokenStream { fn from_iter>(iter: I) -> Self { iter.into_iter() .fold(None, |accum: Option, n| { diff --git a/crates/libs/bindgen/src/winmd/from_reader.rs b/crates/libs/bindgen/src/winmd/from_reader.rs index ed5f4d1783..5771568257 100644 --- a/crates/libs/bindgen/src/winmd/from_reader.rs +++ b/crates/libs/bindgen/src/winmd/from_reader.rs @@ -1,15 +1,14 @@ use super::*; -use crate::winmd::{self, writer}; -pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap<&str, &str>, output: &str) -> crate::Result<()> { - let mut writer = winmd::Writer::new(output); +pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap<&str, &str>, output: &str) -> Result<()> { + let mut writer = Writer::new(output); // TODO: do we need any configuration values for winmd generation? // Maybe per-namespace winmd files for namespace-splitting - be sure to use // the same key as for winmd generation. if let Some((key, _)) = config.first_key_value() { - return Err(crate::Error::new(&format!("invalid configuration value `{key}`"))); + return Err(Error::new(&format!("invalid configuration value `{key}`"))); } // TODO: just use the reader directly since we now have everything in the reader, there's no need to abstract @@ -25,7 +24,7 @@ pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap let extends = if let Some(extends) = def.extends() { writer.insert_type_ref(extends.namespace, extends.name) } else { 0 }; - writer.tables.TypeDef.push(writer::TypeDef { + writer.tables.TypeDef.push(TypeDef { Extends: extends, FieldList: writer.tables.Field.len() as u32, Flags: def.flags().0, @@ -35,10 +34,10 @@ pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap }); for generic in def.generics() { - writer.tables.GenericParam.push(writer::GenericParam { + writer.tables.GenericParam.push(GenericParam { Number: generic.number(), // TODO: isn't this just going to be incremental? Flags: 0, - Owner: writer::TypeOrMethodDef::TypeDef(writer.tables.TypeDef.len() as u32 - 1).encode(), + Owner: TypeOrMethodDef::TypeDef(writer.tables.TypeDef.len() as u32 - 1).encode(), Name: writer.strings.insert(generic.name()), }); } @@ -47,14 +46,14 @@ pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap let ty = winmd_type(&interface.ty); let reference = match &ty { - winmd::Type::TypeRef(type_name) if type_name.generics.is_empty() => writer.insert_type_ref(&type_name.namespace, &type_name.name), - winmd::Type::TypeRef(_) => writer.insert_type_spec(ty), - winmd::Type::IUnknown => writer.insert_type_ref("Windows.Win32.System.Com", "IUnknown"), - winmd::Type::IInspectable => writer.insert_type_ref("Windows.Win32.System.WinRT", "IInspectable"), + Type::TypeRef(type_name) if type_name.generics.is_empty() => writer.insert_type_ref(&type_name.namespace, &type_name.name), + Type::TypeRef(_) => writer.insert_type_spec(ty), + Type::IUnknown => writer.insert_type_ref("Windows.Win32.System.Com", "IUnknown"), + Type::IInspectable => writer.insert_type_ref("Windows.Win32.System.WinRT", "IInspectable"), rest => unimplemented!("{rest:?}"), }; - writer.tables.InterfaceImpl.push(writer::InterfaceImpl { Class: writer.tables.TypeDef.len() as u32 - 1, Interface: reference }); + writer.tables.InterfaceImpl.push(InterfaceImpl { Class: writer.tables.TypeDef.len() as u32 - 1, Interface: reference }); } // TODO: if the class is "Apis" then should we sort the fields (constants) and methods (functions) for stability @@ -63,7 +62,7 @@ pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap let ty = winmd_type(&field.ty(Some(def))); let signature = writer.insert_field_sig(&ty); - writer.tables.Field.push(writer::Field { Flags: field.flags().0, Name: writer.strings.insert(field.name()), Signature: signature }); + writer.tables.Field.push(Field { Flags: field.flags().0, Name: writer.strings.insert(field.name()), Signature: signature }); } for method in def.methods() { @@ -73,7 +72,7 @@ pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap let signature = writer.insert_method_sig(signature.call_flags, &return_type, ¶m_types); - writer.tables.MethodDef.push(winmd::MethodDef { + writer.tables.MethodDef.push(MethodDef { RVA: 0, ImplFlags: method.impl_flags().0, Flags: method.flags().0, @@ -83,53 +82,53 @@ pub fn from_reader(reader: &metadata::Reader, config: std::collections::BTreeMap }); for param in method.params() { - writer.tables.Param.push(writer::Param { Flags: param.flags().0, Sequence: param.sequence(), Name: writer.strings.insert(param.name()) }); + writer.tables.Param.push(Param { Flags: param.flags().0, Sequence: param.sequence(), Name: writer.strings.insert(param.name()) }); } } } // TODO: In theory, `config` could instruct this function to balance the types across a number of winmd files // like mdmerge supports for namespace-splitting. - crate::write_to_file(output, writer.into_stream()).map_err(|err| err.with_path(output)) + write_to_file(output, writer.into_stream()).map_err(|err| err.with_path(output)) } // TODO: keep the basic type conversion -fn winmd_type(ty: &metadata::Type) -> winmd::Type { +fn winmd_type(ty: &metadata::Type) -> Type { match ty { - metadata::Type::Void => winmd::Type::Void, - metadata::Type::Bool => winmd::Type::Bool, - metadata::Type::Char => winmd::Type::Char, - metadata::Type::I8 => winmd::Type::I8, - metadata::Type::U8 => winmd::Type::U8, - metadata::Type::I16 => winmd::Type::I16, - metadata::Type::U16 => winmd::Type::U16, - metadata::Type::I32 => winmd::Type::I32, - metadata::Type::U32 => winmd::Type::U32, - metadata::Type::I64 => winmd::Type::I64, - metadata::Type::U64 => winmd::Type::U64, - metadata::Type::F32 => winmd::Type::F32, - metadata::Type::F64 => winmd::Type::F64, - metadata::Type::ISize => winmd::Type::ISize, - metadata::Type::USize => winmd::Type::USize, - metadata::Type::String => winmd::Type::String, - metadata::Type::GUID => winmd::Type::GUID, - metadata::Type::IUnknown => winmd::Type::IUnknown, - metadata::Type::IInspectable => winmd::Type::IInspectable, - metadata::Type::HRESULT => winmd::Type::HRESULT, - metadata::Type::PSTR => winmd::Type::PSTR, - metadata::Type::PWSTR => winmd::Type::PWSTR, - metadata::Type::PCSTR => winmd::Type::PCSTR, - metadata::Type::PCWSTR => winmd::Type::PCWSTR, - metadata::Type::BSTR => winmd::Type::BSTR, - metadata::Type::Type => winmd::Type::Type, - metadata::Type::TypeDef(def, generics) => winmd::Type::TypeRef(winmd::TypeName { namespace: def.namespace().to_string(), name: def.name().to_string(), generics: generics.iter().map(winmd_type).collect() }), - metadata::Type::GenericParam(generic) => winmd::Type::GenericParam(generic.number()), - metadata::Type::ConstRef(ty) => winmd::Type::ConstRef(Box::new(winmd_type(ty))), - metadata::Type::WinrtArrayRef(ty) => winmd::Type::WinrtArrayRef(Box::new(winmd_type(ty))), - metadata::Type::WinrtArray(ty) => winmd::Type::WinrtArray(Box::new(winmd_type(ty))), - metadata::Type::MutPtr(ty, pointers) => winmd::Type::MutPtr(Box::new(winmd_type(ty)), *pointers), - metadata::Type::ConstPtr(ty, pointers) => winmd::Type::ConstPtr(Box::new(winmd_type(ty)), *pointers), - metadata::Type::Win32Array(ty, len) => winmd::Type::Win32Array(Box::new(winmd_type(ty)), *len), + metadata::Type::Void => Type::Void, + metadata::Type::Bool => Type::Bool, + metadata::Type::Char => Type::Char, + metadata::Type::I8 => Type::I8, + metadata::Type::U8 => Type::U8, + metadata::Type::I16 => Type::I16, + metadata::Type::U16 => Type::U16, + metadata::Type::I32 => Type::I32, + metadata::Type::U32 => Type::U32, + metadata::Type::I64 => Type::I64, + metadata::Type::U64 => Type::U64, + metadata::Type::F32 => Type::F32, + metadata::Type::F64 => Type::F64, + metadata::Type::ISize => Type::ISize, + metadata::Type::USize => Type::USize, + metadata::Type::String => Type::String, + metadata::Type::GUID => Type::GUID, + metadata::Type::IUnknown => Type::IUnknown, + metadata::Type::IInspectable => Type::IInspectable, + metadata::Type::HRESULT => Type::HRESULT, + metadata::Type::PSTR => Type::PSTR, + metadata::Type::PWSTR => Type::PWSTR, + metadata::Type::PCSTR => Type::PCSTR, + metadata::Type::PCWSTR => Type::PCWSTR, + metadata::Type::BSTR => Type::BSTR, + metadata::Type::Type => Type::Type, + metadata::Type::TypeDef(def, generics) => Type::TypeRef(TypeName { namespace: def.namespace().to_string(), name: def.name().to_string(), generics: generics.iter().map(winmd_type).collect() }), + metadata::Type::GenericParam(generic) => Type::GenericParam(generic.number()), + metadata::Type::ConstRef(ty) => Type::ConstRef(Box::new(winmd_type(ty))), + metadata::Type::WinrtArrayRef(ty) => Type::WinrtArrayRef(Box::new(winmd_type(ty))), + metadata::Type::WinrtArray(ty) => Type::WinrtArray(Box::new(winmd_type(ty))), + metadata::Type::MutPtr(ty, pointers) => Type::MutPtr(Box::new(winmd_type(ty)), *pointers), + metadata::Type::ConstPtr(ty, pointers) => Type::ConstPtr(Box::new(winmd_type(ty)), *pointers), + metadata::Type::Win32Array(ty, len) => Type::Win32Array(Box::new(winmd_type(ty)), *len), rest => unimplemented!("{rest:?}"), } } diff --git a/crates/libs/bindgen/src/winmd/verify.rs b/crates/libs/bindgen/src/winmd/verify.rs index c376d9d19d..f322b6ce62 100644 --- a/crates/libs/bindgen/src/winmd/verify.rs +++ b/crates/libs/bindgen/src/winmd/verify.rs @@ -1,6 +1,6 @@ use super::*; -pub fn verify(reader: &metadata::Reader) -> crate::Result<()> { +pub fn verify(reader: &metadata::Reader) -> Result<()> { let unused: Vec<&str> = reader.unused().collect(); if !unused.is_empty() { @@ -10,7 +10,7 @@ pub fn verify(reader: &metadata::Reader) -> crate::Result<()> { message.push_str(&format!("\n {unused}")); } - return Err(crate::Error::new(&message)); + return Err(Error::new(&message)); } for item in reader.items() { @@ -34,9 +34,9 @@ pub fn verify(reader: &metadata::Reader) -> crate::Result<()> { Ok(()) } -fn not_type_ref(ty: &metadata::Type) -> crate::Result<()> { +fn not_type_ref(ty: &metadata::Type) -> Result<()> { if let metadata::Type::TypeRef(ty) = ty { - return Err(crate::Error::new(&format!("missing type definition `{}`", ty))); + return Err(Error::new(&format!("missing type definition `{}`", ty))); } Ok(()) } diff --git a/crates/libs/bindgen/src/winmd/writer/blobs.rs b/crates/libs/bindgen/src/winmd/writer/blobs.rs index 5201a32d08..f24bac338a 100644 --- a/crates/libs/bindgen/src/winmd/writer/blobs.rs +++ b/crates/libs/bindgen/src/winmd/writer/blobs.rs @@ -1,5 +1,4 @@ use super::*; -use std::collections::hash_map::*; pub struct Blobs { map: HashMap, u32>, @@ -19,7 +18,7 @@ impl Blobs { } match self.map.entry(value.to_vec()) { - Entry::Vacant(entry) => { + std::collections::hash_map::Entry::Vacant(entry) => { let offset = *entry.insert(self.stream.len() as u32); let len = value.len(); match len { @@ -38,7 +37,7 @@ impl Blobs { self.stream.extend_from_slice(value); offset } - Entry::Occupied(entry) => *entry.get(), + std::collections::hash_map::Entry::Occupied(entry) => *entry.get(), } } diff --git a/crates/libs/bindgen/src/winmd/writer/file.rs b/crates/libs/bindgen/src/winmd/writer/file.rs index 204358d94d..fab0d3ddc0 100644 --- a/crates/libs/bindgen/src/winmd/writer/file.rs +++ b/crates/libs/bindgen/src/winmd/writer/file.rs @@ -1,6 +1,4 @@ use super::*; -use metadata::*; -use std::mem::*; pub fn write(mut tables: Vec, mut strings: Vec, mut blobs: Vec) -> Vec { if [tables.len(), strings.len(), blobs.len()].iter().any(|len| *len > u32::MAX as usize) { @@ -11,19 +9,19 @@ pub fn write(mut tables: Vec, mut strings: Vec, mut blobs: Vec) -> V let mut guids = vec![0; 16]; // zero guid let size_of_streams = tables.len() + guids.len() + strings.len() + blobs.len(); - let mut dos: IMAGE_DOS_HEADER = zeroed(); - dos.e_magic = IMAGE_DOS_SIGNATURE; + let mut dos: metadata::IMAGE_DOS_HEADER = std::mem::zeroed(); + dos.e_magic = metadata::IMAGE_DOS_SIGNATURE; dos.e_lfarlc = 64; - dos.e_lfanew = size_of::() as i32; + dos.e_lfanew = std::mem::size_of::() as i32; - let mut file: IMAGE_FILE_HEADER = zeroed(); - file.Machine = IMAGE_FILE_MACHINE_I386; + let mut file: metadata::IMAGE_FILE_HEADER = std::mem::zeroed(); + file.Machine = metadata::IMAGE_FILE_MACHINE_I386; file.NumberOfSections = 1; - file.SizeOfOptionalHeader = size_of::() as u16; - file.Characteristics = IMAGE_FILE_DLL | IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_EXECUTABLE_IMAGE; + file.SizeOfOptionalHeader = std::mem::size_of::() as u16; + file.Characteristics = metadata::IMAGE_FILE_DLL | metadata::IMAGE_FILE_32BIT_MACHINE | metadata::IMAGE_FILE_EXECUTABLE_IMAGE; - let mut optional: IMAGE_OPTIONAL_HEADER32 = zeroed(); - optional.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC; + let mut optional: metadata::IMAGE_OPTIONAL_HEADER32 = std::mem::zeroed(); + optional.Magic = metadata::IMAGE_NT_OPTIONAL_HDR32_MAGIC; optional.MajorLinkerVersion = 11; optional.SizeOfInitializedData = 1024; optional.ImageBase = 0x400000; @@ -34,26 +32,26 @@ pub fn write(mut tables: Vec, mut strings: Vec, mut blobs: Vec) -> V optional.MajorSubsystemVersion = 6; optional.MinorSubsystemVersion = 2; optional.SizeOfHeaders = 512; - optional.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; - optional.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT | IMAGE_DLLCHARACTERISTICS_NO_SEH | IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE; + optional.Subsystem = metadata::IMAGE_SUBSYSTEM_WINDOWS_CUI; + optional.DllCharacteristics = metadata::IMAGE_DLLCHARACTERISTICS_NX_COMPAT | metadata::IMAGE_DLLCHARACTERISTICS_NO_SEH | metadata::IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE; optional.SizeOfStackReserve = 0x100000; optional.SizeOfHeapReserve = 4096; optional.LoaderFlags = 0x100000; optional.NumberOfRvaAndSizes = 16; - let mut section: IMAGE_SECTION_HEADER = zeroed(); + let mut section: metadata::IMAGE_SECTION_HEADER = std::mem::zeroed(); section.Name = *b".text\0\0\0"; section.Characteristics = 0x4000_0020; section.VirtualAddress = SECTION_ALIGNMENT; - let mut clr: IMAGE_COR20_HEADER = zeroed(); - clr.cb = size_of::() as u32; + let mut clr: metadata::IMAGE_COR20_HEADER = std::mem::zeroed(); + clr.cb = std::mem::size_of::() as u32; clr.MajorRuntimeVersion = 2; clr.MinorRuntimeVersion = 5; clr.Flags = 1; - let metadata = METADATA_HEADER { - signature: METADATA_SIGNATURE, + let metadata = metadata::METADATA_HEADER { + signature: metadata::METADATA_SIGNATURE, major_version: 1, minor_version: 1, length: 20, @@ -67,22 +65,22 @@ pub fn write(mut tables: Vec, mut strings: Vec, mut blobs: Vec) -> V type GuidsHeader = StreamHeader<8>; type BlobsHeader = StreamHeader<8>; - let size_of_stream_headers = size_of::() + size_of::() + size_of::() + size_of::(); - let size_of_image = optional.FileAlignment as usize + size_of::() + size_of::() + size_of_stream_headers + size_of_streams; + let size_of_stream_headers = std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::(); + let size_of_image = optional.FileAlignment as usize + std::mem::size_of::() + std::mem::size_of::() + size_of_stream_headers + size_of_streams; optional.SizeOfImage = round(size_of_image, optional.SectionAlignment as usize) as u32; section.Misc.VirtualSize = size_of_image as u32 - optional.FileAlignment; section.SizeOfRawData = round(section.Misc.VirtualSize as usize, optional.FileAlignment as usize) as u32; - optional.DataDirectory[14] = IMAGE_DATA_DIRECTORY { VirtualAddress: SECTION_ALIGNMENT, Size: size_of::() as u32 }; + optional.DataDirectory[14] = metadata::IMAGE_DATA_DIRECTORY { VirtualAddress: SECTION_ALIGNMENT, Size: std::mem::size_of::() as u32 }; section.PointerToRawData = optional.FileAlignment; - clr.MetaData.VirtualAddress = SECTION_ALIGNMENT + size_of::() as u32; - clr.MetaData.Size = section.Misc.VirtualSize - size_of::() as u32; + clr.MetaData.VirtualAddress = SECTION_ALIGNMENT + std::mem::size_of::() as u32; + clr.MetaData.Size = section.Misc.VirtualSize - std::mem::size_of::() as u32; let mut buffer = Vec::::new(); buffer.write_header(&dos); - buffer.write_u32(IMAGE_NT_SIGNATURE); + buffer.write_u32(metadata::IMAGE_NT_SIGNATURE); buffer.write_header(&file); buffer.write_header(&optional); buffer.write_header(§ion); diff --git a/crates/libs/bindgen/src/winmd/writer/tables.rs b/crates/libs/bindgen/src/winmd/writer/tables.rs index a18aceae86..df31abd41c 100644 --- a/crates/libs/bindgen/src/winmd/writer/tables.rs +++ b/crates/libs/bindgen/src/winmd/writer/tables.rs @@ -2,7 +2,6 @@ use super::Write; use super::*; -use metadata::*; #[derive(Default)] pub struct Tables { @@ -183,13 +182,13 @@ impl Tables { panic!("metadata table too large"); } - let resolution_scope = coded_index_size(&[self.Module.len(), self.ModuleRef.len(), self.AssemblyRef.len(), self.TypeRef.len()]); + let resolution_scope = metadata::coded_index_size(&[self.Module.len(), self.ModuleRef.len(), self.AssemblyRef.len(), self.TypeRef.len()]); - let type_def_or_ref = coded_index_size(&[self.TypeDef.len(), self.TypeRef.len(), self.TypeSpec.len()]); + let type_def_or_ref = metadata::coded_index_size(&[self.TypeDef.len(), self.TypeRef.len(), self.TypeSpec.len()]); - let has_constant = coded_index_size(&[self.Field.len(), self.Param.len(), self.Property.len()]); + let has_constant = metadata::coded_index_size(&[self.Field.len(), self.Param.len(), self.Property.len()]); - let type_or_method_def = coded_index_size(&[self.TypeDef.len(), self.MethodDef.len()]); + let type_or_method_def = metadata::coded_index_size(&[self.TypeDef.len(), self.MethodDef.len()]); let valid_tables: u64 = 1 << 0 | // Module 1 << 0x01 | // TypeRef diff --git a/crates/libs/core/Cargo.toml b/crates/libs/core/Cargo.toml index 76844d0374..5bf48cc52f 100644 --- a/crates/libs/core/Cargo.toml +++ b/crates/libs/core/Cargo.toml @@ -10,6 +10,9 @@ repository = "https://github.com/microsoft/windows-rs" readme = "readme.md" categories = ["os::windows-apis"] +[lints] +workspace = true + [package.metadata.docs.rs] default-target = "x86_64-pc-windows-msvc" targets = [] diff --git a/crates/libs/core/src/error.rs b/crates/libs/core/src/error.rs index 995c93e0df..c5a0111810 100644 --- a/crates/libs/core/src/error.rs +++ b/crates/libs/core/src/error.rs @@ -60,7 +60,7 @@ impl Error { } } -impl std::convert::From for HRESULT { +impl From for HRESULT { fn from(error: Error) -> Self { let code = error.code; let info: Option = error.info.and_then(|info| info.cast().ok()); @@ -73,25 +73,25 @@ impl std::convert::From for HRESULT { } } -impl std::convert::From for std::io::Error { +impl From for std::io::Error { fn from(from: Error) -> Self { Self::from_raw_os_error(from.code.0) } } -impl std::convert::From for Error { +impl From for Error { fn from(_: std::string::FromUtf16Error) -> Self { Self { code: HRESULT::from_win32(crate::imp::ERROR_NO_UNICODE_TRANSLATION), info: None } } } -impl std::convert::From for Error { +impl From for Error { fn from(_: std::string::FromUtf8Error) -> Self { Self { code: HRESULT::from_win32(crate::imp::ERROR_NO_UNICODE_TRANSLATION), info: None } } } -impl std::convert::From for Error { +impl From for Error { fn from(_: std::num::TryFromIntError) -> Self { Self { code: HRESULT(crate::imp::E_INVALIDARG), info: None } } @@ -101,13 +101,13 @@ impl std::convert::From for Error { // not know the `Infallible` can never be constructed. This code needs to be here // to satesify the type checker but it will never be run. Once `!` is stabilizied // this can be removed. -impl std::convert::From for Error { +impl From for Error { fn from(_: std::convert::Infallible) -> Self { unreachable!() } } -impl std::convert::From for Error { +impl From for Error { fn from(code: HRESULT) -> Self { let info: Option = GetErrorInfo().and_then(|e| e.cast()).ok(); diff --git a/crates/libs/core/src/guid.rs b/crates/libs/core/src/guid.rs index ddaa5611e8..621b34d316 100644 --- a/crates/libs/core/src/guid.rs +++ b/crates/libs/core/src/guid.rs @@ -71,7 +71,7 @@ impl std::fmt::Debug for GUID { } } -impl std::convert::From<&str> for GUID { +impl From<&str> for GUID { fn from(value: &str) -> Self { assert!(value.len() == 36, "Invalid GUID string"); let mut bytes = value.bytes(); @@ -97,13 +97,13 @@ impl std::convert::From<&str> for GUID { } } -impl std::convert::From for GUID { +impl From for GUID { fn from(value: u128) -> Self { Self::from_u128(value) } } -impl std::convert::From for u128 { +impl From for u128 { fn from(value: GUID) -> Self { value.to_u128() } diff --git a/crates/libs/core/src/hresult.rs b/crates/libs/core/src/hresult.rs index 4ff430f327..8c87b67800 100644 --- a/crates/libs/core/src/hresult.rs +++ b/crates/libs/core/src/hresult.rs @@ -105,7 +105,7 @@ impl TypeKind for HRESULT { type TypeKind = CopyType; } -impl std::convert::From> for HRESULT { +impl From> for HRESULT { fn from(result: Result) -> Self { if let Err(error) = result { return error.into(); diff --git a/crates/libs/core/src/imp/factory_cache.rs b/crates/libs/core/src/imp/factory_cache.rs index b36ab42ab3..1f8d929456 100644 --- a/crates/libs/core/src/imp/factory_cache.rs +++ b/crates/libs/core/src/imp/factory_cache.rs @@ -16,7 +16,7 @@ impl FactoryCache { } } -impl FactoryCache { +impl FactoryCache { pub fn call crate::Result>(&self, callback: F) -> crate::Result { loop { // Attempt to load a previously cached factory pointer. @@ -45,11 +45,11 @@ impl FactoryCache { } // This is safe because `FactoryCache` only holds agile factory pointers, which are safe to cache and share between threads. -unsafe impl std::marker::Sync for FactoryCache {} +unsafe impl Sync for FactoryCache {} /// Attempts to load the factory object for the given WinRT class. /// This can be used to access COM interfaces implemented on a Windows Runtime class factory. -pub fn factory() -> crate::Result { +pub fn factory() -> crate::Result { let mut factory: Option = None; let name = crate::HSTRING::from(C::NAME); diff --git a/crates/libs/core/src/imp/generic_factory.rs b/crates/libs/core/src/imp/generic_factory.rs index 5d3d254ca6..cccff8a0a2 100644 --- a/crates/libs/core/src/imp/generic_factory.rs +++ b/crates/libs/core/src/imp/generic_factory.rs @@ -7,7 +7,7 @@ use crate::ComInterface; pub struct IGenericFactory(crate::IUnknown); impl IGenericFactory { - pub fn ActivateInstance(&self) -> crate::Result { + pub fn ActivateInstance(&self) -> crate::Result { unsafe { let mut result__ = std::mem::zeroed(); (crate::Interface::vtable(self).ActivateInstance)(std::mem::transmute_copy(self), &mut result__ as *mut _ as *mut _).from_abi::(result__)?.cast() @@ -25,6 +25,6 @@ unsafe impl crate::Interface for IGenericFactory { type Vtable = IGenericFactory_Vtbl; } -unsafe impl crate::ComInterface for IGenericFactory { +unsafe impl ComInterface for IGenericFactory { const IID: crate::GUID = crate::GUID::from_u128(0x00000035_0000_0000_c000_000000000046); } diff --git a/crates/libs/core/src/imp/sha1.rs b/crates/libs/core/src/imp/sha1.rs index 55afc8ce23..14ef98fb7e 100644 --- a/crates/libs/core/src/imp/sha1.rs +++ b/crates/libs/core/src/imp/sha1.rs @@ -364,7 +364,7 @@ impl Digest { } impl std::fmt::Display for Digest { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for i in self.data.iter() { write!(f, "{:08x}", i)?; } diff --git a/crates/libs/core/src/inspectable.rs b/crates/libs/core/src/inspectable.rs index f6d1e94389..d9e92753ba 100644 --- a/crates/libs/core/src/inspectable.rs +++ b/crates/libs/core/src/inspectable.rs @@ -94,19 +94,19 @@ impl std::fmt::Debug for IInspectable { macro_rules! primitive_boxed_type { ($(($t:ty, $m:ident)),+) => { - $(impl std::convert::TryFrom<$t> for IInspectable { + $(impl TryFrom<$t> for IInspectable { type Error = Error; fn try_from(value: $t) -> Result { imp::PropertyValue::$m(value) } } - impl std::convert::TryFrom for $t { + impl TryFrom for $t { type Error = Error; fn try_from(value: IInspectable) -> Result { ::cast::>(&value)?.Value() } } - impl std::convert::TryFrom<&IInspectable> for $t { + impl TryFrom<&IInspectable> for $t { type Error = Error; fn try_from(value: &IInspectable) -> Result { ::cast::>(value)?.Value() @@ -126,32 +126,32 @@ primitive_boxed_type! { (f32, CreateSingle), (f64, CreateDouble) } -impl std::convert::TryFrom<&str> for IInspectable { +impl TryFrom<&str> for IInspectable { type Error = Error; fn try_from(value: &str) -> Result { let value: HSTRING = value.into(); imp::PropertyValue::CreateString(&value) } } -impl std::convert::TryFrom for IInspectable { +impl TryFrom for IInspectable { type Error = Error; fn try_from(value: HSTRING) -> Result { imp::PropertyValue::CreateString(&value) } } -impl std::convert::TryFrom<&HSTRING> for IInspectable { +impl TryFrom<&HSTRING> for IInspectable { type Error = Error; fn try_from(value: &HSTRING) -> Result { imp::PropertyValue::CreateString(value) } } -impl std::convert::TryFrom for HSTRING { +impl TryFrom for HSTRING { type Error = Error; fn try_from(value: IInspectable) -> Result { ::cast::>(&value)?.Value() } } -impl std::convert::TryFrom<&IInspectable> for HSTRING { +impl TryFrom<&IInspectable> for HSTRING { type Error = Error; fn try_from(value: &IInspectable) -> Result { ::cast::>(value)?.Value() diff --git a/crates/libs/core/src/strings/bstr.rs b/crates/libs/core/src/strings/bstr.rs index 5003117f92..13a06138f2 100644 --- a/crates/libs/core/src/strings/bstr.rs +++ b/crates/libs/core/src/strings/bstr.rs @@ -64,48 +64,48 @@ impl BSTR { } } -impl std::clone::Clone for BSTR { +impl Clone for BSTR { fn clone(&self) -> Self { Self::from_wide(self.as_wide()).unwrap() } } -impl std::convert::From<&str> for BSTR { +impl From<&str> for BSTR { fn from(value: &str) -> Self { - let value: std::vec::Vec = value.encode_utf16().collect(); + let value: Vec = value.encode_utf16().collect(); Self::from_wide(&value).unwrap() } } -impl std::convert::From for BSTR { - fn from(value: std::string::String) -> Self { +impl From for BSTR { + fn from(value: String) -> Self { value.as_str().into() } } -impl std::convert::From<&std::string::String> for BSTR { - fn from(value: &std::string::String) -> Self { +impl From<&String> for BSTR { + fn from(value: &String) -> Self { value.as_str().into() } } -impl<'a> std::convert::TryFrom<&'a BSTR> for std::string::String { +impl<'a> TryFrom<&'a BSTR> for String { type Error = std::string::FromUtf16Error; fn try_from(value: &BSTR) -> std::result::Result { - std::string::String::from_utf16(value.as_wide()) + String::from_utf16(value.as_wide()) } } -impl std::convert::TryFrom for std::string::String { +impl TryFrom for String { type Error = std::string::FromUtf16Error; fn try_from(value: BSTR) -> std::result::Result { - std::string::String::try_from(&value) + String::try_from(&value) } } -impl std::default::Default for BSTR { +impl Default for BSTR { fn default() -> Self { Self(std::ptr::null_mut()) } @@ -113,7 +113,7 @@ impl std::default::Default for BSTR { impl std::fmt::Display for BSTR { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::write!(f, "{}", crate::Decode(|| std::char::decode_utf16(self.as_wide().iter().cloned()))) + std::write!(f, "{}", Decode(|| std::char::decode_utf16(self.as_wide().iter().cloned()))) } } @@ -123,33 +123,33 @@ impl std::fmt::Debug for BSTR { } } -impl std::cmp::PartialEq for BSTR { +impl PartialEq for BSTR { fn eq(&self, other: &Self) -> bool { self.as_wide() == other.as_wide() } } -impl std::cmp::Eq for BSTR {} +impl Eq for BSTR {} -impl std::cmp::PartialEq for &str { +impl PartialEq for &str { fn eq(&self, other: &BSTR) -> bool { other == self } } -impl std::cmp::PartialEq for String { +impl PartialEq for String { fn eq(&self, other: &BSTR) -> bool { other == self } } -impl + ?Sized> std::cmp::PartialEq for BSTR { +impl + ?Sized> PartialEq for BSTR { fn eq(&self, other: &T) -> bool { self.as_wide().iter().copied().eq(other.as_ref().encode_utf16()) } } -impl std::ops::Drop for BSTR { +impl Drop for BSTR { fn drop(&mut self) { if !self.0.is_null() { unsafe { crate::imp::SysFreeString(self.0) } diff --git a/crates/libs/core/src/strings/hstring.rs b/crates/libs/core/src/strings/hstring.rs index a0a7f59fab..de522928b8 100644 --- a/crates/libs/core/src/strings/hstring.rs +++ b/crates/libs/core/src/strings/hstring.rs @@ -49,8 +49,8 @@ impl HSTRING { } /// Get the contents of this `HSTRING` as a String lossily. - pub fn to_string_lossy(&self) -> std::string::String { - std::string::String::from_utf16_lossy(self.as_wide()) + pub fn to_string_lossy(&self) -> String { + String::from_utf16_lossy(self.as_wide()) } /// Get the contents of this `HSTRING` as a OsString. @@ -149,47 +149,47 @@ impl std::fmt::Debug for HSTRING { } } -impl std::convert::From<&str> for HSTRING { +impl From<&str> for HSTRING { fn from(value: &str) -> Self { unsafe { Self::from_wide_iter(value.encode_utf16(), value.len()).unwrap() } } } -impl std::convert::From for HSTRING { - fn from(value: std::string::String) -> Self { +impl From for HSTRING { + fn from(value: String) -> Self { value.as_str().into() } } -impl std::convert::From<&std::string::String> for HSTRING { - fn from(value: &std::string::String) -> Self { +impl From<&String> for HSTRING { + fn from(value: &String) -> Self { value.as_str().into() } } #[cfg(windows)] -impl std::convert::From<&std::path::Path> for HSTRING { +impl From<&std::path::Path> for HSTRING { fn from(value: &std::path::Path) -> Self { value.as_os_str().into() } } #[cfg(windows)] -impl std::convert::From<&std::ffi::OsStr> for HSTRING { +impl From<&std::ffi::OsStr> for HSTRING { fn from(value: &std::ffi::OsStr) -> Self { unsafe { Self::from_wide_iter(std::os::windows::ffi::OsStrExt::encode_wide(value), value.len()).unwrap() } } } #[cfg(windows)] -impl std::convert::From for HSTRING { +impl From for HSTRING { fn from(value: std::ffi::OsString) -> Self { value.as_os_str().into() } } #[cfg(windows)] -impl std::convert::From<&std::ffi::OsString> for HSTRING { +impl From<&std::ffi::OsString> for HSTRING { fn from(value: &std::ffi::OsString) -> Self { value.as_os_str().into() } @@ -215,20 +215,20 @@ impl PartialEq for HSTRING { } } -impl PartialEq for HSTRING { - fn eq(&self, other: &std::string::String) -> bool { +impl PartialEq for HSTRING { + fn eq(&self, other: &String) -> bool { *self == **other } } -impl PartialEq for &HSTRING { - fn eq(&self, other: &std::string::String) -> bool { +impl PartialEq for &HSTRING { + fn eq(&self, other: &String) -> bool { **self == **other } } -impl PartialEq<&std::string::String> for HSTRING { - fn eq(&self, other: &&std::string::String) -> bool { +impl PartialEq<&String> for HSTRING { + fn eq(&self, other: &&String) -> bool { *self == ***other } } @@ -269,19 +269,19 @@ impl PartialEq<&HSTRING> for str { } } -impl PartialEq for std::string::String { +impl PartialEq for String { fn eq(&self, other: &HSTRING) -> bool { *other == **self } } -impl PartialEq for &std::string::String { +impl PartialEq for &String { fn eq(&self, other: &HSTRING) -> bool { *other == ***self } } -impl PartialEq<&HSTRING> for std::string::String { +impl PartialEq<&HSTRING> for String { fn eq(&self, other: &&HSTRING) -> bool { **other == **self } @@ -371,31 +371,31 @@ impl PartialEq<&HSTRING> for std::ffi::OsString { } } -impl<'a> std::convert::TryFrom<&'a HSTRING> for std::string::String { +impl<'a> TryFrom<&'a HSTRING> for String { type Error = std::string::FromUtf16Error; fn try_from(hstring: &HSTRING) -> std::result::Result { - std::string::String::from_utf16(hstring.as_wide()) + String::from_utf16(hstring.as_wide()) } } -impl std::convert::TryFrom for std::string::String { +impl TryFrom for String { type Error = std::string::FromUtf16Error; fn try_from(hstring: HSTRING) -> std::result::Result { - std::string::String::try_from(&hstring) + String::try_from(&hstring) } } #[cfg(windows)] -impl<'a> std::convert::From<&'a HSTRING> for std::ffi::OsString { +impl<'a> From<&'a HSTRING> for std::ffi::OsString { fn from(hstring: &HSTRING) -> Self { hstring.to_os_string() } } #[cfg(windows)] -impl std::convert::From for std::ffi::OsString { +impl From for std::ffi::OsString { fn from(hstring: HSTRING) -> Self { Self::from(&hstring) } diff --git a/crates/libs/core/src/strings/pcstr.rs b/crates/libs/core/src/strings/pcstr.rs index 161db28785..5535c5ae46 100644 --- a/crates/libs/core/src/strings/pcstr.rs +++ b/crates/libs/core/src/strings/pcstr.rs @@ -32,7 +32,7 @@ impl PCSTR { /// /// The `PCSTR`'s pointer needs to be valid for reads up until and including the next `\0`. pub unsafe fn as_bytes(&self) -> &[u8] { - let len = super::strlen(*self); + let len = strlen(*self); std::slice::from_raw_parts(self.0, len) } diff --git a/crates/libs/core/src/strings/pcwstr.rs b/crates/libs/core/src/strings/pcwstr.rs index 8112d83855..03b8cdd928 100644 --- a/crates/libs/core/src/strings/pcwstr.rs +++ b/crates/libs/core/src/strings/pcwstr.rs @@ -32,7 +32,7 @@ impl PCWSTR { /// /// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`. pub unsafe fn as_wide(&self) -> &[u16] { - let len = super::wcslen(*self); + let len = wcslen(*self); std::slice::from_raw_parts(self.0, len) } diff --git a/crates/libs/core/src/strings/pstr.rs b/crates/libs/core/src/strings/pstr.rs index d395953e0e..6ea9d9c70c 100644 --- a/crates/libs/core/src/strings/pstr.rs +++ b/crates/libs/core/src/strings/pstr.rs @@ -32,7 +32,7 @@ impl PSTR { /// /// The `PSTR`'s pointer needs to be valid for reads up until and including the next `\0`. pub unsafe fn as_bytes(&self) -> &[u8] { - let len = super::strlen(PCSTR::from_raw(self.0)); + let len = strlen(PCSTR::from_raw(self.0)); std::slice::from_raw_parts(self.0, len) } diff --git a/crates/libs/core/src/strings/pwstr.rs b/crates/libs/core/src/strings/pwstr.rs index 7eb21084d0..052bfb9cf6 100644 --- a/crates/libs/core/src/strings/pwstr.rs +++ b/crates/libs/core/src/strings/pwstr.rs @@ -32,7 +32,7 @@ impl PWSTR { /// /// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`. pub unsafe fn as_wide(&self) -> &[u16] { - let len = super::wcslen(PCWSTR::from_raw(self.0)); + let len = wcslen(PCWSTR::from_raw(self.0)); std::slice::from_raw_parts(self.0, len) } diff --git a/crates/libs/interface/src/lib.rs b/crates/libs/interface/src/lib.rs index eb62c7847a..198a431538 100644 --- a/crates/libs/interface/src/lib.rs +++ b/crates/libs/interface/src/lib.rs @@ -1,5 +1,4 @@ use quote::quote; -use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; /// Defines a COM interface to call or implement. @@ -373,8 +372,8 @@ impl Interface { } } -impl Parse for Interface { - fn parse(input: ParseStream<'_>) -> syn::Result { +impl syn::parse::Parse for Interface { + fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result { let attributes = input.call(syn::Attribute::parse_outer)?; let mut docs = Vec::new(); for attr in attributes.into_iter() { @@ -474,8 +473,8 @@ impl Guid { } } -impl Parse for Guid { - fn parse(cursor: ParseStream<'_>) -> syn::Result { +impl syn::parse::Parse for Guid { + fn parse(cursor: syn::parse::ParseStream<'_>) -> syn::Result { let string: Option = cursor.parse().ok(); Ok(Self(string)) diff --git a/crates/libs/metadata/src/file.rs b/crates/libs/metadata/src/file.rs index e8867c1c98..31d46c3121 100644 --- a/crates/libs/metadata/src/file.rs +++ b/crates/libs/metadata/src/file.rs @@ -30,13 +30,13 @@ impl PartialEq for File { impl Eq for File {} impl Ord for File { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> Ordering { self.bytes.as_ptr().cmp(&other.bytes.as_ptr()) } } impl PartialOrd for File { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } diff --git a/crates/libs/windows/src/Windows/Foundation/Collections/impl.rs b/crates/libs/windows/src/Windows/Foundation/Collections/impl.rs index a991bd562e..e0672c4fbb 100644 --- a/crates/libs/windows/src/Windows/Foundation/Collections/impl.rs +++ b/crates/libs/windows/src/Windows/Foundation/Collections/impl.rs @@ -712,15 +712,15 @@ impl IVectorView_Vtbl { struct StockIterable where T: ::windows_core::RuntimeType + 'static, - >::Default: ::std::clone::Clone, + >::Default: Clone, { - values: std::vec::Vec, + values: Vec, } impl IIterable_Impl for StockIterable where T: ::windows_core::RuntimeType, - >::Default: ::std::clone::Clone, + >::Default: Clone, { fn First(&self) -> ::windows_core::Result> { unsafe { @@ -735,7 +735,7 @@ where struct StockIterator where T: ::windows_core::RuntimeType + 'static, - >::Default: ::std::clone::Clone, + >::Default: Clone, { owner: IIterable, current: ::std::sync::atomic::AtomicUsize, @@ -744,7 +744,7 @@ where impl IIterator_Impl for StockIterator where T: ::windows_core::RuntimeType, - >::Default: ::std::clone::Clone, + >::Default: Clone, { fn Current(&self) -> ::windows_core::Result { let owner: &StockIterable = unsafe { ::windows_core::AsImpl::as_impl(&self.owner) }; @@ -787,13 +787,13 @@ where } } -impl ::core::convert::TryFrom<::std::vec::Vec> for IIterable +impl ::core::convert::TryFrom> for IIterable where T: ::windows_core::RuntimeType, - >::Default: ::std::clone::Clone, + >::Default: Clone, { type Error = ::windows_core::Error; - fn try_from(values: ::std::vec::Vec) -> ::windows_core::Result { + fn try_from(values: Vec) -> ::windows_core::Result { // TODO: should provide a fallible try_into or more explicit allocator Ok(StockIterable { values }.into()) } @@ -803,8 +803,8 @@ struct StockMapView where K: ::windows_core::RuntimeType + 'static, V: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { map: std::collections::BTreeMap, } @@ -813,8 +813,8 @@ impl IIterable_Impl> for StockMapView where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { fn First(&self) -> ::windows_core::Result>> { unsafe { @@ -829,8 +829,8 @@ impl IMapView_Impl for StockMapView where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { fn Lookup(&self, key: &K::Default) -> ::windows_core::Result { let value = self.map.get(key).ok_or_else(|| ::windows_core::Error::from(::windows_core::imp::E_BOUNDS))?; @@ -842,7 +842,7 @@ where fn HasKey(&self, key: &K::Default) -> ::windows_core::Result { Ok(self.map.contains_key(key)) } - fn Split(&self, first: &mut std::option::Option>, second: &mut std::option::Option>) -> ::windows_core::Result<()> { + fn Split(&self, first: &mut Option>, second: &mut Option>) -> ::windows_core::Result<()> { *first = None; *second = None; Ok(()) @@ -854,8 +854,8 @@ struct StockMapViewIterator<'a, K, V> where K: ::windows_core::RuntimeType + 'static, V: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { _owner: IIterable>, current: ::std::sync::RwLock>, @@ -865,8 +865,8 @@ impl<'a, K, V> IIterator_Impl> for StockMapViewIterator<'a, where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { fn Current(&self) -> ::windows_core::Result> { let mut current = self.current.read().unwrap().clone().peekable(); @@ -913,8 +913,8 @@ struct StockKeyValuePair where K: ::windows_core::RuntimeType + 'static, V: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone, - >::Default: std::clone::Clone, + >::Default: Clone, + >::Default: Clone, { key: K::Default, value: V::Default, @@ -924,8 +924,8 @@ impl IKeyValuePair_Impl for StockKeyValuePair where K: ::windows_core::RuntimeType, V: ::windows_core::RuntimeType, - >::Default: std::clone::Clone, - >::Default: std::clone::Clone, + >::Default: Clone, + >::Default: Clone, { fn Key(&self) -> ::windows_core::Result { K::from_default(&self.key) @@ -939,8 +939,8 @@ impl ::core::convert::TryFrom>::Default: std::clone::Clone + std::cmp::Ord, - >::Default: std::clone::Clone, + >::Default: Clone + Ord, + >::Default: Clone, { type Error = ::windows_core::Error; fn try_from(map: std::collections::BTreeMap) -> ::windows_core::Result { @@ -952,15 +952,15 @@ where struct StockVectorView where T: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { - values: std::vec::Vec, + values: Vec, } impl IIterable_Impl for StockVectorView where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { fn First(&self) -> ::windows_core::Result> { unsafe { @@ -974,7 +974,7 @@ where impl IVectorView_Impl for StockVectorView where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { fn GetAt(&self, index: u32) -> ::windows_core::Result { let item = self.values.get(index as usize).ok_or_else(|| ::windows_core::Error::from(::windows_core::imp::E_BOUNDS))?; @@ -1008,7 +1008,7 @@ where struct StockVectorViewIterator where T: ::windows_core::RuntimeType + 'static, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { owner: IIterable, current: ::std::sync::atomic::AtomicUsize, @@ -1017,7 +1017,7 @@ where impl IIterator_Impl for StockVectorViewIterator where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { fn Current(&self) -> ::windows_core::Result { let owner: &StockVectorView = unsafe { ::windows_core::AsImpl::as_impl(&self.owner) }; @@ -1060,13 +1060,13 @@ where } } -impl ::core::convert::TryFrom<::std::vec::Vec> for IVectorView +impl ::core::convert::TryFrom> for IVectorView where T: ::windows_core::RuntimeType, - >::Default: std::clone::Clone + std::cmp::PartialEq, + >::Default: Clone + PartialEq, { type Error = ::windows_core::Error; - fn try_from(values: ::std::vec::Vec) -> ::windows_core::Result { + fn try_from(values: Vec) -> ::windows_core::Result { // TODO: should provide a fallible try_into or more explicit allocator Ok(StockVectorView { values }.into()) }