fishstringer_slang_parse/
lib.rs1use tree_sitter::{Node, Parser, Tree};
32use unpopped_convert::{EntryModel, EntryModelError, Frontend, Resource, ResourceKind, Semantic};
33
34#[must_use]
39pub fn parse_slang(src: &str) -> Option<Tree> {
40 let mut parser = Parser::new();
41 parser
42 .set_language(&tree_sitter_slang::LANGUAGE_SLANG.into())
43 .ok()?;
44 parser.parse(src, None)
45}
46
47pub const SLANG_RESIDUE: &[&str] = &[
49 "groupshared",
50 "GroupMemoryBarrier",
51 "DeviceMemoryBarrier",
52 "AllMemoryBarrier",
53 "InterlockedAdd",
54 "InterlockedCompareExchange",
55 "RWByteAddressBuffer",
56];
57
58pub const SLANG: Frontend = Frontend::new(
63 "slang",
64 "numthreads",
65 SLANG_RESIDUE,
66 "output",
67 "input",
68 parse_slang,
69)
70.with_entry_model(read_entry_model);
71
72fn text<'a>(n: Node<'_>, src: &'a str) -> &'a str {
73 n.utf8_text(src.as_bytes()).unwrap_or("")
74}
75
76fn collect<'t>(n: Node<'t>, kind: &str, out: &mut Vec<Node<'t>>) {
78 if n.kind() == kind {
79 out.push(n);
80 }
81 let mut c = n.walk();
82 for ch in n.children(&mut c) {
83 collect(ch, kind, out);
84 }
85}
86
87fn numbers(args: Node<'_>, src: &str) -> Vec<u32> {
88 let mut c = args.walk();
89 args.named_children(&mut c)
90 .filter(|a| a.kind() == "number_literal")
91 .filter_map(|a| text(a, src).trim_end_matches(['u', 'U']).parse().ok())
92 .collect()
93}
94
95fn binding_slot(decl: Node<'_>, src: &str) -> Option<u32> {
97 let mut c = decl.walk();
98 for a in decl.children(&mut c) {
99 if a.kind() != "attribute_declaration" {
100 continue;
101 }
102 let mut c2 = a.walk();
103 for attr in a.named_children(&mut c2) {
104 let name = attr.child_by_field_name("name").map(|n| text(n, src));
105 if attr.kind() == "attribute" && name == Some("binding") {
106 let mut c3 = attr.walk();
107 let args = attr
108 .named_children(&mut c3)
109 .find(|n| n.kind() == "argument_list")?;
110 return numbers(args, src).first().copied();
111 }
112 }
113 }
114 None
115}
116
117pub fn read_entry_model(
126 tree: &Tree,
127 src: &str,
128 entry: &str,
129) -> Result<EntryModel, EntryModelError> {
130 let root = tree.root_node();
131 let mut fns = Vec::new();
132 collect(root, "function_definition", &mut fns);
133 let func = fns
134 .into_iter()
135 .find(|f| {
136 f.child_by_field_name("declarator")
137 .and_then(|d| d.child_by_field_name("declarator"))
138 .is_some_and(|n| text(n, src) == entry)
139 })
140 .ok_or_else(|| EntryModelError::new(format!("no entry point named `{entry}`")))?;
141
142 let mut block = None;
144 let mut c = func.walk();
145 for a in func
146 .children(&mut c)
147 .filter(|a| a.kind() == "hlsl_attribute")
148 {
149 let mut calls = Vec::new();
150 collect(a, "call_expression", &mut calls);
151 for call in calls {
152 let is_nt = call
153 .child_by_field_name("function")
154 .is_some_and(|f| text(f, src) == "numthreads");
155 if let (true, Some(args)) = (is_nt, call.child_by_field_name("arguments")) {
156 if let [x, y, z] = numbers(args, src)[..] {
157 block = Some([x, y, z]);
158 } else {
159 return Err(EntryModelError::new(
160 "numthreads without three constant extents",
161 ));
162 }
163 }
164 }
165 }
166
167 let mut semantics = Vec::new();
169 let mut params = Vec::new();
170 collect(func, "parameter_declaration", &mut params);
171 for p in params {
172 let Some(name) = p.child_by_field_name("declarator") else {
173 continue;
174 };
175 let mut sems = Vec::new();
176 collect(p, "semantics", &mut sems);
177 let Some(sem) = sems.first() else { continue };
178 let sem_text = text(*sem, src).trim_start_matches(':').trim();
179 let s = match sem_text {
180 "SV_DispatchThreadID" => Semantic::DispatchThreadId,
181 "SV_GroupID" => Semantic::GroupId,
182 "SV_GroupThreadID" => Semantic::GroupThreadId,
183 "SV_GroupIndex" => Semantic::GroupIndex,
184 other => return Err(EntryModelError::new(format!("the semantic `{other}`"))),
185 };
186 semantics.push((text(name, src).to_string(), s));
187 }
188
189 let mut idents = Vec::new();
191 if let Some(body) = func.child_by_field_name("body") {
192 collect(body, "identifier", &mut idents);
193 }
194 let used: Vec<&str> = idents.iter().map(|n| text(*n, src)).collect();
195
196 let mut resources = Vec::new();
198 let mut c = root.walk();
199 for (order, d) in root
200 .children(&mut c)
201 .filter(|d| d.kind() == "declaration")
202 .enumerate()
203 {
204 let (Some(ty), Some(decl)) = (
205 d.child_by_field_name("type"),
206 d.child_by_field_name("declarator"),
207 ) else {
208 continue;
209 };
210 if ty.kind() != "template_type" {
211 continue;
212 }
213 let name = text(decl, src);
214 if !used.contains(&name) {
215 continue;
216 }
217 let kind_name = ty.child_by_field_name("name").map_or("", |n| text(n, src));
218 let kind = match kind_name {
219 "StructuredBuffer" => ResourceKind::StructuredRO,
220 "RWStructuredBuffer" => ResourceKind::StructuredRW,
221 "ConstantBuffer" => ResourceKind::ConstantBuffer,
222 other => return Err(EntryModelError::new(format!("the resource type `{other}`"))),
223 };
224 let mut targs = Vec::new();
225 collect(ty, "type_descriptor", &mut targs);
226 let elem = targs
227 .first()
228 .and_then(|t| t.child_by_field_name("type"))
229 .map(|t| text(t, src).to_string())
230 .ok_or_else(|| EntryModelError::new("a resource without an element type"))?;
231 let slot = binding_slot(d, src).unwrap_or(u32::try_from(order).unwrap_or(u32::MAX));
232 resources.push(Resource::new(name, kind, elem, slot));
233 }
234 resources.sort_by_key(|r| (r.kind == ResourceKind::ConstantBuffer, r.slot));
235 Ok(EntryModel::new(block, semantics, resources))
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use unpopped::LiftError;
242 use unpopped::ir::{Access, ReduceOp, ScalarExpr};
243 use unpopped_convert::{lift, lift_elementwise, lift_reduction, lift_scan};
244 use unpopped_vocab::ElementKind;
245
246 const F32: &[ElementKind] = &[ElementKind::F32];
247
248 const SLANG_MUL: &str = "StructuredBuffer<float> input0;\n\
249 StructuredBuffer<float> input1;\n\
250 RWStructuredBuffer<float> output;\n\
251 [numthreads(256, 1, 1)]\n\
252 void mul(uint3 tid : SV_DispatchThreadID) {\n\
253 uint i = tid.x;\n\
254 output[i] = input0[i] * input1[i];\n\
255 }";
256 const SLANG_COPY: &str = "StructuredBuffer<float> input0;\n\
257 RWStructuredBuffer<float> output;\n\
258 [numthreads(256, 1, 1)]\n\
259 void k(uint3 tid : SV_DispatchThreadID) { uint i = tid.x; output[i] = input0[i]; }";
260 const SLANG_SUM: &str = "StructuredBuffer<float> input0;\n\
261 RWStructuredBuffer<float> output;\n\
262 [numthreads(256,1,1)]\n\
263 void rsum(uint3 tid : SV_DispatchThreadID){ float acc = 0.0f; for (uint i=0;i<256;i++) acc += input0[i]; output[0] = acc; }";
264 const SLANG_CSUM: &str = "StructuredBuffer<float> input0;\n\
265 RWStructuredBuffer<float> output;\n\
266 [numthreads(256,1,1)]\n\
267 void csum(uint3 tid : SV_DispatchThreadID){ float acc = 0.0f; for (uint i=0;i<256;i++){ acc += input0[i]; output[i] = acc; } }";
268
269 #[test]
270 fn grammar_loads_and_parses() {
271 let tree = parse_slang("float4 f(float x) { return x; }").expect("grammar loads");
272 assert!(!tree.root_node().has_error());
273 }
274
275 #[test]
276 fn syntax_errors_are_error_nodes_not_none() {
277 let tree = parse_slang("void f( {").expect("a parse tree even for broken source");
278 assert!(
279 tree.root_node().has_error(),
280 "broken source must show an ERROR node"
281 );
282 }
283
284 #[test]
285 fn slang_lifts_multiply() {
286 let lifted = lift_elementwise(&SLANG, SLANG_MUL, "slang_mul", F32).unwrap();
287 assert_eq!(lifted.n_inputs, 2);
288 assert_eq!(
289 lifted.op.body,
290 ScalarExpr::Mul(
291 Box::new(ScalarExpr::Input(0)),
292 Box::new(ScalarExpr::Input(1)),
293 )
294 );
295 }
296
297 #[test]
298 fn every_residue_marker_is_refused_as_inexpressible() {
299 for marker in SLANG_RESIDUE {
300 let src = format!(
301 "[numthreads(256,1,1)]\nvoid k(uint3 tid : SV_DispatchThreadID) {{ {marker}; output[tid.x] = input0[tid.x]; }}"
302 );
303 assert!(
304 matches!(
305 lift_elementwise(&SLANG, &src, "x", F32),
306 Err(LiftError::Inexpressible(ref w)) if w == marker
307 ),
308 "{marker}: {:?}",
309 lift_elementwise(&SLANG, &src, "x", F32)
310 );
311 }
312 }
313
314 #[test]
315 fn slang_lifts_sum_reduction() {
316 let lifted = lift_reduction(&SLANG, SLANG_SUM, "rsum", F32).unwrap();
317 assert_eq!(lifted.op.body, ScalarExpr::Input(0));
318 assert!(matches!(
319 lifted.op.access,
320 Access::Reduction {
321 op: ReduceOp::Sum,
322 ..
323 }
324 ));
325 }
326
327 #[test]
328 fn slang_lifts_cumsum() {
329 let lifted = lift_scan(&SLANG, SLANG_CSUM, "csum", F32).unwrap();
330 assert!(matches!(
331 lifted.op.access,
332 Access::Scan {
333 op: ReduceOp::Sum,
334 ..
335 }
336 ));
337 }
338
339 #[test]
340 fn the_three_lifters_do_not_cross() {
341 assert!(lift_elementwise(&SLANG, SLANG_SUM, "x", F32).is_err());
342 assert!(lift_reduction(&SLANG, SLANG_COPY, "x", F32).is_err());
343 assert!(lift_scan(&SLANG, SLANG_CSUM, "x", F32).is_ok());
344 assert!(lift_reduction(&SLANG, SLANG_CSUM, "x", F32).is_err());
345 assert!(lift_elementwise(&SLANG, SLANG_CSUM, "x", F32).is_err());
346 assert!(lift(&SLANG, SLANG_SUM, "x", F32).is_ok());
347 assert!(lift(&SLANG, SLANG_COPY, "x", F32).is_ok());
348 }
349
350 #[test]
351 fn source_without_numthreads_is_not_a_kernel() {
352 assert!(matches!(
353 lift_elementwise(&SLANG, "float f(float x) { return x; }", "x", F32),
354 Err(LiftError::NotAKernel)
355 ));
356 }
357}