//! Vulkan's registry (vk.xml) and Venus's two additions, read into types, //! commands and values, and narrowed to what Venus serializes — by //! venus-protocol's rules (vkxml.py, vn_protocol.py), so the numbers and //! bytes come out the same. use super::extensions::EXTENSIONS; use super::xml::Element; use std::collections::{BTreeMap, BTreeSet}; /// A member of a struct, or a command's parameter or result. #[derive(Clone, Debug)] pub struct Var { pub name: String, /// The base type's name, aliases resolved. pub ty: String, /// How many `*`, and for each level whether it points at const. pub pointers: Vec, /// Fixed array dimensions: a number or a constant's name. pub dims: Vec, /// `len`, split at its commas (an `altlen` replaces it). pub len: Vec, pub optional: Vec, /// A union's selector member (on the union member of a struct). pub selector: Option, /// The values of the selector that pick this union member. pub selection: Vec, /// An sType member's one value. pub values: Option, /// A `stride` parameter (vkCmdDrawMulti*). pub stride: Option, /// A C bitfield's width (`uint32_t mask:8`). pub bits: Option, } #[derive(Clone, Debug)] pub enum Dim { Number(u64), Constant(String), } impl Var { pub fn is_pointer(&self) -> bool { !self.pointers.is_empty() } /// A pointer whose first level points at const. /// What the pointer points at is const (`const T*`, `const T* const*`): /// its outermost level, which levels count from the type outwards. pub fn is_const_pointer(&self) -> bool { self.pointers.last().copied().unwrap_or(false) } pub fn null_terminated(&self) -> bool { self.len.iter().any(|l| l == "null-terminated") } /// Optional at its outermost level, and a pointer: may be null. pub fn maybe_null(&self) -> bool { self.is_pointer() && self.optional.first().copied().unwrap_or(false) } } // Commands are few and few at a time: their size is no matter. #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug)] pub enum Kind { /// A C scalar of this many bytes (float, double and the fixed ints). Primitive, Char, SizeT, Void, /// typedef of a primitive (VkBool32, VkDeviceSize, VkFlags, ...). Basetype(String), /// VkFlags or VkFlags64; the enum of its bits. Bitmask { typedef: String, }, /// Every handle is an id on the wire, dispatchable or not. Handle, Enum { wide: bool, }, Struct { members: Vec, union: bool, extends: Vec, }, Command { ret: Option, params: Vec, }, /// Function pointers, platform types, defines: never serialized. Other, } #[derive(Clone, Debug)] pub struct Type { pub kind: Kind, } #[derive(Default)] pub struct Registry { pub types: BTreeMap, /// Alias → the name it stands for (types and commands). pub aliases: BTreeMap, /// Every enum's values: enum name → (value name, value), in order. pub enums: BTreeMap>, /// Value name → value, every enum's and the API constants'. pub values: BTreeMap, /// The command types (VkCommandTypeEXT): command name → number. pub command_types: BTreeMap, /// What features and the listed extensions require. required: BTreeSet, } /// Whether an element belongs to Vulkan (not only to Vulkan SC). fn for_vulkan(e: &Element) -> bool { e.attr("api") != Some("vulkansc") } impl Registry { pub fn resolve<'a>(&'a self, name: &'a str) -> &'a str { let mut name = name; while let Some(to) = self.aliases.get(name) { name = to; } name } /// Reads one registry file into this one. pub fn read(&mut self, root: &Element) -> Result<(), String> { for section in root.elements().filter(|e| for_vulkan(e)) { match section.name.as_str() { "types" => { for ty in section.all("type").filter(|e| for_vulkan(e)) { self.read_type(ty)?; } } "enums" => self.read_enums(section), "commands" => { for command in section.all("command").filter(|e| for_vulkan(e)) { self.read_command(command)?; } } "feature" => { for require in section.all("require").filter(|e| for_vulkan(e)) { self.read_require(require, None, true); } } "extensions" => { for ext in section.all("extension").filter(|e| for_vulkan(e)) { self.read_extension(ext); } } _ => {} } } Ok(()) } fn read_type(&mut self, e: &Element) -> Result<(), String> { let category = e.attr("category").unwrap_or(""); let name = match e.attr("name") { Some(n) => n.to_string(), None => e.first("name").map(|n| n.text()).unwrap_or_default(), }; if name.is_empty() { return Ok(()); } if let Some(alias) = e.attr("alias") { self.aliases.insert(name, alias.to_string()); return Ok(()); } let kind = match category { "basetype" => match e.first("type") { Some(t) => Kind::Basetype(t.text()), None => Kind::Other, }, "bitmask" => Kind::Bitmask { typedef: e.first("type").map(|t| t.text()).unwrap_or_default(), }, "handle" => Kind::Handle, "enum" => Kind::Enum { wide: false }, "struct" | "union" => { let members = e .all("member") .filter(|m| for_vulkan(m)) .map(read_var) .collect::, _>>()?; Kind::Struct { members: sort_members(members), union: category == "union", extends: e .attr("structextends") .map(|s| s.split(',').map(str::to_string).collect()) .unwrap_or_default(), } } "" => match name.as_str() { "float" | "double" | "uint8_t" | "uint16_t" | "uint32_t" | "uint64_t" | "int32_t" | "int64_t" => Kind::Primitive, "char" => Kind::Char, "size_t" => Kind::SizeT, "void" => Kind::Void, _ => Kind::Other, }, _ => Kind::Other, }; self.types.insert(name, Type { kind }); Ok(()) } fn read_enums(&mut self, e: &Element) { let Some(name) = e.attr("name") else { return }; let wide = e.attr("bitwidth") == Some("64"); if let Some(Type { kind: Kind::Enum { wide: w }, .. }) = self.types.get_mut(name) { *w = wide; } for value in e.all("enum").filter(|v| for_vulkan(v)) { self.read_value(value, Some(name), None); } } /// One ``: of `owner` (an `` block) or extending one, in /// extension `extnumber` when it has an offset. fn read_value(&mut self, e: &Element, owner: Option<&str>, extnumber: Option) { let Some(name) = e.attr("name") else { return }; let enum_name = e.attr("extends").or(owner); let value = if let Some(alias) = e.attr("alias") { match self.values.get(alias) { Some(&v) => v, None => return, } } else if let Some(v) = e.attr("value") { match parse_value(v) { Some(v) => v, None => return, } } else if let Some(bit) = e.attr("bitpos") { match bit.parse::() { Ok(bit) => 1i64 << bit, Err(_) => return, } } else if let Some(offset) = e.attr("offset") { let number = e .attr("extnumber") .and_then(|n| n.parse().ok()) .or(extnumber) .unwrap_or(0); let v = 1_000_000_000 + (number - 1) * 1000 + offset.parse::().unwrap_or(0); if e.attr("dir") == Some("-") { -v } else { v } } else { return; }; if self.values.insert(name.to_string(), value).is_none() && let Some(enum_name) = enum_name { self.enums .entry(enum_name.to_string()) .or_default() .push((name.to_string(), value)); } } fn read_command(&mut self, e: &Element) -> Result<(), String> { if let Some(alias) = e.attr("alias") { if let Some(name) = e.attr("name") { self.aliases.insert(name.to_string(), alias.to_string()); } return Ok(()); } let proto = e.first("proto").ok_or("a command without a proto")?; let ret = read_var(proto)?; let params = e .all("param") .filter(|p| for_vulkan(p)) .map(read_var) .collect::, _>>()?; let name = ret.name.clone(); let ret = (ret.ty != "void" || ret.is_pointer()).then_some(ret); self.types.insert( name, Type { kind: Kind::Command { ret, params }, }, ); Ok(()) } fn read_extension(&mut self, e: &Element) { let number = e.attr("number").and_then(|n| n.parse().ok()); let name = e.attr("name").unwrap_or(""); let listed = EXTENSIONS.contains(&name) && e.attr("supported") .is_some_and(|s| s.split(',').any(|s| s == "vulkan")); for require in e.all("require").filter(|r| for_vulkan(r)) { let wanted = listed && require.attr("depends").is_none_or(supported_depends); self.read_require(require, number, wanted); } } /// A ``: its values always (they number what others use), its /// types and commands when `wanted`. fn read_require(&mut self, e: &Element, extnumber: Option, wanted: bool) { for item in e.elements().filter(|i| for_vulkan(i)) { match item.name.as_str() { "enum" => { if item.attr("extends").is_some() || item.attr("value").is_some() { self.read_value(item, None, extnumber); } } "type" | "command" if wanted => { if let Some(name) = item.attr("name") { self.required.insert(name.to_string()); } } _ => {} } } } /// Venus's command numbers: VkCommandTypeEXT's values, by command. pub fn number_commands(&mut self) { let values = self.enums.get("VkCommandTypeEXT").cloned().unwrap_or_default(); for (name, value) in values { if let Some(command) = name .strip_prefix("VK_COMMAND_TYPE_") .and_then(|n| n.strip_suffix("_EXT")) { self.command_types.insert(command.to_string(), value as u32); } } } /// What Venus serializes: what is required, with everything it needs, /// that can be serialized — types by name, commands among them. pub fn selected(&self) -> BTreeSet { const TYPE_BLOCK_LIST: &[&str] = &[ "VkPhysicalDeviceLayeredApiPropertiesKHR", "VkPhysicalDeviceLayeredApiPropertiesListKHR", "VkPhysicalDeviceLayeredApiVulkanPropertiesKHR", "VkPhysicalDeviceLayeredApiKHR", ]; const COMMAND_BLOCK_LIST: &[&str] = &[ "vkBuildAccelerationStructuresKHR", "vkCopyAccelerationStructureToMemoryKHR", "vkCopyMemoryToAccelerationStructureKHR", "vkWriteSamplerDescriptorsEXT", "vkWriteResourceDescriptorsEXT", ]; let mut seen = BTreeSet::new(); let mut todo: Vec = self .required .iter() .map(|n| self.resolve(n).to_string()) .filter(|n| !TYPE_BLOCK_LIST.contains(&n.as_str())) .filter(|n| !COMMAND_BLOCK_LIST.contains(&n.as_str())) .collect(); while let Some(name) = todo.pop() { if !seen.insert(name.clone()) { continue; } let Some(ty) = self.types.get(&name) else { continue }; let mut deps = Vec::new(); match &ty.kind { Kind::Basetype(t) => deps.push(t.clone()), Kind::Bitmask { typedef } => deps.push(typedef.clone()), Kind::Struct { members, .. } => deps.extend(members.iter().map(|m| m.ty.clone())), Kind::Command { ret, params } => { deps.extend(params.iter().map(|p| p.ty.clone())); deps.extend(ret.iter().map(|r| r.ty.clone())); } _ => {} } for dep in deps { let dep = self.resolve(&dep).to_string(); if !seen.contains(&dep) && !TYPE_BLOCK_LIST.contains(&dep.as_str()) { todo.push(dep); } } } let mut serializable = BTreeMap::new(); seen.into_iter() .filter(|n| self.serializable(n, &mut serializable)) .collect() } /// Whether a type can be put on Venus's wire (memoized in `memo`). pub fn serializable(&self, name: &str, memo: &mut BTreeMap) -> bool { const UNION_DEFAULT_TAGS: &[&str] = &[ "VkClearColorValue", "VkClearValue", "VkDeviceOrHostAddressKHR", "VkDeviceOrHostAddressConstKHR", "VkPipelineExecutableStatisticValueKHR", ]; let name = self.resolve(name); if let Some(&known) = memo.get(name) { return known; } // Assume yes while looking (structs that point at themselves). memo.insert(name.to_string(), true); let Some(ty) = self.types.get(name) else { memo.insert(name.to_string(), false); return false; }; let var_ok = |var: &Var, memo: &mut BTreeMap| -> bool { // pNext, and a pointer that may be null, never keep a type off the // wire: null is always sendable. if var.name == "pNext" || var.maybe_null() { return true; } let base = self.resolve(&var.ty); // A void pointer with a len is a blob. if base == "void" { return var.is_pointer() && !var.len.is_empty(); } self.serializable(base, memo) || var.maybe_null() }; let ok = match &ty.kind { Kind::Primitive | Kind::Char | Kind::SizeT => true, Kind::Void | Kind::Other => false, Kind::Basetype(t) => !t.is_empty(), Kind::Bitmask { .. } | Kind::Handle | Kind::Enum { .. } => true, Kind::Struct { members, union, .. } => { if name == "VkBaseInStructure" || name == "VkBaseOutStructure" { false } else if *union && UNION_DEFAULT_TAGS.contains(&name) { // Sent as one member, chosen once and for all. true } else if *union && !UNION_DEFAULT_TAGS.contains(&name) && members.iter().any(|m| m.selection.is_empty()) { false } else { members.clone().iter().all(|m| var_ok(m, memo)) } } Kind::Command { ret, params } => { ret.as_ref() .is_none_or(|r| r.is_pointer() || self.serializable(&r.ty, memo)) && params.clone().iter().all(|p| var_ok(p, memo)) } }; memo.insert(name.to_string(), ok); ok } } /// A `depends` expression of a ``: true when what it needs (Vulkan /// versions aside) is among the listed extensions. `,` is or, `+` is and. fn supported_depends(depends: &str) -> bool { fn eval(expr: &str) -> Option { let expr = expr.trim(); let expr = strip_parens(expr); for (sep, any) in [(',', true), ('+', false)] { let parts = top_level_split(expr, sep); if parts.len() > 1 { let values: Vec = parts.iter().filter_map(|p| eval(p)).collect(); if values.is_empty() { return None; } return Some(if any { values.iter().any(|&v| v) } else { values.iter().all(|&v| v) }); } } // A version, or something not an extension: no condition. if expr.starts_with("VK_VERSION_") || !expr.starts_with("VK_") { return None; } Some(EXTENSIONS.contains(&expr)) } eval(depends).unwrap_or(true) } /// Without parentheses that enclose the whole expression. fn strip_parens(expr: &str) -> &str { let mut expr = expr.trim(); while expr.starts_with('(') { // Where the first `(` closes: the whole expression, or less. let mut depth = 0; let close = expr.char_indices().find_map(|(i, c)| { match c { '(' => depth += 1, ')' => depth -= 1, _ => {} } (depth == 0).then_some(i) }); if close != Some(expr.len() - 1) { break; } expr = expr[1..expr.len() - 1].trim(); } expr } fn top_level_split(expr: &str, sep: char) -> Vec<&str> { let mut parts = Vec::new(); let mut depth = 0; let mut start = 0; for (i, c) in expr.char_indices() { match c { '(' => depth += 1, ')' => depth -= 1, c if c == sep && depth == 0 => { parts.push(&expr[start..i]); start = i + 1; } _ => {} } } parts.push(&expr[start..]); parts } /// A value attribute: decimal, hex, `(~0U)`-style, float constants (none /// of which sizes anything here) left out. fn parse_value(v: &str) -> Option { let v = v.trim().trim_start_matches('(').trim_end_matches(')'); let (negate, v) = match v.strip_prefix('~') { Some(rest) => (true, rest), None => (false, v), }; let v = v.trim_end_matches(['U', 'L', 'u', 'l']); let n = if let Some(hex) = v.strip_prefix("0x") { i64::from_str_radix(hex, 16).ok()? } else { v.parse::().ok()? }; Some(if negate { !n } else { n }) } /// A ``, `` or ``: its mixed text read in order. fn read_var(e: &Element) -> Result { use super::xml::Node; let mut ty = String::new(); let mut name = String::new(); let mut pointers = Vec::new(); let mut dims = Vec::new(); // Whether a `const` came before the type, or between `*`s. let mut pending_const = false; let mut after_name = String::new(); for child in &e.children { match child { Node::Element(c) if c.name == "type" => ty = c.text(), Node::Element(c) if c.name == "name" => name = c.text(), Node::Element(c) if c.name == "enum" && !name.is_empty() => { after_name.push_str(&format!("{{{}}}", c.text())); } Node::Element(_) => {} Node::Text(t) if name.is_empty() && ty.is_empty() => { pending_const |= t.contains("const"); } Node::Text(t) if name.is_empty() => { // Between the type and the name: `*`, `* const*`, ... Level // i points at const when a `const` comes before its `*` // (before the type, for the first). for word in t.split_inclusive('*') { if word.contains('*') { pointers.push(pending_const || word.contains("const")); pending_const = false; } } pending_const = false; } Node::Text(t) => after_name.push_str(t), } } // `[4]`, `[{VK_UUID_SIZE}]`, `[3][4]`. for part in after_name.split('[').skip(1) { let inside = part.split(']').next().unwrap_or("").trim(); if let Some(constant) = inside.strip_prefix('{').and_then(|c| c.strip_suffix('}')) { dims.push(Dim::Constant(constant.to_string())); } else if let Ok(n) = inside.parse() { dims.push(Dim::Number(n)); } } if name.is_empty() { return Err(format!("a variable without a name: {}", e.text())); } let len = e.attr("altlen").or(e.attr("len")); Ok(Var { name, ty, pointers, dims, len: len .map(|l| l.split(',').map(str::to_string).collect()) .unwrap_or_default(), optional: e .attr("optional") .map(|o| o.split(',').map(|o| o == "true").collect()) .unwrap_or_default(), selector: e.attr("selector").map(str::to_string), selection: e .attr("selection") .map(|s| s.split(',').map(str::to_string).collect()) .unwrap_or_default(), values: e.attr("values").map(str::to_string), stride: e.attr("stride").map(str::to_string), bits: after_name .trim() .strip_prefix(':') .and_then(|b| b.trim().parse().ok()), }) } /// A struct's members in XML order, except that a count declared after the /// array it counts moves to just before it (vkxml.py `_sort_struct_members`). fn sort_members(members: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(members.len()); for (i, member) in members.iter().enumerate() { if out.iter().any(|m| m.name == member.name) { continue; } // An array whose count comes later: put the count first. if let Some(len) = member.len.first() && let Some(j) = members[i + 1..].iter().position(|m| &m.name == len) { out.push(members[i + 1 + j].clone()); } out.push(member.clone()); } out }