naga-rust-rt 0.1.0

Support library for shaders compiled to Rust via the `naga-rust-back` library.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use core::{cmp, ops};
use num_traits::ConstZero;

// Provides float math functions without std.
// TODO: Be more rigorous and explicitly call libm depending on the feature flag
// instead of using the trait.
#[cfg(not(feature = "std"))]
#[cfg_attr(test, allow(unused_imports))]
use num_traits::float::Float as _;

// -------------------------------------------------------------------------------------------------
// Vector type declarations.
//
// Note that these vectors are *not* prepared to become implemented as SIMD vectors.
// This is because, when SIMD happens, our SIMD story is going to be making the
// application-level vectors’ *components* into SIMD vectors, like:
//     Vec2<std::simd::Simd<f32, 4>>
// This will allow us to have a constant SIMD lane count across the entire execution, even while
// the shader code works with vectors of all sizes and scalars.

/// This type wraps an underlying Rust-native scalar (or someday SIMD) type
/// to provide *only* methods and operators which are compatible with shader
/// function behaviors. That is, they act like `Vec*` even where `T` might not.
/// This allows the code generator to not worry as much about mismatches
/// between Rust and shader semantics.
///
/// TODO: This isn't actually used yet.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Scalar<T>(pub T);

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct Vec2<T> {
    pub x: T,
    pub y: T,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct Vec3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct Vec4<T> {
    pub x: T,
    pub y: T,
    pub z: T,
    pub w: T,
}

// -------------------------------------------------------------------------------------------------
// Most general helper macros

macro_rules! delegate_unary_method_elementwise {
    (const $name:ident ($($component:tt)*)) => {
        #[inline]
        pub const fn $name(self) -> Self {
            Self { $( $component: self.$component.$name() ),* }
        }
    };
    ($name:ident ($($component:tt)*)) => {
        #[inline]
        pub fn $name(self) -> Self {
            Self { $( $component: self.$component.$name() ),* }
        }
    };
}

macro_rules! delegate_unary_methods_elementwise {
    (const { $($name:ident),* } $components:tt) => {
        $( delegate_unary_method_elementwise!(const $name $components ); )*
    };
    ({ $($name:ident),* } $components:tt) => {
        $( delegate_unary_method_elementwise!($name $components ); )*
    };
}

macro_rules! delegate_binary_method_elementwise {
    (const $name:ident ($($component:tt)*)) => {
        #[inline]
        pub const fn $name(self, rhs: Self) -> Self {
            Self { $( $component: self.$component.$name(rhs.$component) ),* }
        }
    };
    ($name:ident ($($component:tt)*)) => {
        #[inline]
        pub fn $name(self, rhs: Self) -> Self {
            Self { $( $component: self.$component.$name(rhs.$component) ),* }
        }
    };
}

macro_rules! delegate_binary_methods_elementwise {
    (const { $($name:ident),* } $components:tt) => {
        $( delegate_binary_method_elementwise!(const $name $components ); )*
    };
    ({ $($name:ident),* } $components:tt) => {
        $( delegate_binary_method_elementwise!($name $components ); )*
    };
}

// -------------------------------------------------------------------------------------------------
// Vector operations

/// Generate arithmetic operators and functions for cases where the element type is a
/// Rust primitive *integer*. (In these cases we must ask for wrapping operations.)
macro_rules! impl_vector_integer_arithmetic {
    ($vec:ident, $int:ty, $( $component:tt )*) => {
        impl ops::Add for $vec<$int> {
            type Output = Self;
            /// Wrapping addition.
            #[inline]
            fn add(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_add(rhs.$component), )* }
            }
        }
        impl ops::Sub for $vec<$int> {
            type Output = Self;
            /// Wrapping subtraction.
            #[inline]
            fn sub(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_sub(rhs.$component), )* }
            }
        }
        impl ops::Mul for $vec<$int> {
            type Output = Self;
            /// Wrapping multiplication.
            #[inline]
            fn mul(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_mul(rhs.$component), )* }
            }
        }
        impl ops::Div for $vec<$int> {
            type Output = Self;
            /// On division by zero or overflow, returns the component of `self`,
            /// per [WGSL](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#arithmetic-expr).
            #[inline]
            fn div(self, rhs: Self) -> Self::Output {
                // wrapping_div() panics on division by zero, which is not what we need
                $vec { $(
                    $component:
                        self.$component.checked_div(rhs.$component)
                            .unwrap_or(self.$component),
                )* }
            }
        }
        impl ops::Rem for $vec<$int> {
            type Output = Self;
            #[inline]
            fn rem(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_rem(rhs.$component), )* }
            }
        }

        // Vector-scalar operations
        impl ops::Add<$int> for $vec<$int> {
            type Output = Self;
            /// Wrapping addition.
            #[inline]
            fn add(self, rhs: $int) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_add(rhs), )* }
            }
        }
        impl ops::Sub<$int> for $vec<$int> {
            type Output = Self;
            /// Wrapping subtraction.
            #[inline]
            fn sub(self, rhs: $int) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_sub(rhs), )* }
            }
        }
        impl ops::Mul<$int> for $vec<$int> {
            type Output = Self;
            /// Wrapping multiplication.
            #[inline]
            fn mul(self, rhs: $int) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_mul(rhs), )* }
            }
        }
        impl ops::Div<$int> for $vec<$int> {
            type Output = Self;
            #[inline]
            /// On division by zero or overflow, returns `self`,
            /// per [WGSL](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#arithmetic-expr).
            fn div(self, rhs: $int) -> Self::Output {
                // wrapping_div() panics on division by zero, which is not what we need
                $vec { $(
                    $component:
                        self.$component.checked_div(rhs)
                            .unwrap_or(self.$component),
                )* }
            }
        }
        impl ops::Rem<$int> for $vec<$int> {
            type Output = Self;
            #[inline]
            fn rem(self, rhs: $int) -> Self::Output {
                $vec { $( $component: self.$component.wrapping_rem(rhs), )* }
            }
        }

        impl $vec<$int> {
            delegate_binary_methods_elementwise!({
                max, min
            } ($($component)*));
        }
    }
}

