garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /xtask/src/venus_gen/emit.rs

raw

//! Rust from the narrowed registry: Vulkan's types laid out as C has them,
//! and Venus's encoders and reply decoders for its structs and commands โ€”
//! by venus-protocol's rules (vn_protocol.py), byte for byte.

use super::registry::{Dim, Kind, Registry, Var};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;

pub struct Gen<'a> {
    pub reg: &'a Registry,
    pub selected: &'a BTreeSet<String>,
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum Validity {
    /// All of it.
    Valid,
    /// An output's shape: handles, and structs' sizes, chains and partial
    /// members; no values.
    Partial,
    /// Nothing but a pointer's mark or an array's size.
    Invalid,
}

/// How a scalar goes on the wire.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Wire {
    U8,
    U16,
    U32,
    I32,
    U64,
    I64,
    F32,
    F64,
    SizeT,
    Handle,
}

impl Wire {
    fn size(self) -> usize {
        match self {
            Wire::U8 => 1,
            Wire::U16 => 2,
            Wire::U32 | Wire::I32 | Wire::F32 => 4,
            _ => 8,
        }
    }
}

/// Where the variables of the code being written are: a struct's members
/// (`(*val).x`) or a command's parameters (`x`).
#[derive(Clone, Copy)]
struct Scope<'v> {
    vars: &'v [Var],
    prefix: &'static str,
}

/// A Vulkan name as a Rust identifier: a keyword (`type`) made raw.
fn ident(name: &str) -> String {
    match name {
        "type" | "ref" | "match" | "mod" | "move" | "fn" | "use" | "impl" | "loop" | "box" => {
            format!("r#{name}")
        }
        _ => name.to_string(),
    }
}

impl Scope<'_> {
    fn access(&self, name: &str) -> String {
        format!("{}{}", self.prefix, ident(name))
    }

    fn find(&self, name: &str) -> Option<&Var> {
        self.vars.iter().find(|v| v.name == name)
    }
}

/// Arrays whose elements are arrays counted by another array's element
/// (vkxml.py's two extra levels).
fn inner_count(var: &str) -> Option<&'static str> {
    match var {
        "ppBuildRangeInfos" | "ppMaxPrimitiveCounts" => Some("(*pInfos.add(i)).geometryCount as usize"),
        _ => None,
    }
}

/// A condition that stands in for a null check (vn_protocol.py
/// IGNORABLE_LIST): the array is sent only when it holds.
fn ignorable(owner: &str, var: &str) -> Option<&'static str> {
    match (owner, var) {
        (
            "VkImageCreateInfo" | "VkBufferCreateInfo" | "VkPhysicalDeviceImageDrmFormatModifierInfoEXT",
            "pQueueFamilyIndices",
        ) => Some("(*val).sharingMode == VK_SHARING_MODE_CONCURRENT"),
        ("VkFramebufferCreateInfo", "pAttachments") => {
            Some("((*val).flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT as u32) == 0")
        }
        _ => None,
    }
}

const UNION_DEFAULT_TAGS: &[(&str, u32)] = &[
    ("VkClearColorValue", 2),
    ("VkClearValue", 0),
    ("VkDeviceOrHostAddressKHR", 0),
    ("VkDeviceOrHostAddressConstKHR", 0),
    ("VkPipelineExecutableStatisticValueKHR", 2),
];

