alice-sdf 6.0.0

ALICE-SDF: 3D/Spatial Data Specialist — Store laws, not polygons. GLSL/WGSL/HLSL transpile, SVO, GPU marching cubes, texture-fit, procedural CSG. Optional bridges to alice-physics / alice-codec / libasp / alice-cache behind features.
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! Which `SdfNode` variant reaches which backend, checked against the ledger
//! `docs/node-support.md`.
//!
//! The evaluators and transpilers dispatch on `SdfNode` with `match`. Where a
//! `match` has no `_ =>` arm, rustc already refuses a variant that has no arm
//! (GLSL / WGSL / HLSL / BlinkScript), but an arm can still forward the child
//! unchanged: `ProjectiveTransform` did so in all three shader languages while
//! `shader_unsupported_nodes` reported nothing. Where a `match` has a wildcard
//! arm, a new variant compiles and falls into it silently: the tree evaluator returns `f32::MAX`,
//! the interval evaluator returns `Interval::EVERYTHING`. This test runs every
//! variant through the backends whose outcome can be observed at run time and
//! records the result per variant:
//!
//! | column     | `ok` means                                     | otherwise              |
//! |------------|------------------------------------------------|------------------------|
//! | `eval`     | a finite distance other than `f32::MAX`        | `fallback`             |
//! | `interval` | a bounded enclosure over a ±2 box              | `everything`           |
//! | `compile`  | `CompiledSdf::try_compile` returns `Ok`        | `err`                  |
//! | `jit`      | `JitCompiledSdf::compile` returns `Ok` (`jit`) | `err`                  |
//! | `jit_simd` | `JitSimdSdf::compile` of the compiled tree     | `err`, `-` (no bytecode) |
//! | `msl`      | `MslShader::transpile` returns `Ok` (`msl`)    | `err`                  |
//! | `glsl` / `wgsl` / `hlsl` | the emit is not the child's emit forwarded unchanged (`glsl` / `gpu` / `hlsl`) | `pass-through` |
//! | `rust`     | `RustSource::transpile` returns `Ok` (`rust`)  | `err`                  |
//! | `ffi`      | a constructor `alice_sdf_<name>` in `src/ffi/` | `missing`              |
//! | `python`   | a constructor `fn <name>(` in `src/python/`    | `missing`              |
//!
//! The two binding columns are matched by name (the variant in snake case,
//! `2D` as `_2d`, `Subtraction` as `subtract`, and the few names in
//! `binding_aliases`), so they say whether a constructor of that name exists,
//! not that it builds the right variant.
//!
//! Checks (each one fails the test):
//! - every variant of `SdfNode` (read from `src/types/mod.rs`) is the top-level
//!   variant of at least one entry (the shared corpus, plus `Triangle` and
//!   `Bezier`, which the compiler rejects and the corpus therefore leaves out), so a new variant without a corpus
//!   entry is caught here instead of falling through every `_ =>` arm unseen
//! - the measured cells equal the committed ledger, in both directions: a backend
//!   that stops handling a variant fails, and so does one that starts handling
//!   it until the ledger records the change
//! - the ledger lists exactly the variants of the enum, and at least one cell
//!   was compared
//! - no transpiler forwards the child of a node that changes the distance
//!   unless `shader_unsupported_nodes` names it, and every one-child variant
//!   other than the distance-transparent ones has an entry that changes the
//!   distance (an identity instance cannot tell a transform from a
//!   pass-through)
//!
//! Columns of a feature that is off in this build are not compared. CI runs the
//! test with `jit,msl,rust,glsl,hlsl` so every column is compared there
//! (`msl` turns on `gpu`, which carries the WGSL transpiler).
//!
//! Regenerate the ledger after an intended change (every feature on):
//! `ALICE_SDF_WRITE_NODE_SUPPORT=1 cargo test --features jit,msl,rust,glsl,hlsl --test test_node_backend_matrix`
//!
//! Author: Moroya Sakamoto

mod common;

use alice_sdf::interval::{eval_interval, Vec3Interval};
use alice_sdf::prelude::*;
use common::corpus::corpus;
use std::collections::BTreeMap;