/// Generate arithmetic operators and functions for cases where the element type is a
/// Rust primitive *float*.
macro_rules! impl_vector_float_arithmetic {
    ($vec:ident, $float:ty, $( $component:tt )*) => {
        // Vector-vector operations
        impl ops::Add for $vec<$float> {
            type Output = Self;
            #[inline]
            fn add(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component + rhs.$component, )* }
            }
        }
        impl ops::Sub for $vec<$float> {
            type Output = Self;
            #[inline]
            fn sub(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component - rhs.$component, )* }
            }
        }
        impl ops::Mul for $vec<$float> {
            type Output = Self;
            #[inline]
            fn mul(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component * rhs.$component, )* }
            }
        }
        impl ops::Div for $vec<$float> {
            type Output = Self;
            #[inline]
            fn div(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component / rhs.$component, )* }
            }
        }
        impl ops::Rem for $vec<$float> {
            type Output = Self;
            #[inline]
            fn rem(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component % rhs.$component, )* }
            }
        }

        // Vector-scalar operations
        impl ops::Add<$float> for $vec<$float> {
            type Output = Self;
            #[inline]
            fn add(self, rhs: $float) -> Self::Output {
                $vec { $( $component: self.$component + rhs, )* }
            }
        }
        impl ops::Sub<$float> for $vec<$float> {
            type Output = Self;
            #[inline]
            fn sub(self, rhs: $float) -> Self::Output {
                $vec { $( $component: self.$component - rhs, )* }
            }
        }
        impl ops::Mul<$float> for $vec<$float> {
            type Output = Self;
            #[inline]
            fn mul(self, rhs: $float) -> Self::Output {
                $vec { $( $component: self.$component * rhs, )* }
            }
        }
        impl ops::Div<$float> for $vec<$float> {
            type Output = Self;
            #[inline]
            fn div(self, rhs: $float) -> Self::Output {
                $vec { $( $component: self.$component / rhs, )* }
            }
        }
        impl ops::Rem<$float> for $vec<$float> {
            type Output = Self;
            #[inline]
            fn rem(self, rhs: $float) -> Self::Output {
                $vec { $( $component: self.$component % rhs, )* }
            }
        }

        // Float math functions (mostly elementwise, but not exclusively)
        impl $vec<$float> {
            /// As per WGSL [`clamp()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#clamp).
            #[inline]
            pub const fn clamp(self, low: Self, high: Self) -> Self {
                // TODO: std clamp() panics if low > high, which isn’t conformant
                // (but maybe a better debugging tool? )
                $vec { $( $component: self.$component.clamp(low.$component, high.$component) ),*  }
            }
            /// As per WGSL [`distance()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#distance-builtin).
            #[inline]
            pub fn distance(self, rhs: Self) -> $float {
                (self - rhs).length()
            }
            /// As per WGSL [`dot()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#dot-builtin).
            #[inline]
            pub const fn dot(self, rhs: Self) -> $float {
                $( self.$component * rhs.$component + )* 0.0
            }
            /// As per WGSL [`faceForward()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#faceForward-builtin).
            #[inline]
            pub fn face_forward(self, e2: Self, e3: Self) -> Self {
                // note this is Rust's definition of signum
                self * -e2.dot(e3).signum()
            }
            /// As per WGSL [`length()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#length-builtin).
            #[inline]
            pub fn length(self) -> $float {
                self.dot(self).sqrt()
            }
            /// As per WGSL [`mix()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#mix-builtin).
            #[inline]
            pub const fn mix(self, rhs: Self, blend: $float) -> Self {
                $vec { $( $component: self.$component * (1.0 - blend) + rhs.$component * blend ),*  }
            }
            /// As per WGSL [`fma()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#fma-builtin).
            #[inline]
            pub fn mul_add(self, b: Self, c: Self) -> Self {
                $vec { $( $component: self.$component.mul_add(b.$component, c.$component) ),*  }
            }
            /// As per WGSL [`normalize()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#normalize-builtin).
            #[inline]
            pub fn normalize(self) -> Self {
                self * self.length().recip()
            }
            /// As per WGSL [`reflect()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#reflect-builtin).
            #[inline]
            pub fn reflect(self, rhs: Self) -> Self {
                self - rhs * (2.0 * rhs.dot(self))
            }
            /// As per WGSL [`saturate()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#saturate-float-builtin).
            #[inline]
            pub const fn saturate(self) -> Self {
                $vec { $( $component: self.$component.clamp(0.0, 1.0) ),* }
            }
            /// As per WGSL [`sign()`](https://www.w3.org/TR/2025/CRD-WGSL-20250322/#sign-builtin).
            #[inline]
            pub const fn sign(self) -> Self {
                $vec { $(
                    // TODO: branchless form of this?
                    $component: if self.$component == 0.0 {
                        0.0
                    } else {
                        self.$component.signum()
                    }
                ),* }
            }

            // TODO: some more of these can be const
            delegate_unary_methods_elementwise!(const {
                abs
            } ($($component)*));
            delegate_unary_methods_elementwise!({
                acos, acosh, asin, asinh, atan, atanh, ceil, cos, cosh, exp, exp2, floor, fract, log2, round,
                sin, sinh, tan, tanh, trunc, to_degrees, to_radians
            } ($($component)*));
            delegate_binary_methods_elementwise!({
                atan2, max, min, powf
            } ($($component)*));

            // TODO: modf, frexp, ldexp, cross, refract, step, smoothstep, inverse_sqrt,
            // quantizeToF16, pack*,
        }
    }
}

