Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support aggregate constant initialization #2371

Merged
merged 2 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions crates/libs/bindgen/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ pub fn gen(gen: &Gen, def: Field) -> TokenStream {
#doc
pub const #name: #guid = #value;
}
} else if let Some(value) = initializer(gen, def) {
let kind = gen.type_default_name(&ty);

quote! {
#doc
#features
pub const #name: #kind = #kind { #value };
}
// TODO: remove this branch once https://github.com/microsoft/win32metadata/issues/1483 arrives
} else if let Some((guid, id)) = get_property_key(gen, def) {
let kind = gen.type_default_name(&ty);
let guid = gen.guid(&guid);
Expand All @@ -86,6 +95,110 @@ pub fn gen(gen: &Gen, def: Field) -> TokenStream {
}
}

fn initializer(gen: &Gen, def: Field) -> Option<TokenStream> {
let Some(value) = constant(gen, def) else {
return None;
};

let mut input = value.as_str();

let Type::TypeDef((def, _)) = gen.reader.field_type(def, None) else {
unimplemented!();
};

let mut result = quote! {};

for field in gen.reader.type_def_fields(def) {
let (value, rest) = field_initializer(gen, field, input);
input = rest;
result.combine(&value);
}

Some(result)
}

fn field_initializer<'a>(gen: &Gen, field: Field, input: &'a str) -> (TokenStream, &'a str) {
let name = to_ident(gen.reader.field_name(field));

match gen.reader.field_type(field, None) {
Type::GUID => {
let (literals, rest) = read_literal_array(input, 11);
let value = gen.guid(&GUID::from_string_args(&literals));
(quote! { #name: #value, }, rest)
}
Type::Win32Array((_, len)) => {
let (literals, rest) = read_literal_array(input, len);
let literals = literals.iter().map(|literal| TokenStream::from(*literal));
(quote! { #name: [#(#literals,)*], }, rest)
}
_ => {
let (literal, rest) = read_literal(input);
let literal: TokenStream = literal.into();
(quote! { #name: #literal, }, rest)
}
}
}

fn constant(gen: &Gen, def: Field) -> Option<String> {
gen.reader
.field_attributes(def)
.find(|attribute| gen.reader.attribute_name(*attribute) == "ConstantAttribute")
.map(|attribute| {
let args = gen.reader.attribute_args(attribute);
match &args[0].1 {
Value::String(value) => value.clone(),
_ => unimplemented!(),
}
})
}

fn read_literal(input: &str) -> (&str, &str) {
let mut start = None;
let mut end = 0;

for (pos, c) in input.bytes().enumerate() {
if start.is_none() {
if c != b' ' && c != b',' {
start = Some(pos);
}
} else if c == b' ' || c == b',' || c == b'}' {
break;
}
end += 1;
}

let Some(start) = start else {
unimplemented!();
};

(&input[start..end], &input[end..])
}

fn read_token(input: &str, token: u8) -> &str {
for (pos, c) in input.bytes().enumerate() {
if c == token {
return &input[pos + 1..];
} else if c != b' ' && c != b',' {
break;
}
}

panic!("`{}` expected", token.escape_ascii());
}

fn read_literal_array(input: &str, len: usize) -> (Vec<&str>, &str) {
let mut input = read_token(input, b'{');
let mut result = vec![];

for _ in 0..len {
let (literal, rest) = read_literal(input);
result.push(literal);
input = rest;
}

(result, read_token(input, b'}'))
}

fn get_property_key(gen: &Gen, def: Field) -> Option<(GUID, u32)> {
gen.reader
.field_attributes(def)
Expand Down
4 changes: 4 additions & 0 deletions crates/libs/metadata/src/reader/guid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ impl GUID {
}
Self(unwrap_u32(&args[0].1), unwrap_u16(&args[1].1), unwrap_u16(&args[2].1), unwrap_u8(&args[3].1), unwrap_u8(&args[4].1), unwrap_u8(&args[5].1), unwrap_u8(&args[6].1), unwrap_u8(&args[7].1), unwrap_u8(&args[8].1), unwrap_u8(&args[9].1), unwrap_u8(&args[10].1))
}

pub fn from_string_args(args: &[&str]) -> Self {
Self(args[0].parse().unwrap(), args[1].parse().unwrap(), args[2].parse().unwrap(), args[3].parse().unwrap(), args[4].parse().unwrap(), args[5].parse().unwrap(), args[6].parse().unwrap(), args[7].parse().unwrap(), args[8].parse().unwrap(), args[9].parse().unwrap(), args[10].parse().unwrap())
}
}

impl std::fmt::Debug for GUID {
Expand Down
2 changes: 2 additions & 0 deletions crates/libs/sys/src/Windows/Win32/Security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ pub const CVT_SECONDS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Security\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub const SECURITY_DYNAMIC_TRACKING: super::Foundation::BOOLEAN = 1u8;
#[doc = "*Required features: `\"Win32_Security\"`*"]
pub const SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = SID_IDENTIFIER_AUTHORITY { Value: [0, 0, 0, 0, 0, 5] };
#[doc = "*Required features: `\"Win32_Security\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub const SECURITY_STATIC_TRACKING: super::Foundation::BOOLEAN = 0u8;
Expand Down
2 changes: 2 additions & 0 deletions crates/libs/windows/src/Windows/Win32/Security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,8 @@ pub const CVT_SECONDS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Security\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub const SECURITY_DYNAMIC_TRACKING: super::Foundation::BOOLEAN = super::Foundation::BOOLEAN(1u8);
#[doc = "*Required features: `\"Win32_Security\"`*"]
pub const SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = SID_IDENTIFIER_AUTHORITY { Value: [0, 0, 0, 0, 0, 5] };
#[doc = "*Required features: `\"Win32_Security\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub const SECURITY_STATIC_TRACKING: super::Foundation::BOOLEAN = super::Foundation::BOOLEAN(0u8);
Expand Down
1 change: 1 addition & 0 deletions crates/tools/lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub fn format(namespace: &str, tokens: &mut String) {
if output.status.success() {
*tokens = String::from_utf8(output.stdout).expect("Failed to parse UTF-8");
} else {
// TODO: This doesn't print anything useful
println!("rustfmt failed for `{namespace}` with status {}\nError:\n{}", output.status, String::from_utf8_lossy(&output.stderr));
}
}
Expand Down