wgsl-rs 0.1.0-beta.4

Write WGSL shaders in a subset of Rust: CPU-runnable, GPU-rendered, with wgpu runtime linkage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Regression tests for wgsl-rs#164: vector `==` must lower to
//! `all(lhs == rhs)` and `!=` to `!(all(lhs == rhs))`.
//!
//! Rust's `PartialEq` on vectors yields `bool` (elementwise-all), but WGSL
//! `==` on vectors yields `vecN<bool>` — naga rejects the generated shader
//! wherever a `bool` is required (bindings, returns, conditions).
//!
//! These drive the real `#[wgsl]` macro, render to WGSL, and assert on both
//! specific substrings (to pin the exact lowering) and naga validation.
//! Like `unary_complement.rs`, `skip_validation` keeps the macro's
//! auto-emitted `__validate_wgsl` test off the `--no-default-features`
//! path; the explicit `#[cfg(feature = "validation")]` tests below cover
//! validation instead.

#![allow(dead_code)]
#![allow(unused_variables)]

use wgsl_rs::wgsl;

/// The #164 repro shape: a bool-typed let binding initialized from a
/// vector comparison. Before this fix it rendered `vecN<bool>` into a
/// `bool` binding, which naga rejected; it must now render the wrapped
/// `all(...)`. The `bool` annotation also keeps clippy's
/// `let_and_return` from firing (it skips annotated bindings).
#[wgsl(skip_validation)]
mod eq_repro {
    use wgsl_rs::std::*;

    pub fn compute() -> bool {
        let x: bool = vec2f(0.0, 0.0) == vec2f(0.0, 0.0);
        x
    }
}

#[wgsl(skip_validation)]
mod eq_lowering {
    use wgsl_rs::std::*;

    /// Constructors on both sides.
    pub fn constructors_eq() -> bool {
        vec3f(1.0, 2.0, 3.0) == vec3f(1.0, 2.0, 3.0)
    }

    /// `!=` lowers to `!(all(lhs == rhs))` — matching `PartialEq::ne`,
    /// which is `!(self == other)`, not `all(lhs != rhs)`.
    pub fn constructors_ne() -> bool {
        vec4f(1.0, 2.0, 3.0, 4.0) != vec4f(4.0, 3.0, 2.0, 1.0)
    }

    /// Locals typed by their initializer.
    pub fn locals_eq(a: Vec2f, b: Vec2f) -> bool {
        let c = a;
        let d = b;
        c == d
    }

    /// Locals with explicit type annotations.
    pub fn annotated_eq(a: Vec3f, b: Vec3f) -> bool {
        let e: Vec3f = a;
        let f: Vec3f = b;
        e == f
    }

    /// Multi-component swizzles are vectors.
    pub fn swizzle_eq(a: Vec3f, b: Vec3f) -> bool {
        a.xzy() == b.zyx()
    }

    /// Bool-vector params compare like numeric vectors — `==` must get
    /// the `all(...)` wrap on the WGSL side. This case was previously
    /// impossible: `Vec2b` rendered as the unknown identifier `vec2b`
    /// before wgsl-rs#169 fixed the type render.
    pub fn bool_vec_eq(p: Vec2b, q: Vec2b) -> bool {
        p == q
    }

    /// Bool vectors may be the return type now that `Vec2<bool>`
    /// renders as the generic form. `cmp_eq` yields the raw mask on the
    /// WGSL side.
    pub fn mask_ret(a: Vec2f, b: Vec2f) -> Vec2<bool> {
        cmp_eq(a, b)
    }

    /// Monomorphized generic: the wrap must also apply inside the
    /// instantiated copy of `generic_eq`, where `T` has become `Vec2f`.
    pub fn generic_eq<T: PartialEq>(a: T, b: T) -> bool {
        a == b
    }

    pub fn mono_eq(a: Vec2f, b: Vec2f) -> bool {
        generic_eq::<Vec2f>(a, b)
    }