const LEDGER: &str = "docs/node-support.md";
const COLUMNS: [&str; NCOL] = [
    "eval", "interval", "compile", "jit", "jit_simd", "msl", "glsl", "wgsl", "hlsl", "rust", "ffi",
    "python",
];
const NCOL: usize = 12;

/// Variant names of `SdfNode`, in declaration order, read from the source.
fn enum_variants() -> Vec<String> {
    enum_variants_in(include_str!("../src/types/mod.rs"))
}

/// `enum_variants` over a given source. Line endings are normalised first: a
/// Windows checkout with `core.autocrlf` gives CRLF, and `include_str!` keeps it.
fn enum_variants_in(src: &str) -> Vec<String> {
    let src = src.replace("\r\n", "\n");
    let src = src.as_str();
    let start = src
        .find("pub enum SdfNode {")
        .expect("pub enum SdfNode in src/types/mod.rs");
    let body = &src[start..];
    let end = body.find("\n}\n").expect("end of enum SdfNode");
    let mut out = Vec::new();
    for line in body[..end].lines().skip(1) {
        // a variant starts at four spaces of indentation with an upper-case name
        if let Some(rest) = line.strip_prefix("    ") {
            if rest.starts_with(' ') {
                continue;
            }
            let name: String = rest
                .chars()
                .take_while(|c| c.is_ascii_alphanumeric())
                .collect();
            if name.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
                out.push(name);
            }
        }
    }
    out
}

/// The top-level variant of a node, from its `Debug` form.
fn variant_of(node: &SdfNode) -> String {
    format!("{node:?}")
        .chars()
        .take_while(|c| c.is_ascii_alphanumeric())
        .collect()
}

fn eval_cell(node: &SdfNode) -> &'static str {
    let pts = [
        Vec3::new(0.3, -0.2, 0.1),
        Vec3::new(1.7, 0.4, -0.9),
        Vec3::ZERO,
    ];
    let ok = pts.iter().any(|&p| {
        let d = eval(node, p);
        d.is_finite() && d != f32::MAX
    });
    if ok {
        "ok"
    } else {
        "fallback"
    }
}

fn interval_cell(node: &SdfNode) -> &'static str {
    let b = Vec3Interval::from_bounds(Vec3::splat(-2.0), Vec3::splat(2.0));
    let i = eval_interval(node, b);
    if i.lo.is_finite() || i.hi.is_finite() {
        "ok"
    } else {
        "everything"
    }
}

fn compile_cell(node: &SdfNode) -> &'static str {
    if CompiledSdf::try_compile(node).is_ok() {
        "ok"
    } else {
        "err"
    }
}

#[cfg(feature = "jit")]
fn jit_cell(node: &SdfNode) -> Option<&'static str> {
    Some(
        if alice_sdf::compiled::jit::JitCompiledSdf::compile(node).is_ok() {
            "ok"
        } else {
            "err"
        },
    )
}
#[cfg(not(feature = "jit"))]
const fn jit_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

#[cfg(feature = "jit")]
fn jit_simd_cell(node: &SdfNode) -> Option<&'static str> {
    let Ok(c) = CompiledSdf::try_compile(node) else {
        return Some("-");
    };
    Some(
        if alice_sdf::compiled::jit::JitSimdSdf::compile(&c).is_ok() {
            "ok"
        } else {
            "err"
        },
    )
}
#[cfg(not(feature = "jit"))]
const fn jit_simd_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

#[cfg(feature = "msl")]
fn msl_cell(node: &SdfNode) -> Option<&'static str> {
    use alice_sdf::compiled::{msl::MslShader, TranspileMode};
    Some(
        if MslShader::transpile(node, TranspileMode::Hardcoded).is_ok() {
            "ok"
        } else {
            "err"
        },
    )
}
#[cfg(not(feature = "msl"))]
const fn msl_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

