crcbl-hal 0.2.0

Crucible graphics HAL: backend seam traits and POD descriptors
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
//! Shader modules.
//!
//! # The caller offers every artifact it has; the backend picks
//!
//! [`ShaderModuleDesc`] carries **one field per artifact format** — SPIR-V
//! words, WGSL source, MSL source, DXIL bytes — and the caller fills in every
//! one it has. It does not choose between them and it is not told which backend
//! it is talking to; the backend takes the format it can consume and ignores
//! the rest.
//!
//! This replaces "the seam takes SPIR-V words and nothing else", which held
//! from P0 to P5 on the premise that a backend which cannot consume SPIR-V
//! cross-compiles it. `crcbl-wgpu` disproved the premise: `naga`, the only
//! SPIR-V frontend a browser build can carry, does not implement
//! `DrawParameters`, and every artifact this engine ships declares it because
//! Slang lowers `SV_VertexID` to `gl_VertexIndex - gl_BaseVertex`. So
//! `crcbl-wgpu` could not create a shader module on **any** target — the
//! failure was not browser-specific — while `crcbl-shaders` had been emitting
//! complete WGSL since P5.3 that the seam had no field to carry.
//!
//! Recompiling the SPIR-V without `DrawParameters` would also have unblocked
//! naga. It was rejected: it constrains the Vulkan backend, which wants vertex
//! pulling, in order to widen the wgpu one, and the WGSL artifacts already
//! exist.
//!
//! ## Why fields and not a `ShaderSource` enum
//!
//! An enum with a variant per language was rejected at P0 and is still
//! rejected, for the reason first written down then: it puts artifact-format
//! *selection* above the seam, where the renderer would have to know which
//! backend it was talking to in order to hand it the right bytes. Parallel
//! fields keep the selection below the seam, which is the whole point — a
//! caller says "here is the SPIR-V, here is the WGSL, here is the MSL", every
//! backend sees the same descriptor, and P14's MSL cost exactly one field —
//! not a variant every existing `match` had to grow an arm for. DX4's DXIL cost
//! the same.
//!
//! ## The contract
//!
//! **Callers must supply every format they hold.** Omitting one is not a
//! preference — it is a statement that the artifact does not exist, and it is
//! how a shader silently becomes unusable on a backend that has not been
//! written yet. `crcbl-shaders`' generated table hands out every one
//! (`Shader::spirv`, `Shader::wgsl`, `Shader::msl`,
//! `Shader::dxil_containers`), so the
//! correct call site names all four.
//!
//! **DXIL is per entry point, and the descriptor carries the list rather than
//! the caller splitting itself in two.** `dxc` compiles one entry point per
//! container and a D3D12 pipeline takes one blob per stage, so
//! [`ShaderModuleDesc::dxil`] is a list of `(entry point, container)` pairs
//! where its three neighbours are single artifacts. A caller drawing with a
//! vertex and a fragment stage offers both containers and creates **one**
//! module; the backend that consumes DXIL picks the container named by the
//! [`ShaderEntry::entry_point`] of the stage it is building.
//!
//! One descriptor *per stage* was the alternative, and it was rejected: it puts
//! the granularity of one backend's artifact format above the seam — the exact
//! thing the parallel fields exist to prevent — and it makes the three backends
//! that carry every entry point in one artifact compile that artifact twice,
//! which on Metal is a source compile per stage per pass, to serve the one
//! backend that needs the split.
//!
//! **A descriptor must carry at least one format.** One with neither is
//! [`HalError::ShaderCompilation`].
//!
//! **A backend that is handed only formats it cannot consume must fail, by
//! name.** [`HalError::ShaderCompilation`]
//! whose message says which formats were offered and which the backend needed —
//! never a silent fallback, never a module handle that no pipeline can use.
//! [`ShaderSources`] exists so that message is spelled the same way everywhere.

use core::fmt;

use crcbl_core::Handle;

use crate::{BackendKind, Features, HalError};

/// Marker type for shader-module handles. Uninhabited.
#[derive(Debug)]
pub enum ShaderModule {}

/// A compiled shader module.
pub type ShaderModuleHandle = Handle<ShaderModule>;