macro_rules! impl_vector_bitwise {
    ($vec:ident, $int:ty, $( $component:tt )*) => {
        impl ops::BitAnd for $vec<$int> {
            type Output = Self;
            fn bitand(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component & rhs.$component, )* }
            }
        }
        impl ops::BitOr for $vec<$int> {
            type Output = Self;
            fn bitor(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component | rhs.$component, )* }
            }
        }
        impl ops::BitXor for $vec<$int> {
            type Output = Self;
            fn bitxor(self, rhs: Self) -> Self::Output {
                $vec { $( $component: self.$component ^ rhs.$component, )* }
            }
        }
        impl ops::Not for $vec<$int> {
            type Output = Self;
            fn not(self) -> Self::Output {
                $vec { $( $component: !self.$component, )* }
            }
        }

    }
}

macro_rules! impl_element_casts {
    ($ty:ident) => {
        // TODO: These do not have the right cast semantics, but what *are* the right cast
        // semantics? Naga IR docs are cryptic for `Expression::As`.
        pub fn cast_elem_as_u32(self) -> $ty<u32> {
            self.map(|component| component as u32)
        }
        pub fn cast_elem_as_i32(self) -> $ty<i32> {
            self.map(|component| component as i32)
        }
        pub fn cast_elem_as_f32(self) -> $ty<f32> {
            self.map(|component| component as f32)
        }
        pub fn cast_elem_as_f64(self) -> $ty<f64> {
            self.map(|component| component as f64)
        }
    };
}