/// Sample points for "does this node change the distance": a ±2 grid at 0.5.
fn distance_grid() -> Vec<Vec3> {
    let mut v = Vec::new();
    for i in -4..=4 {
        for j in -4..=4 {
            for k in -4..=4 {
                v.push(
                    Vec3::new(i as f32, j as f32, k as f32) * 0.5 + Vec3::new(0.03, -0.02, 0.01),
                );
            }
        }
    }
    v
}

/// The tree evaluator returns something other than the child's distance at
/// some grid point.
fn changes_distance(node: &SdfNode, child: &SdfNode) -> bool {
    distance_grid()
        .iter()
        .any(|&p| eval(node, p).to_bits() != eval(child, p).to_bits())
}

/// `pass-through` when `node` has exactly one child, changes the distance on
/// the CPU, and `emit` returns byte-for-byte the child's own source; `ok`
/// otherwise.
#[cfg(any(feature = "glsl", feature = "gpu", feature = "hlsl"))]
fn transpile_cell(node: &SdfNode, emit: impl Fn(&SdfNode) -> String) -> &'static str {
    match common::corpus::single_child(node) {
        Some(child) if changes_distance(node, &child) && emit(node) == emit(&child) => {
            "pass-through"
        }
        _ => "ok",
    }
}

#[cfg(feature = "glsl")]
fn glsl_emit(node: &SdfNode) -> String {
    use alice_sdf::compiled::glsl::{GlslShader, GlslTranspileMode};
    GlslShader::transpile(node, GlslTranspileMode::Hardcoded).source
}
#[cfg(feature = "glsl")]
fn glsl_cell(node: &SdfNode) -> Option<&'static str> {
    Some(transpile_cell(node, glsl_emit))
}
#[cfg(not(feature = "glsl"))]
const fn glsl_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

#[cfg(feature = "gpu")]
fn wgsl_emit(node: &SdfNode) -> String {
    use alice_sdf::compiled::{TranspileMode, WgslShader};
    WgslShader::transpile(node, TranspileMode::Hardcoded).source
}
#[cfg(feature = "gpu")]
fn wgsl_cell(node: &SdfNode) -> Option<&'static str> {
    Some(transpile_cell(node, wgsl_emit))
}
#[cfg(not(feature = "gpu"))]
const fn wgsl_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

#[cfg(feature = "hlsl")]
fn hlsl_emit(node: &SdfNode) -> String {
    use alice_sdf::compiled::hlsl::{HlslShader, HlslTranspileMode};
    HlslShader::transpile(node, HlslTranspileMode::Hardcoded).source
}
#[cfg(feature = "hlsl")]
fn hlsl_cell(node: &SdfNode) -> Option<&'static str> {
    Some(transpile_cell(node, hlsl_emit))
}
#[cfg(not(feature = "hlsl"))]
const fn hlsl_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

#[cfg(feature = "rust")]
fn rust_cell(node: &SdfNode) -> Option<&'static str> {
    Some(
        if alice_sdf::compiled::rust::RustSource::transpile(node).is_ok() {
            "ok"
        } else {
            "err"
        },
    )
}
#[cfg(not(feature = "rust"))]
const fn rust_cell(_: &SdfNode) -> Option<&'static str> {
    None
}

/// `Circle2D` -> `circle_2d`, `ExpSmoothSubtraction` -> `exp_smooth_subtract`.
fn constructor_name(variant: &str) -> String {
    let v = variant
        .replace("2D", "_2d")
        .replace("Subtraction", "Subtract");
    // `_` before an upper-case letter that follows a lower-case letter or a digit,
    // so an acronym stays one word (`IWP` -> `iwp`, `FischerKochS` -> `fischer_koch_s`)
    let mut out = String::new();
    let mut prev: Option<char> = None;
    for c in v.chars() {
        if c.is_ascii_uppercase()
            && prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit())
        {
            out.push('_');
        }
        out.push(c.to_ascii_lowercase());
        prev = Some(c);
    }
    out
}