bitflags::bitflags! {
    /// Which shader stages something applies to.
    ///
    /// # The two mesh stages are outside every composite, deliberately
    ///
    /// [`MESH`](Self::MESH) and [`TASK`](Self::TASK) are **not** members of
    /// [`GRAPHICS`](Self::GRAPHICS) or [`ALL`](Self::ALL), which is why those
    /// two are documented as "every stage a device is guaranteed to have"
    /// rather than "every stage there is".
    ///
    /// The reason is that a stage flag naming a stage the device does not have
    /// is not merely useless, it is *refused*: Vulkan rejects
    /// `VK_SHADER_STAGE_MESH_BIT_EXT` in a descriptor-set layout or a
    /// push-constant range on a device where `meshShader` was not enabled. So a
    /// composite carrying the mesh bits would break every layout and every
    /// push-constant range in the engine on the majority of devices, to serve
    /// the one pipeline that wants them — the exact inversion of
    /// topic 39's rule that a missing feature degrades
    /// rather than failing.
    ///
    /// A caller therefore names [`MESH`](Self::MESH) explicitly, and only after
    /// checking [`Features::MESH_SHADER`](crate::Features::MESH_SHADER) — the
    /// same discipline [`BindingFlags`](crate::BindingFlags) already asks for.
    /// A caller that skipped it is refused rather than obeyed:
    /// [`check_supported`](Self::check_supported) is what every backend runs
    /// over a bind-group layout's visibility and a push-constant range's
    /// stages.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct ShaderStages: u32 {
        /// Vertex stage.
        const VERTEX = 1 << 0;
        /// Fragment stage.
        const FRAGMENT = 1 << 1;
        /// Compute stage.
        const COMPUTE = 1 << 2;
        /// Mesh stage, which replaces the vertex stage and emits primitives
        /// directly. Requires
        /// [`Features::MESH_SHADER`](crate::Features::MESH_SHADER); see
        /// [`MeshPipelineDesc`](crate::MeshPipelineDesc).
        const MESH = 1 << 3;
        /// Task (D3D12 and Metal call it amplification) stage, which runs
        /// before the mesh stage and chooses how many mesh workgroups to
        /// launch. Requires
        /// [`Features::TASK_SHADER`](crate::Features::TASK_SHADER).
        const TASK = 1 << 4;

        /// Every graphics stage a device is guaranteed to have. See the type
        /// docs on why the mesh stages are not in it.
        const GRAPHICS = Self::VERTEX.bits() | Self::FRAGMENT.bits();
        /// Every stage a device is guaranteed to have.
        const ALL = Self::GRAPHICS.bits() | Self::COMPUTE.bits();
    }
}

impl ShaderStages {
    /// Refuses a stage set that names a stage this device does not have.
    ///
    /// Every backend runs this over each
    /// [`BindGroupLayoutEntry::visibility`](crate::BindGroupLayoutEntry::visibility)
    /// and over a [`PushConstantRange::stages`](crate::PushConstantRange::stages),
    /// so the rule the type docs state is enforced in one place rather than
    /// re-derived per backend. Only the two capability-gated stages can fail
    /// it: every other bit names a stage a device is guaranteed to have.
    ///
    /// **Up front, and not at the driver.** Vulkan refuses
    /// `VK_SHADER_STAGE_MESH_BIT_EXT` in a descriptor-set layout or a
    /// push-constant range on a device without `meshShader` too — but as a VUID
    /// against a `vkCreate*` call, which reaches the caller as an opaque
    /// backend error naming neither the entry nor the capability. Every backend
    /// that reports no [`Features::MESH_SHADER`](crate::Features::MESH_SHADER)
    /// at all does not even get that far: its stage mapping has no bit to map
    /// these onto and would simply drop them, leaving a layout quietly narrower
    /// than the one that was asked for — the failure
    /// topic 39 requires to be loud.
    ///
    /// # Errors
    ///
    /// [`HalError::Unsupported`], naming the stage and the feature it needs.
    pub fn check_supported(self, features: Features, backend: BackendKind) -> Result<(), HalError> {
        for (stage, required, what) in [
            (
                Self::MESH,
                Features::MESH_SHADER,
                "ShaderStages::MESH on a device without MESH_SHADER",
            ),
            (
                Self::TASK,
                Features::TASK_SHADER,
                "ShaderStages::TASK on a device without TASK_SHADER",
            ),
        ] {
            if self.contains(stage) && !features.contains(required) {
                return Err(HalError::Unsupported { backend, what });
            }
        }
        Ok(())
    }
}