    /// `cmp_eq` is the componentwise escape hatch: it renders as the raw
    /// WGSL `==` operator, yielding a vecN<bool> mask. Feeding it to
    /// `all` exercises the whole path without needing a bool-vector
    /// return type in the signature (`mask_ret` above covers the
    /// bool-vector return case directly).
    pub fn mask_all_eq(a: Vec2f, b: Vec2f) -> bool {
        all(cmp_eq(a, b))
    }

    /// `cmp_ne` renders as the raw WGSL `!=` operator.
    pub fn mask_any_ne(a: Vec3f, b: Vec3f) -> bool {
        any(cmp_ne(a, b))
    }

    /// Scalars must NOT be wrapped.
    pub fn scalar_eq_stays(a: f32, b: f32) -> bool {
        a == b
    }

    /// Single-component swizzles are scalars and must NOT be wrapped.
    pub fn swizzle_scalar_ne_stays(a: Vec2f, b: Vec2f) -> bool {
        a.x != b.y
    }
}

/// Review-gap cases (PR #176): comparisons whose operands come from the
/// mask builtins, vector-preserving builtins, impl methods, or which are
/// vulnerable to nested-module symbol shadowing, must all still infer as
/// vector-typed and get the `all(...)` wrap.
#[wgsl(skip_validation)]
mod infer_gaps {
    use wgsl_rs::std::*;

    /// Masks compared with `==` are vector comparisons too.
    pub fn mask_vs_mask(a: Vec2f, b: Vec2f, c: Vec2f, d: Vec2f) -> bool {
        cmp_eq(a, b) == cmp_eq(c, d)
    }

    /// Mask locals via let-inference.
    pub fn mask_local_eq(a: Vec2f, b: Vec2f, c: Vec2f, d: Vec2f) -> bool {
        let m = cmp_eq(a, b);
        let n = cmp_eq(c, d);
        m == n
    }

    /// Vector-preserving builtins keep comparisons vector-typed.
    pub fn normalize_eq(a: Vec3f, b: Vec3f) -> bool {
        normalize(a) == normalize(b)
    }

    /// Impl methods with vector returns.
    pub struct Helpers {
        _v: Vec2f,
    }

    impl Helpers {
        pub fn make(v: Vec2f) -> Vec2f {
            v
        }
    }

    pub fn method_call_eq(a: Vec2f, b: Vec2f) -> bool {
        Helpers::make(a) == Helpers::make(b)
    }

    // Linkage values are inferable from the module's `storage!`
    // declarations (a plain comment: macro invocations cannot carry doc
    // comments without an unused-doc-comment warning).
    storage!(group(0), binding(0), INPUT: [Vec2f; 2]);

    pub fn linkage_eq() -> bool {
        let input = get!(INPUT);
        input[0] == input[1]
    }

    /// Associated consts of std vector types are inferable from the type
    /// alias shape.
    pub fn zero_one_eq() -> bool {
        Vec2f::ZERO == Vec2f::ONE
    }

    /// Associated consts of user impls are inferable from the impl's
    /// declared type.
    impl Helpers {
        pub const ORIGIN: Vec2f = vec2f(0.0, 0.0);
    }

    pub fn origin_eq(a: Vec2f) -> bool {
        Helpers::ORIGIN == a
    }

    /// The extended vector-preserving builtin list, spot-checked with
    /// `step`.
    pub fn step_eq(a: Vec3f, b: Vec3f, c: Vec3f, d: Vec3f) -> bool {
        step(a, b) == step(c, d)
    }

    /// A nested module's `make` must not shadow the enclosing module's
    /// `make` during inference (nested mods emit no WGSL, but their
    /// symbols used to leak into the enclosing module's table).
    pub fn make() -> Vec2f {
        vec2f(0.0, 0.0)
    }

    pub fn shadowed_eq() -> bool {
        make() == make()
    }

    mod inner {
        pub fn make() -> f32 {
            0.0
        }
    }
}

// ===== WGSL source assertions =====

#[test]
fn repro_wraps_constructors_in_all() {
    let src = eq_repro::WGSL_SOURCE
        .wgsl_source()
        .expect("render should succeed");
    assert!(
        src.contains("let x: bool = all((vec2f(0.0, 0.0) == vec2f(0.0, 0.0)));"),
        "the #164 repro must emit `all(...)` (binary op parenthesized per wgsl-rs#159), got: {src}"
    );
}