/// Constructor names that differ from `constructor_name` in one binding:
/// (variant, ffi name, python name).
fn binding_aliases(variant: &str) -> (Option<&'static str>, Option<&'static str>) {
    match variant {
        "Box3d" => (Some("box"), None),
        "SdfSkinning" => (Some("skinning"), None),
        "RepeatInfinite" => (Some("repeat"), Some("repeat")),
        "ScaleNonUniform" => (None, Some("scale_xyz")),
        "Diamond" => (None, Some("diamond_shape")),
        "Stairs" => (None, Some("stairs_shape")),
        _ => (None, None),
    }
}

fn read_tree(dir: &str) -> String {
    fn walk(p: &std::path::Path, out: &mut String) {
        let mut entries: Vec<_> = std::fs::read_dir(p)
            .expect("read binding dir")
            .flatten()
            .collect();
        entries.sort_by_key(std::fs::DirEntry::path);
        for e in entries {
            let path = e.path();
            if path.is_dir() {
                walk(&path, out);
            } else if path.extension().is_some_and(|x| x == "rs") {
                *out += &std::fs::read_to_string(&path).expect("read binding source");
                out.push('\n');
            }
        }
    }
    let mut s = String::new();
    walk(
        &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(dir),
        &mut s,
    );
    assert!(s.len() > 1000, "{dir}: no source read");
    s
}

fn has_fn(src: &str, name: &str) -> bool {
    // `fn name(` / `fn name<` as a whole word
    let pat = format!("fn {name}");
    src.match_indices(&pat).any(|(i, _)| {
        let before_ok = i == 0 || !src.as_bytes()[i - 1].is_ascii_alphanumeric();
        let after = src[i + pat.len()..].trim_start();
        before_ok && (after.starts_with('(') || after.starts_with('<'))
    })
}

/// (ffi, python) cells of one variant.
fn binding_cells(variant: &str, ffi: &str, py: &str) -> (&'static str, &'static str) {
    let base = constructor_name(variant);
    let (fa, pa) = binding_aliases(variant);
    let f = has_fn(ffi, &format!("alice_sdf_{base}"))
        || fa.is_some_and(|a| has_fn(ffi, &format!("alice_sdf_{a}")));
    let p = has_fn(py, &base) || pa.is_some_and(|a| has_fn(py, a));
    (
        if f { "ok" } else { "missing" },
        if p { "ok" } else { "missing" },
    )
}

/// The shared corpus holds only compilable trees (the parity tests compile every
/// entry). Variants the compiler rejects on purpose are added here, so their
/// row records that rejection instead of being missing.
fn entries() -> Vec<(&'static str, SdfNode)> {
    let mut v = corpus();
    v.push((
        "triangle",
        SdfNode::triangle(
            Vec3::new(-0.5, 0.0, 0.0),
            Vec3::new(0.5, 0.0, 0.0),
            Vec3::new(0.0, 0.6, 0.2),
        ),
    ));
    // The corpus `projective_transform` is the identity, which a transpiler
    // that forwards the child also renders correctly.
    v.push((
        "projective_transform_nonidentity",
        common::corpus::projective_nonidentity(),
    ));
    v.push((
        "bezier",
        SdfNode::bezier(
            Vec3::new(-0.6, 0.0, 0.0),
            Vec3::new(0.0, 0.8, 0.0),
            Vec3::new(0.6, 0.0, 0.0),
            0.1,
        ),
    ));
    v
}