impl Gen<'_> {
    fn kind(&self, name: &str) -> Option<&Kind> {
        self.reg.types.get(self.reg.resolve(name)).map(|t| &t.kind)
    }

    fn base(&self, var: &Var) -> String {
        self.reg.resolve(&var.ty).to_string()
    }

    fn value(&self, name: &str) -> i64 {
        self.reg.values.get(name).copied().unwrap_or(0)
    }

    fn dim(&self, d: &Dim) -> u64 {
        match d {
            Dim::Number(n) => *n,
            Dim::Constant(c) => self.value(c) as u64,
        }
    }

    /// How a scalar of type `name` goes on the wire; None for structs,
    /// unions, char, void.
    fn wire(&self, name: &str) -> Option<Wire> {
        let name = self.reg.resolve(name);
        Some(match name {
            "uint8_t" => Wire::U8,
            "uint16_t" => Wire::U16,
            "uint32_t" => Wire::U32,
            "int32_t" => Wire::I32,
            "uint64_t" => Wire::U64,
            "int64_t" => Wire::I64,
            "float" => Wire::F32,
            "double" => Wire::F64,
            "size_t" => Wire::SizeT,
            _ => match self.kind(name)? {
                Kind::Basetype(t) => return self.wire(t),
                Kind::Bitmask { typedef } => {
                    if typedef == "VkFlags64" {
                        Wire::U64
                    } else {
                        Wire::U32
                    }
                }
                Kind::Enum { wide: true } => Wire::U64,
                Kind::Enum { wide: false } => Wire::I32,
                Kind::Handle => Wire::Handle,
                _ => return None,
            },
        })
    }

    /// An element venus-protocol sends packed: a primitive, a basetype or an
    /// enum (bitmasks and handles go one at a time; it makes no difference
    /// to the bytes).
    fn packed(&self, name: &str) -> bool {
        matches!(
            self.kind(name),
            Some(Kind::Primitive | Kind::Basetype(_) | Kind::Enum { .. })
        )
    }

    fn is_struct(&self, name: &str) -> bool {
        matches!(self.kind(name), Some(Kind::Struct { union: false, .. }))
    }

    fn is_union(&self, name: &str) -> bool {
        matches!(self.kind(name), Some(Kind::Struct { union: true, .. }))
    }

    fn is_handle(&self, name: &str) -> bool {
        matches!(self.kind(name), Some(Kind::Handle))
    }

    /// A member or parameter's sType, when its struct has one.
    fn s_type(&self, name: &str) -> Option<i64> {
        match self.kind(name)? {
            Kind::Struct {
                members,
                union: false,
                ..
            } => members
                .first()
                .filter(|m| m.name == "sType")
                .and_then(|m| m.values.as_deref())
                .map(|v| self.value(v)),
            _ => None,
        }
    }

    fn rust_base(&self, name: &str) -> String {
        let name = self.reg.resolve(name);
        match name {
            "uint8_t" => "u8".into(),
            "uint16_t" => "u16".into(),
            "uint32_t" => "u32".into(),
            "int32_t" => "i32".into(),
            "uint64_t" => "u64".into(),
            "int64_t" => "i64".into(),
            "float" => "f32".into(),
            "double" => "f64".into(),
            "size_t" => "usize".into(),
            "char" => "c_char".into(),
            "void" => "c_void".into(),
            _ => name.to_string(),
        }
    }

    /// A variable's Rust type: its base inside its pointers, inside its
    /// fixed dimensions.
    fn rust_ty(&self, var: &Var) -> String {
        let mut ty = self.rust_base(&var.ty);
        for &is_const in &var.pointers {
            ty = format!("*{} {ty}", if is_const { "const" } else { "mut" });
        }
        for d in var.dims.iter().rev() {
            ty = format!("[{ty}; {}]", self.dim(d));
        }
        ty
    }

    /// A command parameter's Rust type: as [`rust_ty`](Self::rust_ty), but a
    /// fixed-size array (`const float blendConstants[4]`) is, as in C, a
    /// pointer to it. Taken by value, the caller's pointer was read as the
    /// floats, and bloom's blend constants were garbage.
    fn param_ty(&self, var: &Var) -> String {
        if var.dims.is_empty() {
            return self.rust_ty(var);
        }
        format!("*const {}", self.rust_ty(var))
    }

    /// A len expression in Rust, as a usize: the variable it names (or the
    /// member of a pointer it names) read in `scope`.
    fn count(&self, len: &str, scope: Scope) -> String {
        if let Some((pointer, member)) = len.split_once("->") {
            let p = scope.access(pointer.trim());
            return format!(
                "(if {p}.is_null() {{ 0 }} else {{ (*{p}).{} as usize }})",
                member.trim()
            );
        }
        // Identifiers replaced, the rest (numbers, + - * /) kept.
        let mut out = String::from("(");
        let mut word = String::new();
        let flush = |word: &mut String, out: &mut String| {
            if word.is_empty() {
                return;
            }
            match scope.find(word) {
                Some(v) if v.is_pointer() => {
                    let p = scope.access(word);
                    write!(out, "(if {p}.is_null() {{ 0 }} else {{ *{p} as usize }})").unwrap();
                }
                Some(_) => write!(out, "({} as usize)", scope.access(word)).unwrap(),
                None => out.push_str(word),
            }
            word.clear();
        };
        for c in len.chars() {
            if c.is_ascii_alphanumeric() || c == '_' {
                word.push(c);
            } else {
                flush(&mut word, &mut out);
                out.push(c);
            }
        }
        flush(&mut word, &mut out);
        out.push(')');
        out
    }

    /// Writes one scalar read from `value` (an expression of its Rust type).
    fn put_scalar(&self, wire: Wire, value: &str) -> String {
        match wire {
            Wire::U8 | Wire::U16 => format!("e.u32({value} as u32);"),
            Wire::U32 => format!("e.u32({value});"),
            Wire::I32 => format!("e.i32({value});"),
            Wire::U64 | Wire::Handle => format!("e.u64({value});"),
            Wire::I64 => format!("e.i64({value});"),
            Wire::F32 => format!("e.f32({value});"),
            Wire::F64 => format!("e.f64({value});"),
            Wire::SizeT => format!("e.u64({value} as u64);"),
        }
    }

    /// Reads one scalar into `place` (a place of its Rust type).
    fn get_scalar(&self, wire: Wire, place: &str) -> String {
        match wire {
            Wire::U8 => format!("{place} = d.u32() as u8;"),
            Wire::U16 => format!("{place} = d.u32() as u16;"),
            Wire::U32 => format!("{place} = d.u32();"),
            Wire::I32 => format!("{place} = d.i32();"),
            Wire::U64 | Wire::Handle => format!("{place} = d.u64();"),
            Wire::I64 => format!("{place} = d.i64();"),
            Wire::F32 => format!("{place} = d.f32();"),
            Wire::F64 => format!("{place} = d.f64();"),
            Wire::SizeT => format!("{place} = d.u64() as usize;"),
        }
    }

    /// Encodes one value of type `base` at pointer `at` (an expression of
    /// `*const T`), whole or partial.
    fn put_one(&self, base: &str, at: &str, validity: Validity, tag: Option<&str>) -> String {
        if let Some(wire) = self.wire(base) {
            return match validity {
                Validity::Valid => self.put_scalar(wire, &format!("*{at}")),
                Validity::Partial if wire == Wire::Handle => self.put_scalar(wire, &format!("*{at}")),
                _ => String::new(),
            };
        }
        let suffix = if validity == Validity::Partial {
            "_partial"
        } else {
            ""
        };
        match tag {
            Some(tag) => format!("enc_{base}{suffix}(e, {at}, {tag});"),
            None => format!("enc_{base}{suffix}(e, {at});"),
        }
    }

    /// Decodes one value of type `base` into pointer `at` (`*mut T`).
    fn get_one(&self, base: &str, at: &str, tag: Option<&str>) -> String {
        if let Some(wire) = self.wire(base) {
            return self.get_scalar(wire, &format!("*{at}"));
        }
        match tag {
            Some(tag) => format!("dec_{base}(d, {at}, {tag});"),
            None => format!("dec_{base}(d, {at});"),
        }
    }

    /// Encodes a variable: a member (`scope` a struct's) or a parameter.
    fn put_var(
        &self,
        owner: &str,
        var: &Var,
        scope: Scope,
        validity: Validity,
        stride_of: Option<&Var>,
    ) -> String {
        let base = self.base(var);
        let acc = scope.access(&var.name);
        let mut out = String::new();
        // A union member chosen by a sibling.
        let tag = var.selector.as_ref().map(|s| scope.access(s));
        // The stride parameter of an array sent at a stride: the element's
        // size goes instead (vn_protocol.py).
        if let Some(array) = stride_of {
            let elem = self.rust_base(&array.ty);
            return format!("e.u32(core::mem::size_of::<{elem}>() as u32);");
        }
        if !var.dims.is_empty() {
            if validity == Validity::Invalid
                || (validity == Validity::Partial && !self.is_struct(&base) && !self.is_handle(&base))
            {
                return out;
            }
            let n: u64 = var.dims.iter().map(|d| self.dim(d)).product();
            writeln!(out, "e.array_size({n});").unwrap();
            if base == "char" || (self.packed(&base) && validity == Validity::Valid) {
                let size = if base == "char" {
                    1
                } else {
                    self.wire(&base).map_or(1, Wire::size)
                };
                writeln!(
                    out,
                    "e.bytes({acc}.as_ptr() as *const c_void, {});",
                    n as usize * size
                )
                .unwrap();
            } else {
                writeln!(out, "for i in 0..{n} {{").unwrap();
                writeln!(
                    out,
                    "    {}",
                    self.put_one(
                        &base,
                        &format!("({acc}.as_ptr() as *const {}).add(i)", self.rust_base(&base)),
                        validity,
                        None
                    )
                )
                .unwrap();
                writeln!(out, "}}").unwrap();
            }
            return out;
        }
        if var.is_pointer() {
            let serializable_pointee = base != "void" || !var.len.is_empty();
            if !serializable_pointee || (self.kind(&base).is_none() && base != "void") {
                return "e.pointer(false);\n".into();
            }
            if base != "void"
                && base != "char"
                && self.wire(&base).is_none()
                && !self.selected.contains(&base)
            {
                // Unserializable (VkAllocationCallbacks): always null.
                return "e.pointer(false);\n".into();
            }
            // A string, or an array of them.
            if base == "char" && var.null_terminated() {
                if var.len.len() == 1 {
                    return match validity {
                        Validity::Valid => format!("e.string({acc});\n"),
                        _ => format!("e.pointer(!{acc}.is_null());\n"),
                    };
                }
                let count = self.count(&var.len[0], scope);
                return match validity {
                    Validity::Valid => format!(
                        "if {acc}.is_null() {{ e.array_size(0); }} else {{\n    e.array_size({count});\n    for i in 0..{count} {{ e.string(*{acc}.add(i)); }}\n}}\n"
                    ),
                    _ => format!("e.array_size(if {acc}.is_null() {{ 0 }} else {{ {count} }});\n"),
                };
            }
            // An array: a size, then the elements.
            if let Some(len) = var.len.first() {
                let count = self.count(len, scope);
                let present = match ignorable(owner, &var.name) {
                    Some(condition) => condition.to_string(),
                    None => format!("!{acc}.is_null()"),
                };
                if validity == Validity::Invalid
                    || (validity == Validity::Partial
                        && !self.is_struct(&base)
                        && !self.is_handle(&base)
                        && !self.is_union(&base))
                {
                    writeln!(out, "e.array_size(if {present} {{ {count} }} else {{ 0 }});").unwrap();
                    return out;
                }
                writeln!(out, "if {present} {{").unwrap();
                writeln!(out, "    let n = {count};").unwrap();
                writeln!(out, "    e.array_size(n);").unwrap();
                if base == "void"
                    || (self.packed(&base) && validity == Validity::Valid && var.stride.is_none())
                {
                    let size = if base == "void" {
                        1
                    } else {
                        self.wire(&base).map_or(1, Wire::size)
                    };
                    writeln!(out, "    e.bytes({acc} as *const c_void, n * {size});").unwrap();
                } else if let Some(inner) = inner_count(&var.name) {
                    let elem = self.rust_base(&base);
                    writeln!(out, "    for i in 0..n {{").unwrap();
                    writeln!(out, "        let m = {inner};").unwrap();
                    writeln!(out, "        e.array_size(m);").unwrap();
                    writeln!(out, "        let row = *{acc}.add(i);").unwrap();
                    writeln!(
                        out,
                        "        for j in 0..m {{ {} }}",
                        self.put_one(&base, &format!("(row as *const {elem}).add(j)"), validity, None)
                    )
                    .unwrap();
                    writeln!(out, "    }}").unwrap();
                } else {
                    let elem = self.rust_base(&base);
                    let at = match &var.stride {
                        Some(stride) => format!(
                            "(({acc} as *const u8).add({} as usize * i) as *const {elem})",
                            scope.access(stride)
                        ),
                        None => format!("({acc} as *const {elem}).add(i)"),
                    };
                    writeln!(
                        out,
                        "    for i in 0..n {{ {} }}",
                        self.put_one(&base, &at, validity, None)
                    )
                    .unwrap();
                }
                writeln!(out, "}} else {{").unwrap();
                writeln!(out, "    e.array_size(0);").unwrap();
                writeln!(out, "}}").unwrap();
                return out;
            }
            // A pointer to one.
            writeln!(out, "e.pointer(!{acc}.is_null());").unwrap();
            if validity != Validity::Invalid
                && !(validity == Validity::Partial
                    && !self.is_struct(&base)
                    && !self.is_handle(&base)
                    && !self.is_union(&base))
            {
                let elem = self.rust_base(&base);
                writeln!(
                    out,
                    "if !{acc}.is_null() {{ {} }}",
                    self.put_one(
                        &base,
                        &format!("({acc} as *const {elem})"),
                        validity,
                        tag.as_deref()
                    )
                )
                .unwrap();
            }
            return out;
        }
        // A value.
        match validity {
            Validity::Invalid => {}
            Validity::Partial
                if !self.is_struct(&base) && !self.is_handle(&base) && !self.is_union(&base) => {}
            _ => {
                if let Some(wire) = self.wire(&base) {
                    writeln!(out, "{}", self.put_scalar(wire, &acc)).unwrap();
                } else {
                    writeln!(
                        out,
                        "{}",
                        self.put_one(&base, &format!("(&raw const {acc})"), validity, tag.as_deref())
                    )
                    .unwrap();
                }
            }
        }
        out
    }

    /// Decodes a variable (a reply's output, or an output struct's member).
    fn get_var(&self, var: &Var, scope: Scope) -> String {
        let base = self.base(var);
        let acc = scope.access(&var.name);
        let tag = var.selector.as_ref().map(|s| scope.access(s));
        let mut out = String::new();
        if !var.dims.is_empty() {
            let n: u64 = var.dims.iter().map(|d| self.dim(d)).product();
            writeln!(out, "let n = d.array_size({n});").unwrap();
            if base == "char" || self.packed(&base) {
                let size = if base == "char" {
                    1
                } else {
                    self.wire(&base).map_or(1, Wire::size)
                };
                writeln!(out, "d.bytes({acc}.as_mut_ptr() as *mut c_void, n * {size});").unwrap();
                if base == "char" {
                    writeln!(out, "if n > 0 {{ {acc}[n - 1] = 0; }}").unwrap();
                }
            } else {
                let elem = self.rust_base(&base);
                writeln!(
                    out,
                    "for i in 0..n {{ {} }}",
                    self.get_one(
                        &base,
                        &format!("({acc}.as_mut_ptr() as *mut {elem}).add(i)"),
                        None
                    )
                )
                .unwrap();
            }
            return out;
        }
        if var.is_pointer() {
            let elem = self.rust_base(&base);
            if base == "char"
                || (base == "void" && var.len.is_empty())
                || (!self.is_struct(&base)
                    && !self.is_union(&base)
                    && self.wire(&base).is_none()
                    && base != "void")
            {
                // Strings and opaque pointers are not read back.
                writeln!(out, "if d.pointer() {{ d.fatal = true; }}").unwrap();
                return out;
            }
            if let Some(len) = var.len.first() {
                let count = self.count(len, scope);
                writeln!(out, "if d.peek_array_size() != 0 {{").unwrap();
                writeln!(out, "    let n = d.array_size({count});").unwrap();
                if base == "void" || self.packed(&base) {
                    let size = if base == "void" {
                        1
                    } else {
                        self.wire(&base).map_or(1, Wire::size)
                    };
                    writeln!(out, "    d.bytes({acc} as *mut c_void, n * {size});").unwrap();
                } else {
                    writeln!(
                        out,
                        "    for i in 0..n {{ {} }}",
                        self.get_one(&base, &format!("({acc} as *mut {elem}).add(i)"), None)
                    )
                    .unwrap();
                }
                writeln!(out, "}} else {{").unwrap();
                writeln!(out, "    d.u64();").unwrap();
                writeln!(out, "}}").unwrap();
                return out;
            }
            writeln!(out, "if d.pointer() {{").unwrap();
            writeln!(
                out,
                "    if {acc}.is_null() {{ d.fatal = true; }} else {{ {} }}",
                self.get_one(&base, &format!("({acc} as *mut {elem})"), tag.as_deref())
            )
            .unwrap();
            writeln!(out, "}}").unwrap();
            return out;
        }
        if let Some(wire) = self.wire(&base) {
            writeln!(out, "{}", self.get_scalar(wire, &acc)).unwrap();
        } else {
            writeln!(
                out,
                "{}",
                self.get_one(&base, &format!("(&raw mut {acc})"), tag.as_deref())
            )
            .unwrap();
        }
        out
    }

    /// The chained structs that may follow `root`: what Venus serializes
    /// whose `structextends` names it.
    fn chain(&self, root: &str) -> Vec<(String, i64)> {
        let mut out = Vec::new();
        for name in self.selected {
            if let Some(Kind::Struct {
                extends,
                union: false,
                ..
            }) = self.kind(name)
                && extends.iter().any(|e| self.reg.resolve(e) == root)
                && let Some(s_type) = self.s_type(name)
            {
                out.push((name.clone(), s_type));
            }
        }
        out
    }

    /// A struct's members, in a struct's scope.
    fn members<'m>(&self, name: &str, members: &'m [Var]) -> Scope<'m> {
        let _ = name;
        Scope {
            vars: members,
            prefix: "(*val).",
        }
    }

    /// Whether a member of a partially encoded struct goes whole: it counts
    /// another member whose length is not fixed by a constant.
    fn counts_another(&self, var: &Var, members: &[Var]) -> bool {
        members.iter().any(|m| {
            let fixed = m.dims.iter().any(|d| matches!(d, Dim::Constant(_))) && !m.len.is_empty();
            !fixed && m.len.first().is_some_and(|l| first_ident(l) == var.name)
        })
    }

    fn emit_struct(&self, out: &mut String, name: &str, members: &[Var]) {
        let scope = self.members(name, members);
        let s_type = self.s_type(name);
        let chain = self.chain(name);
        let body: Vec<&Var> = members
            .iter()
            .filter(|m| m.name != "sType" && m.name != "pNext")
            .collect();
        for (suffix, partial) in [("", false), ("_partial", true)] {
            writeln!(
                out,
                "pub unsafe fn enc_{name}_self{suffix}(e: &mut Encoder, val: *const {name}) {{"
            )
            .unwrap();
            for m in &body {
                let validity = if !partial || self.counts_another(m, members) {
                    Validity::Valid
                } else {
                    Validity::Partial
                };
                let stride_of = None;
                write!(
                    out,
                    "{}",
                    indent(&self.put_var(name, m, scope, validity, stride_of))
                )
                .unwrap();
            }
            writeln!(out, "}}\n").unwrap();
            if let Some(s_type) = s_type {
                writeln!(
                    out,
                    "pub unsafe fn enc_{name}_pnext{suffix}(e: &mut Encoder, at: *const c_void) {{"
                )
                .unwrap();
                writeln!(out, "    let mut p = at as *const Base;").unwrap();
                writeln!(out, "    while !p.is_null() {{").unwrap();
                if !chain.is_empty() {
                    writeln!(out, "        match (*p).s_type {{").unwrap();
                    for (ext, ext_type) in &chain {
                        writeln!(out, "            {ext_type} => {{").unwrap();
                        writeln!(out, "                e.pointer(true);").unwrap();
                        writeln!(out, "                e.i32({ext_type});").unwrap();
                        writeln!(
                            out,
                            "                enc_{name}_pnext{suffix}(e, (*p).p_next as *const c_void);"
                        )
                        .unwrap();
                        writeln!(
                            out,
                            "                enc_{ext}_self{suffix}(e, p as *const {ext});"
                        )
                        .unwrap();
                        writeln!(out, "                return;").unwrap();
                        writeln!(out, "            }}").unwrap();
                    }
                    writeln!(out, "            _ => {{}}").unwrap();
                    writeln!(out, "        }}").unwrap();
                }
                writeln!(out, "        p = (*p).p_next;").unwrap();
                writeln!(out, "    }}").unwrap();
                writeln!(out, "    e.pointer(false);").unwrap();
                writeln!(out, "}}\n").unwrap();
                writeln!(
                    out,
                    "pub unsafe fn enc_{name}{suffix}(e: &mut Encoder, val: *const {name}) {{"
                )
                .unwrap();
                writeln!(out, "    e.i32({s_type});").unwrap();
                writeln!(
                    out,
                    "    enc_{name}_pnext{suffix}(e, (*val).pNext as *const c_void);"
                )
                .unwrap();
                writeln!(out, "    enc_{name}_self{suffix}(e, val);").unwrap();
                writeln!(out, "}}\n").unwrap();
            } else {
                writeln!(
                    out,
                    "pub unsafe fn enc_{name}{suffix}(e: &mut Encoder, val: *const {name}) {{"
                )
                .unwrap();
                writeln!(out, "    enc_{name}_self{suffix}(e, val);").unwrap();
                writeln!(out, "}}\n").unwrap();
            }
        }
        // Reading it back (an output).
        writeln!(
            out,
            "pub unsafe fn dec_{name}_self(d: &mut Decoder, val: *mut {name}) {{"
        )
        .unwrap();
        for m in &body {
            write!(out, "{}", indent(&self.get_var(m, scope))).unwrap();
        }
        writeln!(out, "}}\n").unwrap();
        if let Some(s_type) = s_type {
            writeln!(
                out,
                "pub unsafe fn dec_{name}_pnext(d: &mut Decoder, chain: *mut c_void) {{"
            )
            .unwrap();
            writeln!(out, "    if !d.pointer() {{ return; }}").unwrap();
            writeln!(out, "    let s_type = d.i32();").unwrap();
            writeln!(out, "    let p = find_in_chain(chain, s_type);").unwrap();
            writeln!(out, "    if p.is_null() {{ d.fatal = true; return; }}").unwrap();
            writeln!(
                out,
                "    dec_{name}_pnext(d, (*(p as *mut Base)).p_next as *mut c_void);"
            )
            .unwrap();
            writeln!(out, "    match s_type {{").unwrap();
            for (ext, ext_type) in &chain {
                writeln!(out, "        {ext_type} => dec_{ext}_self(d, p as *mut {ext}),").unwrap();
            }
            writeln!(out, "        _ => d.fatal = true,").unwrap();
            writeln!(out, "    }}").unwrap();
            writeln!(out, "}}\n").unwrap();
            writeln!(
                out,
                "pub unsafe fn dec_{name}(d: &mut Decoder, val: *mut {name}) {{"
            )
            .unwrap();
            writeln!(out, "    if d.i32() != {s_type} {{ d.fatal = true; return; }}").unwrap();
            writeln!(out, "    dec_{name}_pnext(d, (*val).pNext as *mut c_void);").unwrap();
            writeln!(out, "    dec_{name}_self(d, val);").unwrap();
            writeln!(out, "}}\n").unwrap();
        } else {
            writeln!(
                out,
                "pub unsafe fn dec_{name}(d: &mut Decoder, val: *mut {name}) {{"
            )
            .unwrap();
            writeln!(out, "    dec_{name}_self(d, val);").unwrap();
            writeln!(out, "}}\n").unwrap();
        }
    }

    fn emit_union(&self, out: &mut String, name: &str, members: &[Var]) {
        let default = UNION_DEFAULT_TAGS
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, t)| *t);
        let scope = Scope {
            vars: members,
            prefix: "(*val).",
        };
        // The tag: a fixed member's index, or the selector's value.
        let tag_wire = members
            .first()
            .and_then(|m| m.selection.first())
            .and_then(|v| {
                self.reg
                    .enums
                    .iter()
                    .find(|(_, values)| values.iter().any(|(n, _)| n == v))
            })
            .map(|(e, _)| e.clone());
        for (suffix, validity) in [("", Validity::Valid), ("_partial", Validity::Partial)] {
            match default {
                Some(tag) => {
                    writeln!(
                        out,
                        "pub unsafe fn enc_{name}{suffix}(e: &mut Encoder, val: *const {name}) {{"
                    )
                    .unwrap();
                    writeln!(out, "    e.u32({tag});").unwrap();
                    if let Some(m) = members.get(tag as usize) {
                        write!(out, "{}", indent(&self.put_var(name, m, scope, validity, None))).unwrap();
                    }
                    writeln!(out, "}}\n").unwrap();
                }
                None => {
                    let ty = tag_wire.clone().unwrap_or_else(|| "i32".into());
                    writeln!(
                        out,
                        "pub unsafe fn enc_{name}{suffix}(e: &mut Encoder, val: *const {name}, tag: {ty}) {{"
                    )
                    .unwrap();
                    writeln!(out, "    e.i32(tag as i32);").unwrap();
                    writeln!(out, "    match tag as i64 {{").unwrap();
                    for m in members {
                        for v in &m.selection {
                            writeln!(out, "        {} => {{", self.value(v)).unwrap();
                            write!(
                                out,
                                "{}",
                                indent(&indent(&indent(&self.put_var(name, m, scope, validity, None))))
                            )
                            .unwrap();
                            writeln!(out, "        }}").unwrap();
                        }
                    }
                    writeln!(out, "        _ => {{}}").unwrap();
                    writeln!(out, "    }}").unwrap();
                    writeln!(out, "}}\n").unwrap();
                }
            }
        }
        match default {
            Some(_) => {
                writeln!(
                    out,
                    "pub unsafe fn dec_{name}(d: &mut Decoder, val: *mut {name}) {{"
                )
                .unwrap();
                writeln!(out, "    match d.u32() {{").unwrap();
                for (i, m) in members.iter().enumerate() {
                    writeln!(out, "        {i} => {{").unwrap();
                    write!(out, "{}", indent(&indent(&indent(&self.get_var(m, scope))))).unwrap();
                    writeln!(out, "        }}").unwrap();
                }
                writeln!(out, "        _ => d.fatal = true,").unwrap();
                writeln!(out, "    }}").unwrap();
                writeln!(out, "}}\n").unwrap();
            }
            None => {
                let ty = tag_wire.unwrap_or_else(|| "i32".into());
                writeln!(
                    out,
                    "pub unsafe fn dec_{name}(d: &mut Decoder, val: *mut {name}, _tag: {ty}) {{"
                )
                .unwrap();
                writeln!(out, "    match d.i32() as i64 {{").unwrap();
                for m in members {
                    for v in &m.selection {
                        writeln!(out, "        {} => {{", self.value(v)).unwrap();
                        write!(out, "{}", indent(&indent(&indent(&self.get_var(m, scope))))).unwrap();
                        writeln!(out, "        }}").unwrap();
                    }
                }
                writeln!(out, "        _ => d.fatal = true,").unwrap();
                writeln!(out, "    }}").unwrap();
                writeln!(out, "}}\n").unwrap();
            }
        }
    }

    fn emit_command(&self, out: &mut String, name: &str, ret: Option<&Var>, params: &[Var]) {
        let number = self.reg.command_types[name];
        let scope = Scope {
            vars: params,
            prefix: "",
        };
        // In, out, or both (vn_protocol.py _fixup_registry).
        let len_names: BTreeSet<String> = params
            .iter()
            .flat_map(|p| {
                p.len
                    .iter()
                    .filter(|l| *l != "null-terminated")
                    .map(|l| first_ident(l))
            })
            .collect();
        let out_param = |p: &Var| p.is_pointer() && !p.is_const_pointer();
        let in_param = |p: &Var| {
            !out_param(p)
                || len_names.contains(&p.name)
                || (name == "vkRegisterCustomBorderColorEXT" && p.name == "pIndex")
        };
        let signature: Vec<String> = params
            .iter()
            .map(|p| format!("{}: {}", ident(&p.name), self.param_ty(p)))
            .collect();
        let args = signature.join(", ");
        let stride_of = |p: &Var| {
            params
                .iter()
                .find(|q| q.stride.as_deref() == Some(p.name.as_str()))
        };
        writeln!(out, "pub const {}: u32 = {number};", command_const(name)).unwrap();
        writeln!(
            out,
            "pub unsafe fn encode_{name}(e: &mut Encoder, command_flags: u32, {args}) {{"
        )
        .unwrap();
        // An array parameter arrives as a pointer to it; the rest reads it.
        for p in params.iter().filter(|p| !p.dims.is_empty()) {
            writeln!(out, "    let {0} = *{0};", ident(&p.name)).unwrap();
        }
        writeln!(out, "    e.u32({});", command_const(name)).unwrap();
        writeln!(out, "    e.u32(command_flags);").unwrap();
        for p in params {
            let validity = if in_param(p) {
                Validity::Valid
            } else if self.is_struct(&self.base(p))
                || self.is_handle(&self.base(p))
                || self.is_union(&self.base(p))
            {
                Validity::Partial
            } else {
                Validity::Invalid
            };
            write!(
                out,
                "{}",
                indent(&self.put_var(name, p, scope, validity, stride_of(p)))
            )
            .unwrap();
        }
        writeln!(out, "}}\n").unwrap();
        let outs: Vec<&Var> = params.iter().filter(|p| out_param(p)).collect();
        if ret.is_none() && outs.is_empty() {
            return;
        }
        let (ret_ty, ret_read) = match ret {
            Some(r) => {
                let wire = self.wire(&r.ty).unwrap_or(Wire::I32);
                let ty = self.rust_ty(r);
                let read = match wire {
                    Wire::U8 => "d.u32() as u8",
                    Wire::U16 => "d.u32() as u16",
                    Wire::U32 => "d.u32()",
                    Wire::I32 => "d.i32()",
                    Wire::U64 | Wire::Handle => "d.u64()",
                    Wire::I64 => "d.i64()",
                    Wire::F32 => "d.f32()",
                    Wire::F64 => "d.f64()",
                    Wire::SizeT => "d.u64() as usize",
                };
                (ty, read.to_string())
            }
            None => ("()".into(), "()".into()),
        };
        writeln!(
            out,
            "pub unsafe fn decode_{name}_reply(d: &mut Decoder, {args}) -> {ret_ty} {{"
        )
        .unwrap();
        writeln!(
            out,
            "    if d.u32() != {} {{ d.fatal = true; }}",
            command_const(name)
        )
        .unwrap();
        writeln!(out, "    let ret = {ret_read};").unwrap();
        for p in outs {
            write!(out, "{}", indent(&self.get_var(p, scope))).unwrap();
        }
        writeln!(
            out,
            "    let _ = ({});",
            params
                .iter()
                .map(|p| ident(&p.name))
                .collect::<Vec<_>>()
                .join(", ")
        )
        .unwrap();
        writeln!(out, "    ret").unwrap();
        writeln!(out, "}}\n").unwrap();
    }

    /// The types: C's layout, Vulkan's names.
    pub fn types(&self) -> String {
        let mut out = String::new();
        let mut enum_values: BTreeMap<String, String> = BTreeMap::new();
        for name in self.selected {
            let Some(ty) = self.reg.types.get(name) else {
                continue;
            };
            match &ty.kind {
                Kind::Basetype(t) => writeln!(out, "pub type {name} = {};", self.rust_base(t)).unwrap(),
                Kind::Bitmask { typedef } => {
                    writeln!(out, "pub type {name} = {};", self.rust_base(typedef)).unwrap()
                }
                Kind::Handle => writeln!(out, "pub type {name} = u64;").unwrap(),
                Kind::Enum { wide } => {
                    let int = if *wide { "u64" } else { "i32" };
                    writeln!(out, "pub type {name} = {int};").unwrap();
                    for (value, v) in self.reg.enums.get(name).into_iter().flatten() {
                        let v = if *wide {
                            format!("{}", *v as u64)
                        } else {
                            format!("{}", *v as i32)
                        };
                        enum_values.insert(value.clone(), format!("pub const {value}: {name} = {v};"));
                    }
                }
                Kind::Other => writeln!(out, "pub type {name} = *mut c_void;").unwrap(),
                Kind::Struct { members, union, .. } => {
                    writeln!(out, "#[repr(C)]\n#[derive(Clone, Copy)]").unwrap();
                    writeln!(out, "pub {} {name} {{", if *union { "union" } else { "struct" }).unwrap();
                    let mut bitfield = 0;
                    let mut bits_used = 0;
                    for m in members {
                        if let Some(bits) = m.bits {
                            // C packs bitfields into u32s.
                            if bits_used == 0 || bits_used + bits > 32 {
                                writeln!(out, "    pub bitfield{bitfield}: u32,").unwrap();
                                bitfield += 1;
                                bits_used = 0;
                            }
                            bits_used += bits;
                            continue;
                        }
                        bits_used = 0;
                        writeln!(out, "    pub {}: {},", ident(&m.name), self.rust_ty(m)).unwrap();
                    }
                    writeln!(out, "}}\n").unwrap();
                }
                _ => {}
            }
        }
        // The API constants (sizes and counts): as usize, which they count in.
        for (name, v) in self.reg.enums.get("API Constants").into_iter().flatten() {
            enum_values.insert(
                name.clone(),
                format!("pub const {name}: usize = {};", *v as u64 as usize),
            );
        }
        for line in enum_values.values() {
            writeln!(out, "{line}").unwrap();
        }
        // Types the selected ones name that Venus never sends (the allocation
        // callbacks): opaque, only ever behind a null pointer.
        let mut named = BTreeSet::new();
        for name in self.selected {
            match self.reg.types.get(name).map(|t| &t.kind) {
                Some(Kind::Struct { members, .. }) => named.extend(members.iter().map(|m| self.base(m))),
                Some(Kind::Command { params, ret }) => {
                    named.extend(params.iter().map(|p| self.base(p)));
                    named.extend(ret.iter().map(|r| self.base(r)));
                }
                _ => {}
            }
        }
        for name in named {
            if !self.selected.contains(&name) && name.starts_with("Vk") {
                writeln!(out, "pub type {name} = c_void;").unwrap();
            }
        }
        out
    }

    /// The encoders and reply decoders.
    pub fn encoders(&self) -> String {
        let mut out = String::new();
        let mut memo = BTreeMap::new();
        for name in self.selected {
            let Some(ty) = self.reg.types.get(name) else {
                continue;
            };
            match &ty.kind {
                Kind::Struct {
                    members,
                    union: false,
                    ..
                } => {
                    if members.iter().any(|m| m.bits.is_some()) {
                        continue;
                    }
                    self.emit_struct(&mut out, name, members);
                }
                Kind::Struct {
                    members, union: true, ..
                } => self.emit_union(&mut out, name, members),
                Kind::Command { ret, params } if self.reg.serializable(name, &mut memo) => {
                    self.emit_command(&mut out, name, ret.as_ref(), params);
                }
                _ => {}
            }
        }
        out
    }

    /// The driver's commands: each Vulkan function as C calls it, its
    /// handles' ids given out, then sent โ€” a `vkCmd*` recorded into its
    /// command buffer, a command with outputs called and its reply read,
    /// the rest sent. `special` are the driver's own, not written here;
    /// `sent` are sent with no reply and answered VK_SUCCESS.
    /// Ends with the table of names (aliases too) to functions.
    pub fn driver(&self, special: &[&str], sent: &[&str]) -> String {
        let mut out = String::new();
        let mut memo = BTreeMap::new();
        let mut table: Vec<(String, String)> = Vec::new();
        for name in self.selected {
            let Some(Kind::Command { ret, params }) = self.reg.types.get(name).map(|t| &t.kind) else {
                continue;
            };
            if !self.reg.serializable(name, &mut memo) {
                continue;
            }
            table.push((name.clone(), name.clone()));
            for (alias, to) in &self.reg.aliases {
                if to == name && alias.starts_with("vk") {
                    table.push((alias.clone(), name.clone()));
                }
            }
            if special.contains(&name.as_str()) {
                continue;
            }
            let scope = Scope {
                vars: params,
                prefix: "",
            };
            let signature: Vec<String> = params
                .iter()
                .map(|p| format!("{}: {}", ident(&p.name), self.param_ty(p)))
                .collect();
            let args: Vec<String> = params.iter().map(|p| ident(&p.name)).collect();
            let args = args.join(", ");
            let ret_ty = ret.as_ref().map(|r| self.rust_ty(r));
            writeln!(
                out,
                "pub unsafe extern \"system\" fn {name}({}){} {{",
                signature.join(", "),
                ret_ty.as_ref().map(|t| format!(" -> {t}")).unwrap_or_default()
            )
            .unwrap();
            // The handles it makes are named by ids of ours.
            let outs: Vec<&Var> = params
                .iter()
                .filter(|p| p.is_pointer() && !p.is_const_pointer())
                .collect();
            for p in &outs {
                if !self.is_handle(&self.base(p)) || p.pointers.len() != 1 {
                    continue;
                }
                let acc = ident(&p.name);
                match p.len.first() {
                    Some(len) => {
                        let count = self.count(len, scope);
                        writeln!(
                            out,
                            "    if !{acc}.is_null() {{ for i in 0..{count} {{ *{acc}.add(i) = crate::new_id(); }} }}"
                        )
                        .unwrap();
                    }
                    None => writeln!(out, "    if !{acc}.is_null() {{ *{acc} = crate::new_id(); }}").unwrap(),
                }
            }
            if name.starts_with("vkCmd") {
                let buffer = ident(&params[0].name);
                writeln!(
                    out,
                    "    crate::record({buffer}, |e| encode_{name}(e, 0, {args}));"
                )
                .unwrap();
            } else if sent.contains(&name.as_str()) {
                assert!(
                    ret_ty.as_deref() == Some("VkResult"),
                    "{name} is sent with no reply, so must answer a VkResult"
                );
                writeln!(out, "    crate::send(|e| encode_{name}(e, 0, {args}));").unwrap();
                writeln!(out, "    VK_SUCCESS").unwrap();
            } else if ret.is_some() || !outs.is_empty() {
                writeln!(
                    out,
                    "    crate::call({}, |e| encode_{name}(e, crate::GENERATE_REPLY, {args}), |d| decode_{name}_reply(d, {args}))",
                    command_const(name)
                )
                .unwrap();
            } else {
                writeln!(out, "    crate::send(|e| encode_{name}(e, 0, {args}));").unwrap();
            }
            writeln!(out, "}}\n").unwrap();
        }
        // The driver's own that Venus does not carry (vkGetInstanceProcAddr,
        // vkMapMemory) are named too.
        for &own in special {
            if !table.iter().any(|(_, to)| to == own) {
                table.push((own.to_string(), own.to_string()));
                for (alias, to) in &self.reg.aliases {
                    if to == own && alias.starts_with("vk") {
                        table.push((alias.clone(), own.to_string()));
                    }
                }
            }
        }
        writeln!(out, "/// The function a name stands for (an alias's too).").unwrap();
        writeln!(out, "pub fn proc_addr(name: &[u8]) -> PFN_vkVoidFunction {{").unwrap();
        writeln!(
            out,
            "    // SAFETY: each is a function; the caller casts it back to its type."
        )
        .unwrap();
        writeln!(out, "    unsafe {{").unwrap();
        writeln!(out, "        match name {{").unwrap();
        table.sort();
        for (name, to) in &table {
            let path = if special.contains(&to.as_str()) {
                format!("crate::{to}")
            } else {
                to.clone()
            };
            writeln!(
                out,
                "            b\"{name}\" => Some(core::mem::transmute::<*const (), unsafe extern \"system\" fn()>({path} as *const ())),"
            )
            .unwrap();
        }
        writeln!(out, "            _ => None,").unwrap();
        writeln!(out, "        }}").unwrap();
        writeln!(out, "    }}").unwrap();
        writeln!(out, "}}").unwrap();
        out
    }
}

fn first_ident(len: &str) -> String {
    len.trim_start_matches(['(', ' '])
        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .find(|w| !w.is_empty() && !w.chars().next().unwrap().is_ascii_digit())
        .unwrap_or("")
        .to_string()
}

fn command_const(name: &str) -> String {
    // vkSetReplyCommandStreamMESA โ†’ COMMAND_VK_SET_REPLY_COMMAND_STREAM_MESA:
    // a break before a capital that follows a small letter or a digit.
    let mut out = String::from("COMMAND_");
    let mut previous = ' ';
    for c in name.chars() {
        if c.is_ascii_uppercase() && (previous.is_ascii_lowercase() || previous.is_ascii_digit()) {
            out.push('_');
        }
        out.push(c.to_ascii_uppercase());
        previous = c;
    }
    out
}

fn indent(code: &str) -> String {
    code.lines()
        .map(|l| {
            if l.is_empty() {
                "\n".into()
            } else {
                format!("    {l}\n")
            }
        })
        .collect()
}