vulkane_spirv_parse/
lib.rs1use std::collections::HashMap;
10
11use rspirv::binary::Assemble;
12use rspirv::dr;
13use rspirv::spirv::{self, Decoration, ExecutionMode, ExecutionModel, Op, StorageClass};
14
15#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum ParseError {
19 #[error("malformed SPIR-V: {0}")]
21 Malformed(String),
22}
23
24#[derive(Debug, Clone)]
26pub struct Module {
27 inner: dr::Module,
28 generator: u32,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct EntryPoint {
35 pub model: ExecutionModel,
37 pub name: String,
39 pub function: u32,
41 pub local_size: Option<[u32; 3]>,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Binding {
48 pub variable: u32,
50 pub set: Option<u32>,
52 pub binding: u32,
54 pub storage_class: StorageClass,
56 pub name: Option<String>,
58}
59
60impl Module {
61 pub fn parse(words: &[u32]) -> Result<Self, ParseError> {
63 let generator = words.get(2).copied().unwrap_or(0);
64 dr::load_words(words)
65 .map(|inner| Self { inner, generator })
66 .map_err(|e| ParseError::Malformed(e.to_string()))
67 }
68
69 pub fn to_words(&self) -> Vec<u32> {
72 let mut w = self.inner.assemble();
73 w[2] = self.generator;
74 w
75 }
76
77 pub fn as_rspirv(&self) -> &dr::Module {
79 &self.inner
80 }
81
82 pub fn capabilities(&self) -> Vec<spirv::Capability> {
84 self.inner
85 .capabilities
86 .iter()
87 .filter_map(|i| match i.operands.first() {
88 Some(dr::Operand::Capability(c)) => Some(*c),
89 _ => None,
90 })
91 .collect()
92 }
93
94 pub fn entry_points(&self) -> Vec<EntryPoint> {
96 self.inner
97 .entry_points
98 .iter()
99 .filter_map(|ep| {
100 let (model, function, name) = match ep.operands.as_slice() {
101 [
102 dr::Operand::ExecutionModel(m),
103 dr::Operand::IdRef(f),
104 dr::Operand::LiteralString(n),
105 ..,
106 ] => (*m, *f, n.clone()),
107 _ => return None,
108 };
109 let local_size =
110 self.inner
111 .execution_modes
112 .iter()
113 .find_map(|em| match em.operands.as_slice() {
114 [
115 dr::Operand::IdRef(f),
116 dr::Operand::ExecutionMode(ExecutionMode::LocalSize),
117 dr::Operand::LiteralBit32(x),
118 dr::Operand::LiteralBit32(y),
119 dr::Operand::LiteralBit32(z),
120 ] if *f == function => Some([*x, *y, *z]),
121 _ => None,
122 });
123 Some(EntryPoint {
124 model,
125 name,
126 function,
127 local_size,
128 })
129 })
130 .collect()
131 }
132
133 pub fn bindings(&self) -> Vec<Binding> {
135 let (set, bind) = self.descriptor_decorations();
136 let names = self.names();
137 let mut out: Vec<Binding> = self
138 .inner
139 .types_global_values
140 .iter()
141 .filter(|i| i.class.opcode == Op::Variable)
142 .filter_map(|i| {
143 let id = i.result_id?;
144 let binding = *bind.get(&id)?;
145 Some(Binding {
146 variable: id,
147 set: set.get(&id).copied(),
148 binding,
149 storage_class: storage_class_of(i)?,
150 name: names.get(&id).cloned(),
151 })
152 })
153 .collect();
154 out.sort_by_key(|b| (b.set, b.binding, b.variable));
155 out
156 }
157
158 fn descriptor_decorations(&self) -> (HashMap<u32, u32>, HashMap<u32, u32>) {
160 let mut set = HashMap::new();
161 let mut bind = HashMap::new();
162 for d in self
163 .inner
164 .annotations
165 .iter()
166 .filter(|d| d.class.opcode == Op::Decorate)
167 {
168 if let [
169 dr::Operand::IdRef(id),
170 dr::Operand::Decoration(dec),
171 dr::Operand::LiteralBit32(v),
172 ] = d.operands.as_slice()
173 {
174 match dec {
175 Decoration::DescriptorSet => set.insert(*id, *v),
176 Decoration::Binding => bind.insert(*id, *v),
177 _ => None,
178 };
179 }
180 }
181 (set, bind)
182 }
183
184 fn names(&self) -> HashMap<u32, String> {
185 self.inner
186 .debug_names
187 .iter()
188 .filter_map(|i| match i.operands.as_slice() {
189 [dr::Operand::IdRef(id), dr::Operand::LiteralString(n)] => Some((*id, n.clone())),
190 _ => None,
191 })
192 .collect()
193 }
194}
195
196fn storage_class_of(var: &dr::Instruction) -> Option<StorageClass> {
197 match var.operands.first() {
198 Some(dr::Operand::StorageClass(s)) => Some(*s),
199 _ => None,
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 #[test]
208 fn rejects_garbage() {
209 assert!(Module::parse(&[1, 2, 3]).is_err());
210 assert!(Module::parse(&[]).is_err());
211 }
212}