/// Per variant, per column: the outcomes of every corpus entry of that variant
/// (joined with `/` when they differ). `None` for a column whose feature is off.
fn measure() -> BTreeMap<String, [Option<String>; NCOL]> {
    let mut acc: BTreeMap<String, [Vec<&'static str>; NCOL]> = BTreeMap::new();
    let mut seen_feature = [
        true, true, true, false, false, false, false, false, false, false, true, true,
    ];
    let ffi = read_tree("src/ffi");
    let py = read_tree("src/python");
    for (_name, node) in entries() {
        let (f, p) = binding_cells(&variant_of(&node), &ffi, &py);
        let cells = [
            Some(eval_cell(&node)),
            Some(interval_cell(&node)),
            Some(compile_cell(&node)),
            jit_cell(&node),
            jit_simd_cell(&node),
            msl_cell(&node),
            glsl_cell(&node),
            wgsl_cell(&node),
            hlsl_cell(&node),
            rust_cell(&node),
            Some(f),
            Some(p),
        ];
        let row = acc.entry(variant_of(&node)).or_default();
        for (i, c) in cells.iter().enumerate() {
            if let Some(c) = c {
                seen_feature[i] = true;
                if !row[i].contains(c) {
                    row[i].push(c);
                }
            }
        }
    }
    acc.into_iter()
        .map(|(k, v)| {
            let cols = std::array::from_fn(|i| {
                seen_feature[i].then(|| {
                    let mut s = v[i].clone();
                    s.sort_unstable();
                    s.join("/")
                })
            });
            (k, cols)
        })
        .collect()
}

fn render(variants: &[String], m: &BTreeMap<String, [Option<String>; NCOL]>) -> String {
    let mut out = String::from(
        "# SdfNode backend support\n\n\
_Generated by `tests/test_node_backend_matrix.rs` (`ALICE_SDF_WRITE_NODE_SUPPORT=1 cargo test --features jit,msl,rust,glsl,hlsl --test test_node_backend_matrix`); \
no timestamp, the file changes only when its content does._\n\n\
Every `SdfNode` variant, run through the backends whose outcome can be observed at run time, \
using the shared test corpus (`tests/common/corpus.rs`). CI fails when a cell changes and this file does not.\n\n\
| Column | `ok` | otherwise |\n|--------|------|-----------|\n\
| `eval` | the tree evaluator returns a finite distance other than `f32::MAX` | `fallback`: the unknown-variant arm |\n\
| `interval` | `eval_interval` returns a bounded enclosure over a ±2 box | `everything`: no pruning for this variant |\n\
| `compile` | `CompiledSdf::try_compile` succeeds | `err` |\n\
| `jit` | `JitCompiledSdf::compile` (scalar tree JIT) succeeds (`jit` feature) | `err` |\n\
| `jit_simd` | `JitSimdSdf::compile` of the compiled tree succeeds (`jit` feature) | `err`; `-` when the tree does not compile |\n\
| `msl` | `MslShader::transpile` succeeds (`msl` feature) | `err` |\n\
| `glsl` / `wgsl` / `hlsl` | the emitted source is not the child's source forwarded unchanged, for a node whose tree evaluator changes the child's distance (`glsl` / `gpu` / `hlsl` features; `msl` turns on `gpu`) | `pass-through` |\n\
| `rust` | `RustSource::transpile` succeeds (`rust` feature) | `err` |\n\
| `ffi` | a constructor `alice_sdf_<name>` exists in `src/ffi/` (matched by name) | `missing` |\n\
| `python` | a constructor `fn <name>(` exists in `src/python/` (matched by name) | `missing` |\n\n\
GLSL, WGSL, HLSL and BlinkScript share one dispatch (`transpile_node_inner` in \
`src/compiled/transpiler_common.rs`) whose `match` has no wildcard arm, so rustc rejects a variant without an arm \
(`transpiler_dispatch_has_no_wildcard_arm` keeps it that way); the three shader columns check that the arm does \
more than forward the child (BlinkScript is the HLSL body). `ProjectiveTransform` is measured with the corpus \
identity and a non-identity matrix.\n\n\
| Variant | eval | interval | compile | jit | jit_simd | msl | glsl | wgsl | hlsl | rust | ffi | python |\n\
|---------|------|----------|---------|-----|----------|-----|------|------|------|------|-----|--------|\n",
    );
    for v in variants {
        let row = m.get(v).expect("every variant is measured");
        let cells: Vec<String> = row
            .iter()
            .map(|c| c.clone().unwrap_or_else(|| "?".into()))
            .collect();
        out += &format!("| `{v}` | {} |\n", cells.join(" | "));
    }
    out
}

/// Ledger rows: variant -> cells.
fn parse_ledger(text: &str) -> BTreeMap<String, Vec<String>> {
    let mut out = BTreeMap::new();
    for line in text.lines() {
        let Some(rest) = line.strip_prefix("| `") else {
            continue;
        };
        let Some((name, tail)) = rest.split_once("` |") else {
            continue;
        };
        if !name.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
            continue; // the column legend rows start with a lower-case name
        }
        let cells: Vec<String> = tail
            .split('|')
            .map(|c| c.trim().to_string())
            .filter(|c| !c.is_empty())
            .collect();
        out.insert(name.to_string(), cells);
    }
    out
}