macro_rules! impl_vector_regular_fns {
    ( $ty:ident $component_count:literal : $( $component:tt )* ) => {
        impl<T> $ty<T> {
            pub fn splat(value: T) -> Self
            where
                T: Copy
            {
                Self { $( $component: value, )* }
            }
            pub fn splat_from_scalar(value: Scalar<T>) -> Self
            where
                T: Copy
            {
                Self { $( $component: value.0, )* }
            }

            /// Replaces the elements of `self` with the elements of `trues` wherever
            /// `mask` contains [`true`].
            pub const fn select(self, trues: Self, mask: $ty<bool>) -> Self
            where
                T: Copy
            {
                Self {
                    $(
                        $component: if mask.$component {
                            trues.$component
                        } else {
                            self.$component
                        },
                    )*
                }
            }

            pub fn map<U, F>(self, mut f: F) -> $ty<U>
            where
                F: FnMut(T) -> U,
            {
                $ty {
                    $(
                        $component: f(self.$component),
                    )*
                }
            }
        }

        impl_vector_integer_arithmetic!($ty, i32, $($component)*);
        impl_vector_integer_arithmetic!($ty, u32, $($component)*);
        impl_vector_float_arithmetic!($ty, f32, $($component)*);
        impl_vector_float_arithmetic!($ty, f64, $($component)*);

        impl_vector_bitwise!($ty, bool, $($component)*);
        impl_vector_bitwise!($ty, i32, $($component)*);
        impl_vector_bitwise!($ty, u32, $($component)*);

        impl $ty<i32> {
            impl_element_casts!($ty);
        }
        impl $ty<u32> {
            impl_element_casts!($ty);
        }
        impl $ty<f32> {
            impl_element_casts!($ty);
        }
        impl $ty<f64> {
            impl_element_casts!($ty);
        }

        // Zero constant and traits.
        impl<T: ConstZero> $ty<T> {
            // inherent so that traits are not needed in scope
            pub const ZERO: Self = Self { $( $component: T::ZERO, )* };
        }
        impl<T: ConstZero> ConstZero for $ty<T>
        where
            Self: ops::Add<Output = Self>
        {
            const ZERO: Self = Self { $( $component: T::ZERO, )* };
        }
        impl<T: ConstZero> num_traits::Zero for $ty<T>
        where
            Self: ops::Add<Output = Self>
        {
            fn zero() -> Self {
                Self::ZERO
            }
            fn is_zero(&self) -> bool {
                $(T::is_zero(&self.$component) & )* true
            }
        }

        // Elementwise comparison
        impl<T: PartialOrd> $ty<T> {
            pub fn elementwise_eq(self, rhs: Self) -> $ty<bool> {
                self.partial_cmp(rhs).map(|cmp| matches!(cmp, Some(cmp::Ordering::Equal)))
            }
            pub fn elementwise_ne(self, rhs: Self) -> $ty<bool> {
                self.partial_cmp(rhs).map(|cmp| !matches!(cmp, Some(cmp::Ordering::Equal)))
            }
            pub fn elementwise_lt(self, rhs: Self) -> $ty<bool> {
                self.partial_cmp(rhs).map(|cmp| matches!(cmp, Some(cmp::Ordering::Less)))
            }
            pub fn elementwise_le(self, rhs: Self) -> $ty<bool> {
                self.partial_cmp(rhs).map(|cmp| {
                    matches!(cmp, Some(cmp::Ordering::Less | cmp::Ordering::Equal))
                })
            }
            pub fn elementwise_gt(self, rhs: Self) -> $ty<bool> {
                self.partial_cmp(rhs).map(|cmp| matches!(cmp, Some(cmp::Ordering::Greater)))
            }
            pub fn elementwise_ge(self, rhs: Self) -> $ty<bool> {
                self.partial_cmp(rhs).map(|cmp| {
                    matches!(cmp, Some(cmp::Ordering::Greater | cmp::Ordering::Equal))
                })
            }

            /// Helper for comparison operations
            fn partial_cmp(self, rhs: Self) -> $ty<Option<cmp::Ordering>> {
                $ty {
                    $(
                        $component: self.$component.partial_cmp(&rhs.$component),
                    )*
                }
            }
        }

        // Conversion in and out
        impl<T> From<$ty<T>> for [T; $component_count] {
            fn from(value: $ty<T>) -> Self {
                [$( value.$component ),*]
            }
        }

        // Irregular integer math: `$vec<u32>.abs()` exists even though it is the identity,
        // but Rust doesn't have it.
        impl $ty<i32> {
            delegate_unary_methods_elementwise!(const { abs } ($($component)*));
        }
        impl $ty<u32> {
            pub fn abs(self) -> Self { self }
        }
    }
}

