use std::collections::HashMap;
use rspirv::binary::Assemble;
use rspirv::dr;
use rspirv::spirv::{self, Decoration, ExecutionMode, ExecutionModel, Op, StorageClass};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ParseError {
#[error("malformed SPIR-V: {0}")]
Malformed(String),
}
#[derive(Debug, Clone)]
pub struct Module {
inner: dr::Module,
generator: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryPoint {
pub model: ExecutionModel,
pub name: String,
pub function: u32,
pub local_size: Option<[u32; 3]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
pub variable: u32,
pub set: Option<u32>,
pub binding: u32,
pub storage_class: StorageClass,
pub name: Option<String>,
}
impl Module {
pub fn parse(words: &[u32]) -> Result<Self, ParseError> {
let generator = words.get(2).copied().unwrap_or(0);
dr::load_words(words)
.map(|inner| Self { inner, generator })
.map_err(|e| ParseError::Malformed(e.to_string()))
}
pub fn to_words(&self) -> Vec<u32> {
let mut w = self.inner.assemble();
w[2] = self.generator;
w
}
pub fn as_rspirv(&self) -> &dr::Module {
&self.inner
}
pub fn capabilities(&self) -> Vec<spirv::Capability> {
self.inner
.capabilities
.iter()
.filter_map(|i| match i.operands.first() {
Some(dr::Operand::Capability(c)) => Some(*c),
_ => None,
})
.collect()
}
pub fn entry_points(&self) -> Vec<EntryPoint> {
self.inner
.entry_points
.iter()
.filter_map(|ep| {
let (model, function, name) = match ep.operands.as_slice() {
[
dr::Operand::ExecutionModel(m),
dr::Operand::IdRef(f),
dr::Operand::LiteralString(n),
..,
] => (*m, *f, n.clone()),
_ => return None,
};
let local_size =
self.inner
.execution_modes
.iter()
.find_map(|em| match em.operands.as_slice() {
[
dr::Operand::IdRef(f),
dr::Operand::ExecutionMode(ExecutionMode::LocalSize),
dr::Operand::LiteralBit32(x),
dr::Operand::LiteralBit32(y),
dr::Operand::LiteralBit32(z),
] if *f == function => Some([*x, *y, *z]),
_ => None,
});
Some(EntryPoint {
model,
name,
function,
local_size,
})
})
.collect()
}
pub fn bindings(&self) -> Vec<Binding> {
let (set, bind) = self.descriptor_decorations();
let names = self.names();
let mut out: Vec<Binding> = self
.inner
.types_global_values
.iter()
.filter(|i| i.class.opcode == Op::Variable)
.filter_map(|i| {
let id = i.result_id?;
let binding = *bind.get(&id)?;
Some(Binding {
variable: id,
set: set.get(&id).copied(),
binding,
storage_class: storage_class_of(i)?,
name: names.get(&id).cloned(),
})
})
.collect();
out.sort_by_key(|b| (b.set, b.binding, b.variable));
out
}
fn descriptor_decorations(&self) -> (HashMap<u32, u32>, HashMap<u32, u32>) {
let mut set = HashMap::new();
let mut bind = HashMap::new();
for d in self
.inner
.annotations
.iter()
.filter(|d| d.class.opcode == Op::Decorate)
{
if let [
dr::Operand::IdRef(id),
dr::Operand::Decoration(dec),
dr::Operand::LiteralBit32(v),
] = d.operands.as_slice()
{
match dec {
Decoration::DescriptorSet => set.insert(*id, *v),
Decoration::Binding => bind.insert(*id, *v),
_ => None,
};
}
}
(set, bind)
}
fn names(&self) -> HashMap<u32, String> {
self.inner
.debug_names
.iter()
.filter_map(|i| match i.operands.as_slice() {
[dr::Operand::IdRef(id), dr::Operand::LiteralString(n)] => Some((*id, n.clone())),
_ => None,
})
.collect()
}
}
fn storage_class_of(var: &dr::Instruction) -> Option<StorageClass> {
match var.operands.first() {
Some(dr::Operand::StorageClass(s)) => Some(*s),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_garbage() {
assert!(Module::parse(&[1, 2, 3]).is_err());
assert!(Module::parse(&[]).is_err());
}
}