#[test]
fn every_variant_reaches_the_backends_the_ledger_records() {
    let variants = enum_variants();
    assert!(
        variants.len() >= 100,
        "read only {} variants from src/types/mod.rs",
        variants.len()
    );
    let m = measure();

    let missing: Vec<&String> = variants.iter().filter(|v| !m.contains_key(*v)).collect();
    assert!(
        missing.is_empty(),
        "SdfNode variants with no entry in tests/common/corpus.rs (add one): {missing:?}"
    );
    let unknown: Vec<&String> = m.keys().filter(|k| !variants.contains(k)).collect();
    assert!(
        unknown.is_empty(),
        "corpus top-level variants not in the enum: {unknown:?}"
    );

    let path = format!("{}/{LEDGER}", env!("CARGO_MANIFEST_DIR"));
    if std::env::var_os("ALICE_SDF_WRITE_NODE_SUPPORT").is_some() {
        assert!(
            m.values().all(|r| r.iter().all(Option::is_some)),
            "write the ledger with every feature column on: --features jit,msl,rust,glsl,hlsl"
        );
        std::fs::write(&path, render(&variants, &m)).expect("write ledger");
        return;
    }

    let ledger =
        parse_ledger(&std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{LEDGER}: {e}")));
    let ledger_names: Vec<&String> = ledger.keys().collect();
    let mut sorted_variants: Vec<&String> = variants.iter().collect();
    sorted_variants.sort();
    assert_eq!(
        ledger_names, sorted_variants,
        "{LEDGER} does not list exactly the SdfNode variants"
    );

    let mut diffs = Vec::new();
    let mut compared = 0usize;
    for v in &variants {
        let row = &m[v];
        let want = &ledger[v];
        assert_eq!(
            want.len(),
            COLUMNS.len(),
            "{LEDGER}: row `{v}` has {} cells",
            want.len()
        );
        for (i, col) in COLUMNS.iter().enumerate() {
            if let Some(got) = &row[i] {
                compared += 1;
                if got != &want[i] {
                    diffs.push(format!("{v}.{col}: measured `{got}`, ledger `{}`", want[i]));
                }
            }
        }
    }
    assert!(
        compared >= variants.len() * 3,
        "compared only {compared} cells"
    );
    assert!(
        diffs.is_empty(),
        "backend support changed ({} cells); if intended, regenerate {LEDGER} \
         (ALICE_SDF_WRITE_NODE_SUPPORT=1 cargo test --features jit,msl,rust,glsl,hlsl --test test_node_backend_matrix):\n  {}",
        diffs.len(),
        diffs.join("\n  ")
    );
}

#[test]
fn the_enum_reader_finds_the_variants_it_should() {
    let v = enum_variants();
    for name in [
        "Sphere",
        "Box3d",
        "MetricBall",
        "MetricBlend",
        "Union",
        "Translate",
        "Twist",
        "WithMaterial",
        "Terrain",
    ] {
        assert!(
            v.contains(&name.to_string()),
            "{name} not read from src/types/mod.rs"
        );
    }
    // field names (indented deeper) are not variants
    assert!(!v
        .iter()
        .any(|n| n == "Radius" || n.chars().next().is_some_and(char::is_lowercase)));
}

#[test]
fn constructor_names_follow_the_binding_convention() {
    assert_eq!(constructor_name("Circle2D"), "circle_2d");
    assert_eq!(constructor_name("RoundedRect2D"), "rounded_rect_2d");
    assert_eq!(
        constructor_name("ExpSmoothSubtraction"),
        "exp_smooth_subtract"
    );
    assert_eq!(constructor_name("Box3d"), "box3d");
    assert_eq!(constructor_name("IWP"), "iwp");
    assert_eq!(constructor_name("FischerKochS"), "fischer_koch_s");
    assert!(has_fn(
        "pub extern \"C\" fn alice_sdf_box(x: f32)",
        "alice_sdf_box"
    ));
    assert!(!has_fn(
        "pub extern \"C\" fn alice_sdf_box_frame(x: f32)",
        "alice_sdf_box"
    ));
    assert!(!has_fn("fn my_alice_sdf_box(", "alice_sdf_box"));
}

/// The body of the first `match node {` after `fn <name>`, with comments removed.
fn match_body(src: &str, fn_name: &str) -> String {
    let src = src.replace("\r\n", "\n");
    let code: String = src
        .lines()
        .map(|l| l.split("//").next().unwrap_or(""))
        .collect::<Vec<_>>()
        .join("\n");
    let f = code
        .find(&format!("fn {fn_name}"))
        .unwrap_or_else(|| panic!("fn {fn_name} not found"));
    let m = f + code[f..]
        .find("match node {")
        .unwrap_or_else(|| panic!("no `match node` in {fn_name}"));
    let start = m + "match node {".len();
    let mut depth = 1;
    for (i, c) in code[start..].char_indices() {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return code[start..start + i].to_string();
                }
            }
            _ => {}
        }
    }
    panic!("unbalanced match in {fn_name}");
}