impl_vector_regular_fns!(Scalar 1 : 0);
impl_vector_regular_fns!(Vec2 2 : x y);
impl_vector_regular_fns!(Vec3 3 : x y z);
impl_vector_regular_fns!(Vec4 4 : x y z w);

// -------------------------------------------------------------------------------------------------
// Impls that differ between `Vec*` and `Scalar`

/// Applied to every `Vec` type but not `Scalar`
macro_rules! impl_vector_not_scalar_fns {
    ( $ty:ident $component_count:literal : $( $component:tt )* ) => {
        impl<T> $ty<T> {
            // User-friendly constructor, not used by translated code.
            pub const fn new($( $component: T, )*) -> Self {
                Self { $( $component, )* }
            }

            pub const fn from_scalars($( $component: Scalar<T>, )*) -> Self
            where
                T: Copy
            {
                Self { $( $component: $component.0, )* }
            }
        }

        impl<T> From<[T; $component_count]> for $ty<T> {
            fn from(value: [T; $component_count]) -> Self {
                let [$( $component ),*] = value;
                Self::new($( $component ),*)
            }
        }

        // Commutative scalar-vector operators are derived from vector-scalar operators
        impl<T> ops::Add<$ty<T>> for Scalar<T>
        where
            $ty<T>: ops::Add<Scalar<T>>
        {
            type Output = <$ty<T> as ops::Add<Scalar<T>>>::Output;
            fn add(self, rhs: $ty<T>) -> Self::Output {
                rhs + self
            }
        }
        impl<T> ops::Mul<$ty<T>> for Scalar<T>
        where
            $ty<T>: ops::Mul<Scalar<T>>
        {
            type Output = <$ty<T> as ops::Mul<Scalar<T>>>::Output;
            fn mul(self, rhs: $ty<T>) -> Self::Output {
                rhs * self
            }
        }

    }
}

impl_vector_not_scalar_fns!(Vec2 2 : x y);
impl_vector_not_scalar_fns!(Vec3 3 : x y z);
impl_vector_not_scalar_fns!(Vec4 4 : x y z w);

impl<T> Scalar<T> {
    pub fn new(value: T) -> Self {
        Self(value)
    }
}
impl<T> From<[T; 1]> for Scalar<T> {
    fn from([value]: [T; 1]) -> Self {
        Self(value)
    }
}

// -------------------------------------------------------------------------------------------------
// Irregular functions and impls

impl<T> From<T> for Scalar<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl<T: Default> Default for Scalar<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}