#[test]
fn vector_eq_ne_lower_to_all() {
    let src = eq_lowering::WGSL_SOURCE
        .wgsl_source()
        .expect("render should succeed");
    for (needle, why) in [
        (
            "return all((vec3f(1.0, 2.0, 3.0) == vec3f(1.0, 2.0, 3.0)));",
            "constructor == wraps in all()",
        ),
        (
            "return !all((vec4f(1.0, 2.0, 3.0, 4.0) == vec4f(4.0, 3.0, 2.0, 1.0)));",
            "vector != lowers to !(all(lhs == rhs)); binary op parenthesized per wgsl-rs#159",
        ),
        ("return all((c == d));", "locals compared via =="),
        ("return all((e == f));", "annotated locals compared via =="),
        (
            "return all((a.xzy == b.zyx));",
            "multi-component swizzles are vectors",
        ),
        (
            "return all((a == b));",
            "cmp_eq lowers to the raw == operator; the monomorphized generic_eq body renders the \
             same way",
        ),
        (
            "return any((a != b));",
            "cmp_ne lowers to the raw != operator",
        ),
        (
            "return _1generic_eq_vec2f(a, b);",
            "mono call site is rewritten",
        ),
        (
            "p: vec2<bool>",
            "bool-vector params render as the generic form (#169)",
        ),
        (
            "return all((p == q));",
            "bool-vector == wraps in all() like numeric vectors",
        ),
        (
            "-> vec2<bool>",
            "bool-vector return type renders as the generic form (#169)",
        ),
    ] {
        assert!(
            src.contains(needle),
            "expected `{needle}` ({why}) in: {src}"
        );
    }
    // The mono instance `_1generic_eq_vec2f` must wrap its body.
    assert!(
        src.contains("generic_eq") && src.contains("return all((a == b));"),
        "monomorphized generic_eq must wrap `a == b` in all(), got: {src}"
    );
    // No raw vector == survived unwrapped at a return position.
    assert!(
        !src.contains("return c == d;")
            && !src.contains("return e == f;")
            && !src.contains("return a.xzy() == b.zyx();"),
        "no vector ==/!= should survive lowering, got: {src}"
    );
}

#[test]
fn scalar_comparisons_stay_raw() {
    let src = eq_lowering::WGSL_SOURCE
        .wgsl_source()
        .expect("render should succeed");
    assert!(
        src.contains("return (a == b);"),
        "scalar == must stay free of the all() wrap, got: {src}"
    );
    assert!(
        src.contains("return (a.x != b.y);"),
        "single-component swizzle != must stay free of the all() wrap, got: {src}"
    );
}

#[test]
fn infer_gaps_lower_to_all() {
    let src = infer_gaps::WGSL_SOURCE
        .wgsl_source()
        .expect("render should succeed");
    for (needle, why) in [
        ("return all(((a == b) == (c == d)));", "mask == mask wraps"),
        (
            "let m = (a == b);",
            "mask local binding renders the raw mask",
        ),
        ("return all((m == n));", "mask locals compare via =="),
        (
            "return all((normalize(a) == normalize(b)));",
            "vector-preserving builtins infer",
        ),
        (
            "return all((Helpers_make(a) == Helpers_make(b)));",
            "impl method calls infer",
        ),
        (
            "return all((make() == make()));",
            "nested module does not shadow outer symbols",
        ),
        (
            "return all((input[0] == input[1]));",
            "storage linkage values infer",
        ),
        (
            "return all((vec2f_ZERO == vec2f_ONE));",
            "std vector associated consts infer",
        ),
        (
            "return all((Helpers_ORIGIN == a));",
            "user impl associated consts infer",
        ),
        (
            "return all((step(a, b) == step(c, d)));",
            "step is a vector-preserving builtin",
        ),
    ] {
        assert!(
            src.contains(needle),
            "expected `{needle}` ({why}) in: {src}"
        );
    }
}

// ===== naga validation =====

