Skip to main content

fishstringer_slang_parse/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The Slang front end for [Unpopped](https://crates.io/crates/unpopped).
3//!
4//! FishStringer owns Slang in the CireSnave ecosystem (it moved here from Vulkane's `vulkane-slang-parse`), so the language's parser lives here
5//! (the emitter is `fishstringer-slang-emit`). Unpopped keeps the language-neutral half:
6//! [`Frontend`] and the `lift_*` walkers in `unpopped::convert`, which this crate feeds with
7//! a grammar binding, exactly as `baracuda-cuda-parse` does for CUDA.
8//!
9//! * [`parse_slang`] - Slang source to an error-tolerant tree-sitter CST.
10//! * [`SLANG_RESIDUE`] - constructs refused as inexpressible (shared memory, barriers, atomics).
11//! * [`SLANG`] - the [`Frontend`]: `numthreads` kernels with `output` / `input{K}` buffers.
12//!   The buffer names are not a style choice: `out` and `in` are HLSL keywords.
13//!
14//! ```
15//! use unpopped_convert::lift_elementwise;
16//! use unpopped_vocab::ElementKind;
17//! use fishstringer_slang_parse::SLANG;
18//!
19//! let src = "StructuredBuffer<float> input0;\n\
20//!     RWStructuredBuffer<float> output;\n\
21//!     [numthreads(256, 1, 1)]\n\
22//!     void copy(uint3 tid : SV_DispatchThreadID) { uint i = tid.x; output[i] = input0[i]; }";
23//! let lifted = lift_elementwise(&SLANG, src, "copy", &[ElementKind::F32]).unwrap();
24//! assert_eq!(lifted.n_inputs, 1);
25//! ```
26//!
27//! The grammar crate (`tree-sitter-slang`) is named in exactly one place, [`parse_slang`].
28//! Moved here from `unpopped::convert` (Unpopped `213df4f`, v0.34.11); see
29//! `THIRD-PARTY-NOTICES.md`.
30
31use tree_sitter::{Parser, Tree};
32use unpopped_convert::Frontend;
33
34/// Parse Slang source into a tree-sitter CST.
35///
36/// `None` only if the grammar fails to load or the parser is cancelled; syntax errors
37/// do not return `None`, they appear as `ERROR` nodes in the tree.
38#[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
47/// Slang constructs that aren't IR-expressible - group-shared memory, barriers, atomics.
48pub const SLANG_RESIDUE: &[&str] = &[
49    "groupshared",
50    "GroupMemoryBarrier",
51    "DeviceMemoryBarrier",
52    "AllMemoryBarrier",
53    "InterlockedAdd",
54    "InterlockedCompareExchange",
55    "RWByteAddressBuffer",
56];
57
58/// Slang: `numthreads` compute kernels, `output`/`input{K}` buffers.
59///
60/// The buffer names differ from CUDA's because `out` and `in` are **HLSL keywords** - a
61/// language constraint, not a style choice.
62pub const SLANG: Frontend = Frontend::new(
63    "slang",
64    "numthreads",
65    SLANG_RESIDUE,
66    "output",
67    "input",
68    parse_slang,
69);
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use unpopped::LiftError;
75    use unpopped::ir::{Access, ReduceOp, ScalarExpr};
76    use unpopped_convert::{lift, lift_elementwise, lift_reduction, lift_scan};
77    use unpopped_vocab::ElementKind;
78
79    const F32: &[ElementKind] = &[ElementKind::F32];
80
81    const SLANG_MUL: &str = "StructuredBuffer<float> input0;\n\
82        StructuredBuffer<float> input1;\n\
83        RWStructuredBuffer<float> output;\n\
84        [numthreads(256, 1, 1)]\n\
85        void mul(uint3 tid : SV_DispatchThreadID) {\n\
86            uint i = tid.x;\n\
87            output[i] = input0[i] * input1[i];\n\
88        }";
89    const SLANG_COPY: &str = "StructuredBuffer<float> input0;\n\
90        RWStructuredBuffer<float> output;\n\
91        [numthreads(256, 1, 1)]\n\
92        void k(uint3 tid : SV_DispatchThreadID) { uint i = tid.x; output[i] = input0[i]; }";
93    const SLANG_SUM: &str = "StructuredBuffer<float> input0;\n\
94        RWStructuredBuffer<float> output;\n\
95        [numthreads(256,1,1)]\n\
96        void rsum(uint3 tid : SV_DispatchThreadID){ float acc = 0.0f; for (uint i=0;i<256;i++) acc += input0[i]; output[0] = acc; }";
97    const SLANG_CSUM: &str = "StructuredBuffer<float> input0;\n\
98        RWStructuredBuffer<float> output;\n\
99        [numthreads(256,1,1)]\n\
100        void csum(uint3 tid : SV_DispatchThreadID){ float acc = 0.0f; for (uint i=0;i<256;i++){ acc += input0[i]; output[i] = acc; } }";
101
102    #[test]
103    fn grammar_loads_and_parses() {
104        let tree = parse_slang("float4 f(float x) { return x; }").expect("grammar loads");
105        assert!(!tree.root_node().has_error());
106    }
107
108    #[test]
109    fn syntax_errors_are_error_nodes_not_none() {
110        let tree = parse_slang("void f( {").expect("a parse tree even for broken source");
111        assert!(
112            tree.root_node().has_error(),
113            "broken source must show an ERROR node"
114        );
115    }
116
117    #[test]
118    fn slang_lifts_multiply() {
119        let lifted = lift_elementwise(&SLANG, SLANG_MUL, "slang_mul", F32).unwrap();
120        assert_eq!(lifted.n_inputs, 2);
121        assert_eq!(
122            lifted.op.body,
123            ScalarExpr::Mul(
124                Box::new(ScalarExpr::Input(0)),
125                Box::new(ScalarExpr::Input(1)),
126            )
127        );
128    }
129
130    #[test]
131    fn every_residue_marker_is_refused_as_inexpressible() {
132        for marker in SLANG_RESIDUE {
133            let src = format!(
134                "[numthreads(256,1,1)]\nvoid k(uint3 tid : SV_DispatchThreadID) {{ {marker}; output[tid.x] = input0[tid.x]; }}"
135            );
136            assert!(
137                matches!(
138                    lift_elementwise(&SLANG, &src, "x", F32),
139                    Err(LiftError::Inexpressible(ref w)) if w == marker
140                ),
141                "{marker}: {:?}",
142                lift_elementwise(&SLANG, &src, "x", F32)
143            );
144        }
145    }
146
147    #[test]
148    fn slang_lifts_sum_reduction() {
149        let lifted = lift_reduction(&SLANG, SLANG_SUM, "rsum", F32).unwrap();
150        assert_eq!(lifted.op.body, ScalarExpr::Input(0));
151        assert!(matches!(
152            lifted.op.access,
153            Access::Reduction {
154                op: ReduceOp::Sum,
155                ..
156            }
157        ));
158    }
159
160    #[test]
161    fn slang_lifts_cumsum() {
162        let lifted = lift_scan(&SLANG, SLANG_CSUM, "csum", F32).unwrap();
163        assert!(matches!(
164            lifted.op.access,
165            Access::Scan {
166                op: ReduceOp::Sum,
167                ..
168            }
169        ));
170    }
171
172    #[test]
173    fn the_three_lifters_do_not_cross() {
174        assert!(lift_elementwise(&SLANG, SLANG_SUM, "x", F32).is_err());
175        assert!(lift_reduction(&SLANG, SLANG_COPY, "x", F32).is_err());
176        assert!(lift_scan(&SLANG, SLANG_CSUM, "x", F32).is_ok());
177        assert!(lift_reduction(&SLANG, SLANG_CSUM, "x", F32).is_err());
178        assert!(lift_elementwise(&SLANG, SLANG_CSUM, "x", F32).is_err());
179        assert!(lift(&SLANG, SLANG_SUM, "x", F32).is_ok());
180        assert!(lift(&SLANG, SLANG_COPY, "x", F32).is_ok());
181    }
182
183    #[test]
184    fn source_without_numthreads_is_not_a_kernel() {
185        assert!(matches!(
186            lift_elementwise(&SLANG, "float f(float x) { return x; }", "x", F32),
187            Err(LiftError::NotAKernel)
188        ));
189    }
190}