bitflags::bitflags! {
    /// Which shader artifact formats are in play — offered by a caller, or
    /// consumable by a backend.
    ///
    /// One bit per field of [`ShaderModuleDesc`]. It exists so that "you gave
    /// me WGSL and I need SPIR-V" is one sentence written once rather than a
    /// phrase each backend invents, and so a test can assert what a call site
    /// supplied without reaching for the descriptor's fields one at a time.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct ShaderSources: u32 {
        /// [`ShaderModuleDesc::spirv`] is non-empty.
        const SPIRV = 1 << 0;
        /// [`ShaderModuleDesc::wgsl`] is `Some`.
        const WGSL = 1 << 1;
        /// [`ShaderModuleDesc::msl`] is `Some`.
        const MSL = 1 << 2;
        /// [`ShaderModuleDesc::dxil`] is `Some`.
        const DXIL = 1 << 3;
    }
}

impl fmt::Display for ShaderSources {
    /// Names the formats in a form that reads inside a sentence:
    /// `"SPIR-V and WGSL"`, `"WGSL"`, or `"nothing"` for the empty set.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for (bit, name) in [
            (Self::SPIRV, "SPIR-V"),
            (Self::WGSL, "WGSL"),
            (Self::MSL, "MSL"),
            (Self::DXIL, "DXIL"),
        ] {
            if self.contains(bit) {
                if !first {
                    f.write_str(" and ")?;
                }
                f.write_str(name)?;
                first = false;
            }
        }
        if first {
            f.write_str("nothing")
        } else {
            Ok(())
        }
    }
}

/// Creation parameters for a shader module.
///
/// One field per artifact format. Fill in every one you have — see the
/// [module docs](self) for why the caller offers and the backend picks, and for
/// what a backend owes you when it cannot use what you offered.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ShaderModuleDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// SPIR-V, as 32-bit words. Empty when there is no SPIR-V artifact.
    ///
    /// Words rather than bytes because SPIR-V is defined as a word stream and
    /// every consumer needs 4-byte alignment; taking `&[u8]` would push a
    /// realignment copy into every backend. Build scripts emit `&[u32]` via
    /// `include_bytes!` + a const transmute helper, or read words at load time.
    ///
    /// Empty rather than `Option<&[u32]>` for absence: a zero-word SPIR-V
    /// module is not a thing that exists — the format's own header is five
    /// words — so the two states cannot be confused, and every existing call
    /// site keeps passing a slice.
    pub spirv: &'a [u32],
    /// WGSL source, as text. `None` when there is no WGSL artifact.
    ///
    /// `Option<&str>` rather than `""` for absence, unlike `spirv` above,
    /// because the empty string *is* a syntactically valid WGSL module — one
    /// with no entry points. Conflating it with "no artifact" would turn a
    /// truncated file into "this backend does not get WGSL" and send the caller
    /// looking in the wrong place.
    ///
    /// Text and not a parsed module: WGSL's interchange form is source, every
    /// consumer of it is a compiler, and the seam has no business owning a
    /// syntax tree.
    pub wgsl: Option<&'a str>,
    /// Metal Shading Language source, as text. `None` when there is no MSL
    /// artifact.
    ///
    /// `Option<&str>` for the same reason [`wgsl`](Self::wgsl) is one: an empty
    /// MSL translation unit is valid — it declares no functions — so conflating
    /// it with "no artifact" would turn a truncated file into "this backend
    /// does not get MSL".
    ///
    /// **Source, not a compiled `.metallib`.** Metal's offline compiler ships
    /// only with Xcode, so `crcbl-shaders` stops at MSL text and `crcbl-mtl`
    /// finishes the job with
    /// `MTLDevice::newLibraryWithSource:options:error:`. A backend that fails
    /// to compile it owes the caller Metal's own message — see
    /// [`HalError::ShaderCompilation`].
    pub msl: Option<&'a str>,
    /// The compiled DXIL containers, each paired with the entry point it was
    /// compiled for. Empty when there is no DXIL artifact.
    ///
    /// **A list where the three fields above are single artifacts, because a
    /// container holds exactly one entry point.** `dxc` compiles a single `-E`
    /// and a D3D12 pipeline state object takes one bytecode blob per stage, so
    /// there is no container that is "the DXIL for `mesh.slang`" the way there
    /// is one SPIR-V module for it. The module still is one module: a backend
    /// that consumes DXIL looks the container up by the
    /// [`ShaderEntry::entry_point`] of the stage it is building, and owes the
    /// caller [`HalError::ShaderCompilation`] naming that entry point when the
    /// list has no container for it — never a pipeline built from whichever
    /// container happened to be first. See the [module docs](self) for what was
    /// rejected.
    ///
    /// The names are matched exactly, as they appear in the SPIR-V
    /// `OpEntryPoint` — the same strings [`ShaderEntry::entry_point`] carries.
    ///
    /// Pairs rather than a map: a module has a handful of entry points, a
    /// linear scan over them is nothing beside creating a pipeline state
    /// object, and a `&[(…)]` is something a caller can build in a `const`
    /// while no map is.
    ///
    /// **Bytes, not text — this field is closer to [`spirv`](Self::spirv) than
    /// to its two `Option<&str>` neighbours.** DXIL is a *signed binary blob*:
    /// a `DxilContainerHeader` whose 16-byte digest covers the contents, so
    /// there is no source for a backend to compile and nothing for it to parse.
    /// `crcbl-dx12` hands the slice straight to
    /// `D3D12_SHADER_BYTECODE`. Passing text through here would only mean the
    /// artifact had been decoded and re-encoded on the way, and an unsigned or
    /// re-encoded container is rejected by every D3D12 driver.
    ///
    /// Absence is the *empty list*, and a pair whose container is empty is a
    /// truncated artifact rather than an absent one — the distinction a
    /// zero-byte file would otherwise lose, reporting a corrupt build as an
    /// unwritten backend. Each container is `&[u8]` rather than `&[u32]`
    /// because nothing about a DXIL container is word-addressed: its parts are
    /// byte-offset, so aligning it would buy no consumer anything.
    pub dxil: &'a [(&'a str, &'a [u8])],
}