// Constructor functions that take a mix of scalars and vectors.
// These names must match those generated by `Writer::write_constructor_expression()`.
macro_rules! impl_flattening_ctor {
    (fn $fn_name:ident ( $($param:tt)* ) => ( $($arg:tt)* )) => {
        pub const fn $fn_name ($($param)*) -> Self {
            Self::new($($arg)*)
        }
    }
}
// Note: Copy bound is solely due to otherwise needing `feature(const_precise_live_drops)`.
impl<T: Copy> Vec3<T> {
    impl_flattening_ctor!(fn new_12(x: T, yz: Vec2<T>) => (x, yz.x, yz.y));
    impl_flattening_ctor!(fn new_21(xy: Vec2<T>, z: T) => (xy.x, xy.y, z));
}
impl<T: Copy> Vec4<T> {
    impl_flattening_ctor!(fn new_112(x: T, y: T, zw: Vec2<T>) => (x, y, zw.x, zw.y));
    impl_flattening_ctor!(fn new_121(x: T, yz: Vec2<T>, w: T) => (x, yz.x, yz.y, w));
    impl_flattening_ctor!(fn new_211(xy: Vec2<T>, z: T, w: T) => (xy.x, xy.y, z, w));
    impl_flattening_ctor!(fn new_22(xy: Vec2<T>, zw: Vec2<T>) => (xy.x, xy.y, zw.x, zw.y));
    impl_flattening_ctor!(fn new_13(x: T, yzw: Vec3<T>) => (x, yzw.x, yzw.y, yzw.z));
    impl_flattening_ctor!(fn new_31(xyz: Vec3<T>, w: T) => (xyz.x, xyz.y, xyz.z, w));
}

// -------------------------------------------------------------------------------------------------
// Swizzles

macro_rules! swizzle_fn {
    ($name:ident $output:ident ($($cin:ident)*) ) => {
        /// Takes the
        #[doc = stringify!($($cin),*)]
        /// elements of `self` and returns them in that order.
        pub fn $name(self) -> $output<T> {
            $output::new($(self.$cin,)*)
        }
    }
}

impl<T: Copy> Vec2<T> {
    swizzle_fn!(xy Vec2(x y));
    swizzle_fn!(yx Vec2(y x));
}
impl<T: Copy> Vec3<T> {
    swizzle_fn!(xy Vec2(x y));
    swizzle_fn!(yx Vec2(y x));
    swizzle_fn!(xyz Vec3(x y z));
    swizzle_fn!(xzy Vec3(x z y));
    swizzle_fn!(yxz Vec3(y x z));
    swizzle_fn!(yzx Vec3(y z x));
    swizzle_fn!(zxy Vec3(z x y));
    swizzle_fn!(zyx Vec3(z y x));
}
impl<T: Copy> Vec4<T> {
    swizzle_fn!(xy Vec2(x y));
    swizzle_fn!(yx Vec2(y x));
    swizzle_fn!(xyz Vec3(x y z));
    swizzle_fn!(xzy Vec3(x z y));
    swizzle_fn!(yxz Vec3(y x z));
    swizzle_fn!(yzx Vec3(y z x));
    swizzle_fn!(zxy Vec3(z x y));
    swizzle_fn!(zyx Vec3(z y x));
    swizzle_fn!(xyzw Vec4(x y z w));
    swizzle_fn!(xywz Vec4(x y w z));
    swizzle_fn!(xzwy Vec4(x z w y));
    swizzle_fn!(xzyw Vec4(x z y w));
    swizzle_fn!(xwyz Vec4(x w y z));
    swizzle_fn!(xwzy Vec4(x w z y));
    swizzle_fn!(yxzw Vec4(y x z w));
    swizzle_fn!(yxwz Vec4(y x w z));
    swizzle_fn!(yzxw Vec4(y z x w));
    swizzle_fn!(yzwx Vec4(y z w x));
    swizzle_fn!(ywzx Vec4(y w z x));
    swizzle_fn!(ywxz Vec4(y w x z));
    swizzle_fn!(zxyw Vec4(z x y w));
    swizzle_fn!(zxwy Vec4(z x w y));
    swizzle_fn!(zyxw Vec4(z y x w));
    swizzle_fn!(zywx Vec4(z y w x));
    swizzle_fn!(zwxy Vec4(z w x y));
    swizzle_fn!(zwyx Vec4(z w y x));
    swizzle_fn!(wxyz Vec4(w x y z));
    swizzle_fn!(wxzy Vec4(w x z y));
    swizzle_fn!(wyxz Vec4(w y x z));
    swizzle_fn!(wyzx Vec4(w y z x));
    swizzle_fn!(wzxy Vec4(w z x y));
    swizzle_fn!(wzyx Vec4(w z y x));
}