#[cfg(feature = "validation")]
#[test]
fn repro_validates() {
    eq_repro::WGSL_SOURCE.validate().expect("naga validation");
}

#[cfg(feature = "validation")]
#[test]
fn lowering_validates() {
    eq_lowering::WGSL_SOURCE
        .validate()
        .expect("naga validation");
}

#[cfg(feature = "validation")]
#[test]
fn infer_gaps_validates() {
    infer_gaps::WGSL_SOURCE.validate().expect("naga validation");
}

// ===== CPU-side parity =====
//
// The `#[wgsl]` module stays valid Rust; these lock the two-worlds
// agreement: GPU `all(lhs == rhs)` must produce the same values as
// Rust's vector `PartialEq`.

#[test]
fn cpu_vector_eq_values() {
    use eq_lowering as m;
    use wgsl_rs::std::*;

    let v = vec2f(1.0, 2.0);
    let w = vec2f(3.0, 4.0);
    assert!(m::locals_eq(v, v));
    assert!(!m::locals_eq(v, w));
    assert!(m::annotated_eq(vec3f(1.0, 2.0, 3.0), vec3f(1.0, 2.0, 3.0)));
    assert!(!m::annotated_eq(vec3f(1.0, 2.0, 3.0), vec3f(3.0, 2.0, 1.0)));
    assert!(m::constructors_eq());
    assert!(m::constructors_ne());
    assert!(m::swizzle_eq(vec3f(1.0, 2.0, 3.0), vec3f(2.0, 3.0, 1.0)));
    assert!(!m::swizzle_eq(vec3f(1.0, 2.0, 3.0), vec3f(1.0, 2.0, 3.0)));
    assert!(m::mono_eq(v, v));
    assert!(!m::mono_eq(v, w));
    assert!(m::scalar_eq_stays(2.0, 2.0));
    assert!(!m::scalar_eq_stays(1.0, 2.0));
    assert!(m::swizzle_scalar_ne_stays(vec2f(1.0, 2.0), vec2f(3.0, 4.0)));
    assert!(m::mask_all_eq(v, v));
    assert!(!m::mask_all_eq(v, w));
    assert!(m::mask_any_ne(vec3f(1.0, 2.0, 3.0), vec3f(3.0, 2.0, 1.0)));
    assert!(m::bool_vec_eq(vec2b(true, false), vec2b(true, false)));
    assert!(!m::bool_vec_eq(vec2b(true, false), vec2b(false, false)));
    assert!(m::mask_ret(v, v) == vec2b(true, true));
    assert!(m::mask_ret(v, w) == vec2b(false, false));
    use infer_gaps as g;
    assert!(g::mask_vs_mask(v, w, v, w));
    assert!(!g::mask_vs_mask(v, w, v, v));
    assert!(g::mask_local_eq(v, v, v, v));
    assert!(!g::mask_local_eq(v, w, v, v));
    assert!(g::normalize_eq(vec3f(1.0, 2.0, 3.0), vec3f(1.0, 2.0, 3.0)));
    assert!(!g::normalize_eq(vec3f(1.0, 2.0, 3.0), vec3f(3.0, 2.0, 1.0)));
    assert!(g::method_call_eq(v, v));
    assert!(!g::method_call_eq(v, w));
    assert!(g::shadowed_eq());
    g::INPUT.set([vec2f(1.0, 2.0), vec2f(1.0, 2.0)]);
    assert!(g::linkage_eq());
    g::INPUT.set([vec2f(1.0, 2.0), vec2f(3.0, 4.0)]);
    assert!(!g::linkage_eq());
    assert!(!g::zero_one_eq());
    assert!(g::origin_eq(vec2f(0.0, 0.0)));
    assert!(!g::origin_eq(vec2f(1.0, 1.0)));
    assert!(g::step_eq(
        vec3f(0.0, 0.0, 0.0),
        vec3f(1.0, 1.0, 1.0),
        vec3f(0.0, 0.0, 0.0),
        vec3f(1.0, 1.0, 1.0)
    ));
    assert!(!m::mask_any_ne(vec3f(1.0, 2.0, 3.0), vec3f(1.0, 2.0, 3.0)));
}