impl ShaderModuleDesc<'_> {
    /// Which formats this descriptor actually carries.
    ///
    /// The one place the "empty means absent" rule for
    /// [`spirv`](Self::spirv) is spelled out, so no backend re-derives it.
    #[must_use]
    pub fn provided(&self) -> ShaderSources {
        let mut sources = ShaderSources::empty();
        if !self.spirv.is_empty() {
            sources |= ShaderSources::SPIRV;
        }
        if self.wgsl.is_some() {
            sources |= ShaderSources::WGSL;
        }
        if self.msl.is_some() {
            sources |= ShaderSources::MSL;
        }
        if !self.dxil.is_empty() {
            sources |= ShaderSources::DXIL;
        }
        sources
    }

    /// The error a backend owes a caller when this descriptor carries nothing
    /// it can consume — including the case where it carries nothing at all.
    ///
    /// `accepted` is what the backend can compile. The message names both
    /// sides, because "shader compilation failed" without them sends the reader
    /// to the shader source when the bug is at the call site.
    #[must_use]
    pub fn unusable(&self, accepted: ShaderSources) -> HalError {
        HalError::ShaderCompilation(format!(
            "shader module `{label}` was given {given}, but this backend can only compile \
             {accepted}",
            label = self.label.unwrap_or("<unlabelled>"),
            given = self.provided(),
        ))
    }
}