/// Whether a `match` body has a `_ =>` arm at its top level.
fn has_top_level_wildcard(body: &str) -> bool {
    let mut depth = 0i32;
    let mut top = String::new();
    for c in body.chars() {
        match c {
            '{' | '(' | '[' => depth += 1,
            '}' | ')' | ']' => depth -= 1,
            _ if depth == 0 => top.push(c),
            _ => {}
        }
    }
    // an arm may carry attributes (`#[allow(..)] _ => ..`): their brackets are
    // already dropped above, so skip the `#` that is left, and a leading `|`
    top.split([',', '\n']).any(|arm| {
        let a = arm.trim_start_matches(|c: char| c.is_whitespace() || c == '#' || c == '|');
        a.starts_with("_ =>") || a.starts_with("_ if ") || a == "_"
    })
}

#[test]
fn transpiler_dispatch_has_no_wildcard_arm() {
    let body = match_body(
        include_str!("../src/compiled/transpiler_common.rs"),
        "transpile_node_inner",
    );
    assert!(
        body.matches("SdfNode::").count() >= 100,
        "transpile_node_inner no longer dispatches on SdfNode"
    );
    assert!(
        !has_top_level_wildcard(&body),
        "transpile_node_inner gained a `_ =>` arm: a new SdfNode variant would compile without a shader law"
    );
    // the scanner itself: a wildcard at the top level is found, one inside an arm is not
    assert!(has_top_level_wildcard(
        "SdfNode::A { .. } => 1,\n    _ => 0,"
    ));
    assert!(!has_top_level_wildcard(
        "SdfNode::A { x } => match x { _ => 0 },"
    ));
    assert!(has_top_level_wildcard(
        "SdfNode::A { .. } => 1,\n    #[allow(unreachable_patterns)] _ => 0,"
    ));
    assert!(has_top_level_wildcard(
        "SdfNode::A { .. } => 1,\n    _ if false => 0,"
    ));
}

#[test]
fn the_source_readers_accept_crlf_line_endings() {
    // a Windows checkout with core.autocrlf=true hands include_str! CRLF text
    let lf = include_str!("../src/types/mod.rs");
    let crlf = lf.replace("\r\n", "\n").replace('\n', "\r\n");
    assert_eq!(enum_variants_in(&crlf), enum_variants_in(lf));
    let common = include_str!("../src/compiled/transpiler_common.rs");
    let common_crlf = common.replace("\r\n", "\n").replace('\n', "\r\n");
    assert_eq!(
        match_body(&common_crlf, "transpile_node_inner").len(),
        match_body(common, "transpile_node_inner").len()
    );
}