/// One stage of a pipeline: a module plus the entry point to use from it.
///
/// Slang emits several entry points into one module routinely (a vertex and
/// fragment pair, or a cull shader and its compaction pass), so the entry point
/// is named per-stage rather than assumed to be `main`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShaderEntry<'a> {
    /// Module the code lives in.
    pub module: ShaderModuleHandle,
    /// Entry-point name, as it appears in the SPIR-V `OpEntryPoint`.
    pub entry_point: &'a str,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stage_groups_are_unions_of_their_members() {
        assert!(ShaderStages::GRAPHICS.contains(ShaderStages::VERTEX));
        assert!(ShaderStages::GRAPHICS.contains(ShaderStages::FRAGMENT));
        assert!(!ShaderStages::GRAPHICS.contains(ShaderStages::COMPUTE));
        assert!(ShaderStages::ALL.contains(ShaderStages::GRAPHICS));
        assert!(ShaderStages::ALL.contains(ShaderStages::COMPUTE));
    }

    /// The composites must stay clear of the capability-gated stages. A
    /// `GRAPHICS` that grew a mesh bit would put
    /// `VK_SHADER_STAGE_MESH_BIT_EXT` into every existing layout and
    /// push-constant range, which every device without the feature refuses —
    /// so this is the assertion that keeps a convenience constant from
    /// breaking device creation for everyone. See the type docs.
    #[test]
    fn the_mesh_stages_are_in_no_composite() {
        for composite in [ShaderStages::GRAPHICS, ShaderStages::ALL] {
            assert!(!composite.intersects(ShaderStages::MESH | ShaderStages::TASK));
        }
        assert!(ShaderStages::MESH.intersects(ShaderStages::MESH | ShaderStages::TASK));
        assert_ne!(ShaderStages::MESH, ShaderStages::TASK);
    }

    /// The guard's two halves: a gated stage passes only alongside its own
    /// feature, and the stages every device has pass on a device that reports
    /// nothing at all.
    #[test]
    fn the_gated_stages_need_their_own_feature() {
        let backend = crate::BackendKind::Null;
        for (stage, feature, other) in [
            (
                ShaderStages::MESH,
                Features::MESH_SHADER,
                Features::TASK_SHADER,
            ),
            (
                ShaderStages::TASK,
                Features::TASK_SHADER,
                Features::MESH_SHADER,
            ),
        ] {
            stage
                .check_supported(feature, backend)
                .expect("the stage's own feature is what admits it");
            let HalError::Unsupported { what, .. } = stage
                .check_supported(other, backend)
                .expect_err("the other mesh flag is not this stage's")
            else {
                panic!("a missing capability is an Unsupported, not a generic failure");
            };
            assert!(what.contains("without"), "{what}");
        }

        // The half that would break every existing layout if it were wrong:
        // the guaranteed stages pass on a device reporting nothing.
        ShaderStages::ALL
            .check_supported(Features::empty(), backend)
            .expect("no composite carries a gated stage");
        ShaderStages::empty()
            .check_supported(Features::empty(), backend)
            .expect("an empty stage set names nothing to refuse");
    }

    /// Both stages named at once are refused on their *first* missing feature,
    /// and only the message differs — so a device with one of the two still
    /// gets told which one it is short of.
    #[test]
    fn a_stage_set_naming_both_names_the_one_that_is_missing() {
        let both = ShaderStages::MESH | ShaderStages::TASK;
        let HalError::Unsupported { what, .. } = both
            .check_supported(Features::MESH_SHADER, crate::BackendKind::Null)
            .expect_err("this device has the mesh stage and not the task stage")
        else {
            panic!("a missing capability is an Unsupported");
        };
        assert_eq!(what, "ShaderStages::TASK on a device without TASK_SHADER");
        both.check_supported(
            Features::MESH_SHADER | Features::TASK_SHADER,
            crate::BackendKind::Null,
        )
        .expect("both features present");
    }

    /// SPIR-V magic number, as the first word of any valid module.
    ///
    /// There is deliberately no test that [`ShaderModuleDesc::spirv`] is words
    /// rather than bytes: it is `&[u32]`, so the compiler checks it and a test
    /// could only read its own literal back. That the *magic word* is what a
    /// backend reads is checked where a backend reads it —
    /// `crate::null`'s `shader_modules_reject_non_spirv`.
    const MAGIC: u32 = 0x0723_0203;

    /// The contract's "empty means absent" rule, in both fields, read back
    /// through the one function every backend uses to read it.
    #[test]
    fn provided_reports_exactly_the_formats_that_are_present() {
        let spirv = [MAGIC, 0x0001_0600, 0, 0, 0];
        assert_eq!(
            ShaderModuleDesc::default().provided(),
            ShaderSources::empty()
        );
        assert_eq!(
            ShaderModuleDesc {
                spirv: &spirv,
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::SPIRV
        );
        assert_eq!(
            ShaderModuleDesc {
                wgsl: Some("@fragment fn main() {}"),
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::WGSL
        );
        assert_eq!(
            ShaderModuleDesc {
                msl: Some("[[fragment]] float4 main() { return 0; }"),
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::MSL
        );
        assert_eq!(
            ShaderModuleDesc {
                dxil: &[("mainVs", b"DXBC")],
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::DXIL
        );
        assert_eq!(
            ShaderModuleDesc {
                spirv: &spirv,
                wgsl: Some("@fragment fn main() {}"),
                msl: Some("[[fragment]] float4 main() { return 0; }"),
                dxil: &[("mainVs", b"DXBC"), ("mainPs", b"DXBC")],
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::all(),
            "a module carrying a container for each of its two entry points \
             offers DXIL once, not twice"
        );
    }

    /// An empty DXIL blob is a *present* artifact, like the two text formats
    /// and unlike [`ShaderModuleDesc::spirv`].
    ///
    /// The distinction is the whole reason absence is spelled as the empty
    /// *list* rather than as an empty container: a zero-byte container is a
    /// truncated file, and reporting it as absent would send a reader looking
    /// for an unwritten backend.
    #[test]
    fn an_empty_dxil_blob_is_present_not_absent() {
        assert_eq!(
            ShaderModuleDesc {
                dxil: &[("mainVs", b"")],
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::DXIL
        );
        assert_eq!(
            ShaderModuleDesc::default().provided(),
            ShaderSources::empty(),
            "the default must still report nothing, or the check above is vacuous"
        );
    }

    /// An empty text string is a *present* artifact, not an absent one — the
    /// distinction `Option` exists to keep, for both text formats.
    #[test]
    fn an_empty_text_artifact_is_present_not_absent() {
        assert_eq!(
            ShaderModuleDesc {
                wgsl: Some(""),
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::WGSL
        );
        assert_eq!(
            ShaderModuleDesc {
                msl: Some(""),
                ..ShaderModuleDesc::default()
            }
            .provided(),
            ShaderSources::MSL
        );
    }

    #[test]
    fn source_sets_name_themselves_in_a_sentence() {
        assert_eq!(ShaderSources::empty().to_string(), "nothing");
        assert_eq!(ShaderSources::SPIRV.to_string(), "SPIR-V");
        assert_eq!(ShaderSources::WGSL.to_string(), "WGSL");
        assert_eq!(ShaderSources::MSL.to_string(), "MSL");
        assert_eq!(ShaderSources::DXIL.to_string(), "DXIL");
        assert_eq!(
            (ShaderSources::SPIRV | ShaderSources::WGSL).to_string(),
            "SPIR-V and WGSL"
        );
        assert_eq!(
            ShaderSources::all().to_string(),
            "SPIR-V and WGSL and MSL and DXIL",
            "every bit must have a name in the sentence, or a backend's refusal \
             would silently omit the format the caller actually supplied"
        );
    }

    /// The error a backend owes names both sides of the gap, and the module, so
    /// the reader looks at the call site rather than at the shader source.
    #[test]
    fn the_unusable_error_names_the_gap() {
        let desc = ShaderModuleDesc {
            label: Some("mesh.slang"),
            wgsl: Some("@fragment fn main() {}"),
            ..ShaderModuleDesc::default()
        };
        let HalError::ShaderCompilation(message) = desc.unusable(ShaderSources::SPIRV) else {
            panic!("an unusable descriptor is a shader-compilation failure");
        };
        assert!(message.contains("mesh.slang"), "{message}");
        assert!(message.contains("was given WGSL"), "{message}");
        assert!(message.contains("only compile SPIR-V"), "{message}");
    }

    #[test]
    fn a_descriptor_with_no_artifact_at_all_says_so() {
        let HalError::ShaderCompilation(message) =
            ShaderModuleDesc::default().unusable(ShaderSources::all())
        else {
            panic!("an unusable descriptor is a shader-compilation failure");
        };
        assert!(message.contains("was given nothing"), "{message}");
    }
}