/// `SdfCategory::count()` is a hand-written table; count the categories of one
/// node per variant so a new variant cannot leave it stale (4.0.0 added
/// `MetricBall` / `MetricBlend` and the table was not updated).
#[test]
fn category_counts_match_one_node_per_variant() {
    let variants = enum_variants();
    let mut seen = std::collections::BTreeMap::new();
    for (_, node) in entries() {
        seen.entry(variant_of(&node))
            .or_insert_with(|| node.category());
    }
    assert_eq!(
        seen.len(),
        variants.len(),
        "corpus does not cover every variant, the counts below would be partial"
    );
    for cat in [
        SdfCategory::Primitive,
        SdfCategory::Operation,
        SdfCategory::Transform,
        SdfCategory::Modifier,
    ] {
        let measured = seen.values().filter(|c| **c == cat).count() as u32;
        assert_eq!(cat.count(), measured, "SdfCategory::{cat:?}::count()");
    }
    assert_eq!(SdfCategory::total() as usize, variants.len());
}

/// Variants whose tree evaluator returns the child's distance by definition, so
/// forwarding the child is the faithful emit.
const DISTANCE_TRANSPARENT: [&str; 2] = ["Animated", "WithMaterial"];

/// Every one-child variant except the distance-transparent ones has an entry
/// that changes the distance; otherwise the transpiler columns would compare
/// an identity with an identity (the corpus `projective_transform` alone read
/// `ok` while all three transpilers forwarded the child).
#[test]
fn every_one_child_variant_has_an_entry_that_changes_the_distance() {
    let mut one_child: BTreeMap<String, bool> = BTreeMap::new();
    for (_name, node) in entries() {
        if let Some(child) = common::corpus::single_child(&node) {
            *one_child.entry(variant_of(&node)).or_default() |= changes_distance(&node, &child);
        }
    }
    // one entry per `child: Arc<Self>` field of the enum
    let declared =
        std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/types/mod.rs"))
            .expect("read src/types/mod.rs")
            .matches("child: Arc<Self>")
            .count();
    assert!(
        declared >= 30,
        "read only {declared} one-child variants from src/types/mod.rs"
    );
    assert_eq!(
        one_child.len(),
        declared,
        "the serde child reader found {} one-child variants, the enum declares {declared}: {:?}",
        one_child.len(),
        one_child.keys().collect::<Vec<_>>()
    );
    let trivial: Vec<&String> = one_child
        .iter()
        .filter(|(v, changes)| !**changes && !DISTANCE_TRANSPARENT.contains(&v.as_str()))
        .map(|(v, _)| v)
        .collect();
    assert!(
        trivial.is_empty(),
        "one-child variants whose every entry leaves the distance unchanged \
         (add a non-trivial entry): {trivial:?}"
    );
    for v in DISTANCE_TRANSPARENT {
        assert_eq!(
            one_child.get(v),
            Some(&false),
            "{v} is not distance-transparent"
        );
    }
}

/// No transpiler forwards the child of a node that changes the distance while
/// `shader_unsupported_nodes` says the node is supported.
#[cfg(all(feature = "glsl", feature = "gpu", feature = "hlsl"))]
#[test]
fn no_transpiler_silently_forwards_a_child() {
    use alice_sdf::compiled::shader_unsupported_nodes;
    type Emit = fn(&SdfNode) -> String;
    let langs: [(&str, Emit); 3] = [
        ("glsl", glsl_emit),
        ("wgsl", wgsl_emit),
        ("hlsl", hlsl_emit),
    ];
    let mut lies = Vec::new();
    let mut checked = 0usize;
    for (name, node) in entries() {
        let Some(child) = common::corpus::single_child(&node) else {
            continue;
        };
        if !changes_distance(&node, &child) {
            continue;
        }
        checked += 1;
        for (lang, emit) in langs {
            if emit(&node) == emit(&child) && shader_unsupported_nodes(&node).is_empty() {
                lies.push(format!("{name}: {lang} forwards the child unchanged"));
            }
        }
    }
    assert!(
        checked >= 40,
        "only {checked} one-child entries change the distance"
    );
    assert!(
        lies.is_empty(),
        "transpilers forward the child of a node they report as supported:\n  {}",
        lies.join("\n  ")
    );
}