goldy 0.2.0

Fondaco Machine GPU runtime for Rust (Vulkan, DX12, Metal)
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
//! High-level Slang compiler API.
//!
//! Provides a safe, ergonomic interface for compiling Slang shaders.

use anyhow::{Context, Result};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::ptr;
use std::sync::{Arc, Mutex};

/// Serializes Slang global-session create/destroy and compilation.
///
/// Parallel `Instance::new` / `release_idle_shader_compiler` paths can otherwise
/// call `create_global_session` and `global_session_release` concurrently and SIGSEGV.
static SLANG_PROCESS_LOCK: Mutex<()> = Mutex::new(());

use super::ffi::*;
use super::loader::SlangLibrary;
use super::virtual_main::effective_slang_source_for_compile;
use crate::types::{OptimizationLevel, ResourceCategory};
use crate::{goldy_event, goldy_span};

/// Returns `true` when layout validation is enabled.
///
/// This is on when:
/// - `GOLDY_VALIDATE_LAYOUTS` is `1`, `true`, or `yes` (unchanged), or
/// - `GOLDY_VALIDATION` lists `layout` / `layouts` / `all` (see `validation_env`).
///
/// Note: `GOLDY_VALIDATION=1|true|yes` enables **GPU API** validation only, not layout checks.
///
/// Controls both struct layout checks (at compile time) and buffer element-stride
/// checks (at dispatch time). Reads the environment on every call so that tests
/// can toggle the flag without restarting the process.
pub fn layout_validation_enabled() -> bool {
    crate::validation_env::layout_validation_enabled()
}

// ============================================================================
// Reflection data structures
// ============================================================================

/// Kind of resource in a parameter block field
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ResourceKind {
    /// A buffer (StructuredBuffer, RWStructuredBuffer, etc.)
    Buffer,
    /// A mutable buffer (RWStructuredBuffer, RWByteAddressBuffer)
    MutableBuffer,
    /// A texture (Texture2D, etc.)
    Texture,
    /// A mutable texture (RWTexture2D)
    MutableTexture,
    /// A sampler state
    Sampler,
    /// A constant buffer / uniform block
    ConstantBuffer,
    /// A nested parameter block
    ParameterBlock,
    /// Other/unknown
    Other,
}

/// Layout information for a single field within a ParameterBlock
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FieldLayout {
    /// Name of the field
    pub name: String,
    /// Offset in bytes from the start of the containing struct
    pub offset: usize,
    /// Size in bytes
    pub size: usize,
    /// What kind of resource this field represents
    pub resource_kind: ResourceKind,
    /// Type name (e.g., `StructuredBuffer<Particle>`)
    pub type_name: String,
}

/// Layout information for a ParameterBlock
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ParameterBlockLayout {
    /// Name of the parameter (from shader)
    pub name: String,
    /// Binding slot (for Metal: buffer index)
    pub binding_slot: u32,
    /// Binding space/set
    pub binding_space: u32,
    /// Total size of the argument buffer in bytes
    pub size: usize,
    /// Alignment requirement
    pub alignment: usize,
    /// Fields within the parameter block
    pub fields: Vec<FieldLayout>,
}

/// Complete reflection information for a compiled shader
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ShaderReflection {
    /// All parameter blocks found in the shader
    pub parameter_blocks: Vec<ParameterBlockLayout>,
    /// Per push-constant slot, the [`ResourceCategory`]
    /// the shader expects. Populated from `[goldy_*]` entry-point analysis at compile time.
    /// Used by backend validation when `BindResourcesTyped` is used to catch category
    /// mismatches against the shader's reflected expectations.
    pub push_constant_categories: Vec<Option<crate::types::ResourceCategory>>,
    /// Per push-constant slot, the DX12 bindless view kind the shader expects
    /// (`Scattered<T>` → UAV, `BufRO<T>` → SRV). Empty when source has no
    /// `[goldy_*]` annotations. Re-derived from source at compile time (not serialized).
    #[cfg(all(feature = "dx12", target_os = "windows"))]
    #[serde(skip)]
    pub(crate) push_constant_slot_kinds: Vec<Option<crate::types::BindlessSlotKind>>,
    /// Per push-constant slot, the expected element stride (bytes) of the bound
    /// buffer. Populated from `[goldy_*]` source analysis + Slang reflection at
    /// compile time.  At dispatch time, backends compare each bound buffer's
    /// `element_stride` against this value when layout validation is enabled
    /// (`GOLDY_VALIDATE_LAYOUTS`, `GOLDY_VALIDATION=layout`).
    #[serde(default)]
    pub binding_element_strides: Vec<Option<u32>>,
}

/// Byte layout of a Slang `struct` under uniform / constant-buffer rules (`SlangLayoutRules::Default`).
///
/// Used with [`StructLayout::validate`] to compare against a Rust `#[repr(C)]` type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructLayout {
    /// Reflected type name (as requested, e.g. `SceneUniforms`).
    pub name: String,
    /// Total size in bytes.
    pub size: usize,
    /// Alignment in bytes (Slang-reported for the uniform category).
    pub alignment: usize,
    pub fields: Vec<StructFieldLayout>,
}

/// One field in a [`StructLayout`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructFieldLayout {
    pub name: String,
    /// Byte offset from the start of the struct.
    pub offset: usize,
    /// Size in bytes.
    pub size: usize,
    /// Slang type name (e.g. `float4x4`, `float2`).
    pub type_name: String,
}

impl StructLayout {
    /// Compare this Slang layout against Rust `size_of` / `offset_of!` / per-field `size_of`.
    ///
    /// Validation rules:
    /// - Every field declared in the shader must exist in the Rust struct with a matching name,
    ///   byte offset, and size. A missing or mismatched shader field is a hard error.
    /// - The Rust struct must be large enough to cover all shader-declared data (i.e. ≥ the last
    ///   shader field's end byte). Tail padding added by constant-buffer alignment rules is *not*
    ///   required to be present in the Rust struct.
    /// - Extra Rust fields that have no counterpart in the shader are allowed (they are padding or
    ///   bookkeeping). A warning is emitted for non-`_`-prefixed extras so genuine "forgot to add
    ///   this field to the shader" mistakes are visible. Prefix with `_` to silence the warning.
    pub fn validate(&self, rust_size: usize, rust_fields: &[(&str, usize, usize)]) -> Result<()> {
        let mut errors: Vec<String> = Vec::new();
        let mut warnings: Vec<String> = Vec::new();

        // Data extent: the last byte actually declared by the shader (excludes CB tail padding).
        let slang_data_extent = self.fields.iter().map(|f| f.offset + f.size).max().unwrap_or(0);

        if rust_size < slang_data_extent {
            errors.push(format!(
                "Rust struct ({rust_size} bytes) is smaller than the shader's data extent \
                 ({slang_data_extent} bytes); all shader fields must fit inside the Rust struct"
            ));
        }

        // Direction 1: every Slang field must exist in Rust with matching offset and size.
        for sf in &self.fields {
            match rust_fields.iter().find(|&&(name, _, _)| name == sf.name) {
                Some(&(_, rust_offset, rust_size_field)) => {
                    if sf.offset != rust_offset {
                        errors.push(format!(
                            "field `{}`: offset Slang {} vs Rust {}",
                            sf.name, sf.offset, rust_offset
                        ));
                    }
                    if sf.size != rust_size_field {
                        errors.push(format!(
                            "field `{}`: size Slang {} vs Rust {}",
                            sf.name, sf.size, rust_size_field
                        ));
                    }
                }
                None => {
                    errors.push(format!(
                        "field `{}` is declared in the shader but missing from the Rust struct",
                        sf.name
                    ));
                }
            }
        }

        // Direction 2: Rust fields absent from the shader — warn for non-`_`-prefixed ones.
        for &(name, _, _) in rust_fields {
            if !self.fields.iter().any(|sf| sf.name == name) && !name.starts_with('_') {
                warnings.push(format!(
                    "field `{name}` is in the Rust struct but not in the shader \
                     (prefix with `_` to suppress this warning)"
                ));
            }
        }

        if !warnings.is_empty() {
            tracing::warn!("Layout check for `{}`: {}", self.name, warnings.join("; "));
        }

        if errors.is_empty() {
            Ok(())
        } else {
            anyhow::bail!("Struct layout mismatch for `{}`:\n{}", self.name, errors.join("\n"));
        }
    }
}

/// Opt-in Rust vs Slang struct layout checks run during the same compile as GPU codegen.
///
/// Pass a slice to [`ShaderModule::from_slang_with_options`](crate::ShaderModule::from_slang_with_options).
/// Checks only run when `GOLDY_VALIDATE_LAYOUTS=1` is set.
#[derive(Debug, Clone, Copy)]
pub struct LayoutCheck<'a> {
    pub type_name: &'a str,
    pub rust_size: usize,
    pub rust_fields: &'a [(&'a str, usize, usize)],
}

/// Stored on backend shader state for deferred per-stage compilation.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OwnedLayoutCheck {
    pub type_name: String,
    pub rust_size: usize,
    pub rust_fields: Vec<(String, usize, usize)>,
}

impl OwnedLayoutCheck {
    pub fn from_layout_check(c: &LayoutCheck<'_>) -> Self {
        Self {
            type_name: c.type_name.to_string(),
            rust_size: c.rust_size,
            rust_fields: c
                .rust_fields
                .iter()
                .map(|(n, o, s)| ((*n).to_string(), *o, *s))
                .collect(),
        }
    }
}

/// Compiled shader output with optional reflection data.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CompiledShaderWithReflection {
    /// The compiled shader
    pub shader: CompiledShader,
    /// Reflection data (if requested)
    pub reflection: ShaderReflection,
}

/// Shader compilation target.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ShaderTarget {
    /// SPIR-V bytecode for Vulkan
    Spirv,
    /// DXIL bytecode for DirectX 12 (binary, SM 6.6 for bindless)
    Dxil,
    /// Metal Shading Language
    Metal,
    /// WebGPU Shading Language
    Wgsl,
    /// CUDA PTX (Slang → CUDA C++ → NVRTC)
    Ptx,
}

impl ShaderTarget {
    fn to_slang_target(self) -> SlangCompileTarget {
        match self {
            ShaderTarget::Spirv => SlangCompileTarget::Spirv,
            ShaderTarget::Dxil => SlangCompileTarget::Dxil,
            ShaderTarget::Metal => SlangCompileTarget::Metal,
            ShaderTarget::Wgsl => SlangCompileTarget::Wgsl,
            ShaderTarget::Ptx => SlangCompileTarget::Ptx,
        }
    }

    /// Returns true if this target produces binary bytecode (not text).
    pub fn is_binary(self) -> bool {
        matches!(self, ShaderTarget::Spirv | ShaderTarget::Dxil)
    }
}

/// Compiled shader output.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CompiledShader {
    /// The compiled bytecode or source code
    pub data: Vec<u8>,
    /// The target format
    pub target: ShaderTarget,
}

impl CompiledShader {
    /// Get the data as a string (for text-based targets like Metal).
    pub fn as_str(&self) -> Option<&str> {
        match self.target {
            ShaderTarget::Metal | ShaderTarget::Wgsl | ShaderTarget::Ptx => std::str::from_utf8(&self.data).ok(),
            ShaderTarget::Spirv | ShaderTarget::Dxil => None,
        }
    }

    /// Get the data as SPIR-V words (for Vulkan).
    pub fn as_spirv(&self) -> Option<&[u32]> {
        if self.target == ShaderTarget::Spirv && self.data.len().is_multiple_of(4) {
            Some(bytemuck::cast_slice(&self.data))
        } else {
            None
        }
    }

    /// Get the data as DXIL bytecode (for DirectX 12).
    pub fn as_dxil(&self) -> Option<&[u8]> {
        if self.target == ShaderTarget::Dxil {
            Some(&self.data)
        } else {
            None
        }
    }
}

/// Return the byte stride of a Slang built-in scalar/vector/matrix type, or
/// `None` for user-defined structs that require Slang reflection.
pub fn builtin_type_stride(name: &str) -> Option<u32> {
    match name {
        "uint" | "int" | "float" | "bool" | "dword" => Some(4),
        "half" | "float16_t" => Some(2),
        "double" | "uint64_t" | "int64_t" => Some(8),
        "uint2" | "int2" | "float2" => Some(8),
        "half2" => Some(4),
        "uint3" | "int3" | "float3" => Some(12),
        "half3" => Some(6),
        "uint4" | "int4" | "float4" => Some(16),
        "half4" => Some(8),
        "float2x2" => Some(16),
        "float3x3" => Some(36),
        "float4x4" => Some(64),
        "DispatchShape" => Some(12),
        _ => None,
    }
}

/// Slang shader compiler.
///
/// Thread-safe wrapper around the Slang compilation API.
pub struct SlangCompiler {
    library: Arc<SlangLibrary>,
    global_session: *mut IGlobalSession,
    shader_disk_cache: std::sync::Mutex<crate::shader_cache::ShaderBytecodeDiskCache>,
}

// SlangCompiler is Send + Sync because each compilation creates its own request
unsafe impl Send for SlangCompiler {}
unsafe impl Sync for SlangCompiler {}

impl SlangCompiler {
    /// Create a new Slang compiler instance.
    pub fn new() -> Result<Self> {
        let _span = goldy_span!("slang.compiler.init").entered();

        let _guard = SLANG_PROCESS_LOCK.lock().unwrap();

        let library = Arc::new(SlangLibrary::load()?);

        // Create global session using the new COM API
        let mut global_session: *mut IGlobalSession = ptr::null_mut();
        let global_desc = SlangGlobalSessionDesc::default();
        tracing::debug!(
            "Creating global session with desc size: {}",
            std::mem::size_of::<SlangGlobalSessionDesc>()
        );
        let result = unsafe { (library.create_global_session)(&global_desc, &mut global_session) };

        if !slang_succeeded(result) || global_session.is_null() {
            anyhow::bail!(
                "Failed to create Slang global session (result={}, ptr={:?})",
                result,
                global_session
            );
        }
        tracing::debug!("Global session created: {:?}", global_session);

        goldy_event!("slang.session.create", success = true);
        tracing::info!("Slang compiler initialized");

        Ok(Self {
            library,
            global_session,
            shader_disk_cache: std::sync::Mutex::new(crate::shader_cache::ShaderBytecodeDiskCache::new_load_or_empty()),
        })
    }

    /// Compile with reflection data.
    ///
    /// Returns both the compiled shader and reflection information about
    /// ParameterBlocks, which is needed to properly set up argument buffers.
    ///
    /// Target-specific preprocessor defines (`__SPIRV__`, `__DX12__`, `__METAL__`) are applied
    /// automatically (same as [`Self::compile_bindless_with_reflection_and_defines`] with no
    /// extra defines).
    pub fn compile_bindless_with_reflection(
        &self,
        source: &str,
        target: ShaderTarget,
        entry_points: &[(&str, SlangStage)],
        search_paths: &[&str],
    ) -> Result<CompiledShaderWithReflection> {
        self.compile_bindless_with_reflection_and_defines(
            source,
            target,
            entry_points,
            search_paths,
            &[],
            &[],
            OptimizationLevel::Default,
        )
    }

    /// Like [`Self::compile_bindless_with_reflection`] but with extra preprocessor defines.
    ///
    /// Extra defines are merged with target-specific defines (e.g. `__SPIRV__`, `__DX12__`).
    /// Use for shader variants like `msaa`, `msaa8`, `msaa16`.
    #[allow(clippy::too_many_arguments)] // layout_checks + defines + paths are all required at call sites
    pub fn compile_bindless_with_reflection_and_defines(
        &self,
        source: &str,
        target: ShaderTarget,
        entry_points: &[(&str, SlangStage)],
        search_paths: &[&str],
        extra_defines: &[(&str, &str)],
        layout_checks: &[OwnedLayoutCheck],
        optimization_level: OptimizationLevel,
    ) -> Result<CompiledShaderWithReflection> {
        let mut defines = Self::bindless_defines_for_target(target);
        defines.extend_from_slice(extra_defines);
        self.compile_with_reflection(
            source,
            target,
            entry_points,
            search_paths,
            &defines,
            layout_checks,
            optimization_level,
        )
    }

    /// Get preprocessor defines for the given target.
    fn bindless_defines_for_target(target: ShaderTarget) -> Vec<(&'static str, &'static str)> {
        match target {
            ShaderTarget::Spirv => vec![("__SPIRV__", "1")],
            ShaderTarget::Dxil => vec![("__DX12__", "1")],
            ShaderTarget::Metal => vec![("__METAL__", "1")],
            ShaderTarget::Wgsl => vec![("__WGSL__", "1")],
            ShaderTarget::Ptx => vec![("__CUDA__", "1")],
        }
    }

    /// Shared session + compile path; invokes `f` with the live compile request after `spCompile` succeeds.
    ///
    /// `source` must be the effective Slang translation-unit text (after
    /// [`super::virtual_main::effective_slang_source_for_compile`] when applicable). Virtual-main
    /// rewriting is not applied here so it runs once per logical compile.
    #[allow(clippy::too_many_arguments)] // mirrors public compile entry points
    fn with_compiled_request<R>(
        &self,
        source: &str,
        target: ShaderTarget,
        entry_points: &[(&str, SlangStage)],
        search_paths: &[&str],
        defines: &[(&str, &str)],
        optimization_level: OptimizationLevel,
        f: impl FnOnce(&Self, *mut SlangCompileRequest, i32) -> Result<R>,
    ) -> Result<R> {
        let _guard = SLANG_PROCESS_LOCK.lock().unwrap();

        // Create session with session-level preprocessor macros.
        let define_names: Vec<CString> = defines.iter().map(|(k, _)| CString::new(*k).unwrap()).collect();
        let define_values: Vec<CString> = defines.iter().map(|(_, v)| CString::new(*v).unwrap()).collect();
        let macro_descs: Vec<PreprocessorMacroDesc> = define_names
            .iter()
            .zip(define_values.iter())
            .map(|(name, value)| PreprocessorMacroDesc {
                name: name.as_ptr(),
                value: value.as_ptr(),
            })
            .collect();

        let search_path_cstrings: Vec<CString> = search_paths.iter().map(|p| CString::new(*p).unwrap()).collect();
        let search_path_ptrs: Vec<*const c_char> = search_path_cstrings.iter().map(|s| s.as_ptr()).collect();

        let mut session_desc = SessionDesc::default();
        if !search_path_ptrs.is_empty() {
            session_desc.search_paths = search_path_ptrs.as_ptr();
            session_desc.search_path_count = search_path_ptrs.len() as i64;
        }
        if !macro_descs.is_empty() {
            session_desc.preprocessor_macros = macro_descs.as_ptr();
            session_desc.preprocessor_macro_count = macro_descs.len() as i64;
        }

        tracing::debug!(
            "Creating session with {} macros, SessionDesc size: {}",
            macro_descs.len(),
            std::mem::size_of::<SessionDesc>()
        );
        let mut session: *mut ISession = ptr::null_mut();
        let result = unsafe { global_session_create_session(self.global_session, &session_desc, &mut session) };
        if !slang_succeeded(result) || session.is_null() {
            anyhow::bail!(
                "Failed to create Slang session with preprocessor defines (result={}, ptr={:?})",
                result,
                session
            );
        }
        tracing::debug!("Session with defines created: {:?}", session);

        let _session_guard = scopeguard::guard(session, |s| {
            unsafe { session_release(s) };
        });

        let mut request: *mut SlangCompileRequest = ptr::null_mut();
        let result = unsafe { session_create_compile_request(session, &mut request) };
        if !slang_succeeded(result) || request.is_null() {
            anyhow::bail!(
                "Failed to create Slang compile request (result={}, ptr={:?})",
                result,
                request
            );
        }
        tracing::debug!("Compile request created: {:?}", request);

        let library = self.library.clone();
        let _guard = scopeguard::guard(request, |req| {
            unsafe { (library.destroy_compile_request)(req) };
        });

        let target_index = unsafe { (self.library.add_code_gen_target)(request, target.to_slang_target() as i32) };
        if target_index < 0 {
            anyhow::bail!("Failed to add code generation target");
        }

        if target == ShaderTarget::Dxil {
            let profile_name = CString::new("sm_6_6").unwrap();
            let profile_id = unsafe { global_session_find_profile(self.global_session, profile_name.as_ptr()) };
            if profile_id > 0 {
                unsafe {
                    (self.library.set_target_profile)(request, target_index, profile_id);
                }
                tracing::debug!("Set DXIL target profile to sm_6_6 (id={})", profile_id);
            } else {
                tracing::warn!("Could not find sm_6_6 profile, using default");
            }
            unsafe {
                (self.library.set_target_floating_point_mode)(request, target_index, SLANG_FLOATING_POINT_MODE_PRECISE);
            }
        }

        let unit_name = CString::new("shader").unwrap();
        let translation_unit = unsafe {
            (self.library.add_translation_unit)(request, SlangSourceLanguage::Slang as i32, unit_name.as_ptr())
        };
        if translation_unit < 0 {
            anyhow::bail!("Failed to add translation unit");
        }

        let source_path = CString::new("shader.slang").unwrap();
        let source_cstr = CString::new(source).context("Source contains null bytes")?;
        unsafe {
            (self.library.add_translation_unit_source_string)(
                request,
                translation_unit,
                source_path.as_ptr(),
                source_cstr.as_ptr(),
            );
        }

        for (name, stage) in entry_points {
            let name_cstr = CString::new(*name).context("Entry point name contains null bytes")?;
            let entry_index =
                unsafe { (self.library.add_entry_point)(request, translation_unit, name_cstr.as_ptr(), *stage as i32) };
            if entry_index < 0 {
                anyhow::bail!("Failed to add entry point: {}", name);
            }
        }

        if optimization_level != OptimizationLevel::Default {
            let ffi_level = match optimization_level {
                OptimizationLevel::None => SLANG_OPTIMIZATION_LEVEL_NONE,
                OptimizationLevel::Default => unreachable!(),
                OptimizationLevel::High => SLANG_OPTIMIZATION_LEVEL_HIGH,
                OptimizationLevel::Maximal => SLANG_OPTIMIZATION_LEVEL_MAXIMAL,
            };
            unsafe { (self.library.set_optimization_level)(request, ffi_level) };
            tracing::info!("Slang optimization level set to {:?}", optimization_level);
        }

        let result = unsafe { (self.library.compile)(request) };
        if !slang_succeeded(result) {
            let diag_ptr = unsafe { (self.library.get_diagnostic_output)(request) };
            let diagnostic = if !diag_ptr.is_null() {
                unsafe { CStr::from_ptr(diag_ptr) }.to_string_lossy().into_owned()
            } else {
                "Unknown compilation error".to_string()
            };
            anyhow::bail!("Slang compilation failed:\n{}", diagnostic);
        }

        f(self, request, target_index)
    }

    /// Compile with reflection data.
    ///
    /// This performs compilation and extracts reflection information about
    /// all parameters, especially ParameterBlocks for bindless rendering.
    ///
    /// When `layout_checks` is non-empty, each struct is reflected from the same compile request
    /// and validated before returning (see [`OwnedLayoutCheck`]).
    #[allow(clippy::too_many_arguments)] // Slang compile inputs are naturally wide
    pub fn compile_with_reflection(
        &self,
        source: &str,
        target: ShaderTarget,
        entry_points: &[(&str, SlangStage)],
        search_paths: &[&str],
        defines: &[(&str, &str)],
        layout_checks: &[OwnedLayoutCheck],
        optimization_level: OptimizationLevel,
    ) -> Result<CompiledShaderWithReflection> {
        // Hash the same string Slang compiles (post virtual-main transform). This runs on cache
        // hits too; a micro-optimization could cache keys per `(Arc<str>, …)` if needed.
        let effective = effective_slang_source_for_compile(source);
        let cache_key = crate::shader_cache::compile_cache_key(
            effective.as_ref(),
            target,
            entry_points,
            search_paths,
            defines,
            layout_checks,
            optimization_level,
        );

        {
            let mut disk = self.shader_disk_cache.lock().unwrap_or_else(|p| p.into_inner());
            if let Some(hit) = disk.get(cache_key) {
                return hit.with_context(|| "decode shader disk cache");
            }
        }

        let binding_type_names = super::virtual_main::extract_binding_element_type_names(source);
        let binding_categories = super::virtual_main::extract_push_constant_categories(source);

        let out = self.with_compiled_request(
            effective.as_ref(),
            target,
            entry_points,
            search_paths,
            defines,
            optimization_level,
            |slf, request, target_index| {
                let mut blob: *mut ISlangBlob = ptr::null_mut();
                let result = unsafe { (slf.library.get_entry_point_code_blob)(request, 0, target_index, &mut blob) };

                if !slang_succeeded(result) || blob.is_null() {
                    anyhow::bail!("Failed to get compiled shader code");
                }

                let (data_ptr, data_size) = unsafe { blob_get_data(blob) };
                let data = unsafe { std::slice::from_raw_parts(data_ptr, data_size) }.to_vec();
                unsafe { blob_release(blob) };

                let mut reflection = slf.extract_reflection(request)?;

                if !layout_checks.is_empty() {
                    slf.validate_owned_layout_checks(request, layout_checks)?;
                }

                let strides: Vec<Option<u32>> = binding_type_names
                    .iter()
                    .enumerate()
                    .map(|(i, opt_name)| {
                        let cat = binding_categories.get(i).copied().unwrap_or(None);
                        opt_name.as_deref().and_then(|name| {
                            builtin_type_stride(name).or_else(|| slf.reflect_binding_element_stride(request, name, cat))
                        })
                    })
                    .collect();
                reflection.binding_element_strides = strides;

                Ok(CompiledShaderWithReflection {
                    shader: CompiledShader { data, target },
                    reflection,
                })
            },
        )?;

        {
            let mut disk = self.shader_disk_cache.lock().unwrap_or_else(|p| p.into_inner());
            if let Err(e) = disk.insert(cache_key, &out) {
                tracing::warn!(?e, "failed to serialize shader disk cache entry");
            }
        }

        Ok(out)
    }

    fn validate_owned_layout_checks(
        &self,
        request: *mut SlangCompileRequest,
        checks: &[OwnedLayoutCheck],
    ) -> Result<()> {
        for owned in checks {
            let layout = self.reflect_named_struct_from_request(request, &owned.type_name)?;
            let field_refs: Vec<(&str, usize, usize)> =
                owned.rust_fields.iter().map(|(n, o, s)| (n.as_str(), *o, *s)).collect();
            layout.validate(owned.rust_size, &field_refs)?;
        }
        Ok(())
    }

    /// Compile `shader_source` with bindless target defines and return the uniform layout of struct `type_name`.
    ///
    /// `shader_source` must declare a vertex entry point named **`vs_main`** (same convention as typical goldy shaders).
    pub fn reflect_struct_layout(
        &self,
        shader_source: &str,
        target: ShaderTarget,
        search_paths: &[&str],
        type_name: &str,
    ) -> Result<StructLayout> {
        let defines = Self::bindless_defines_for_target(target);
        let entry_points = &[("vs_main", SlangStage::Vertex)];
        let effective = effective_slang_source_for_compile(shader_source);
        self.with_compiled_request(
            effective.as_ref(),
            target,
            entry_points,
            search_paths,
            &defines,
            OptimizationLevel::Default,
            |slf, request, _target_index| slf.reflect_named_struct_from_request(request, type_name),
        )
    }

    fn reflect_named_struct_from_request(
        &self,
        request: *mut SlangCompileRequest,
        type_name: &str,
    ) -> Result<StructLayout> {
        let reflection_ptr = unsafe { (self.library.get_reflection)(request) };
        if reflection_ptr.is_null() {
            anyhow::bail!("No Slang reflection available after compile");
        }

        let name_cstr = CString::new(type_name).context("type_name contains null bytes")?;
        let ty = unsafe { (self.library.reflection_find_type_by_name)(reflection_ptr, name_cstr.as_ptr()) };
        if ty.is_null() {
            anyhow::bail!("Slang reflection: type `{type_name}` not found");
        }

        let layout_ptr =
            unsafe { (self.library.reflection_get_type_layout)(reflection_ptr, ty, SlangLayoutRules::Default) };
        if layout_ptr.is_null() {
            anyhow::bail!("Slang reflection: failed to get layout for `{type_name}`");
        }

        self.extract_struct_layout_uniform(layout_ptr, type_name)
    }

    /// Query the per-element byte stride for a bindless slot's element type.
    ///
    /// Broadcast uniforms use std140-style `Uniform` layout. Storage-buffer element
    /// types (`Scattered<T>`, `BufRO<T>`, etc.) use `ShaderResource` layout so
    /// simple structs like `{ uint a; uint b; }` report 8 bytes, not the 16-byte
    /// uniform round-up that would mismatch GPU structured-buffer indexing.
    fn reflect_binding_element_stride(
        &self,
        request: *mut SlangCompileRequest,
        type_name: &str,
        category: Option<ResourceCategory>,
    ) -> Option<u32> {
        // Broadcast (constant-buffer) params: use struct_storage_stride which sums
        // field extents without std140 tail-padding.  reflect_type_size_with_category
        // with Uniform returns the cbuffer-padded whole-struct size (e.g. 16 for a
        // single-float struct), which does not match the buffer's element_stride set
        // at allocation time.
        if matches!(category, Some(ResourceCategory::Broadcast)) {
            return self.reflect_struct_storage_stride(request, type_name, SlangParameterCategory::Uniform);
        }

        let layout_cat = match category {
            Some(ResourceCategory::StorageImage) => SlangParameterCategory::UnorderedAccess,
            Some(ResourceCategory::Scattered)
            | Some(ResourceCategory::Texture)
            | Some(ResourceCategory::Sampler)
            | None => SlangParameterCategory::ShaderResource,
            Some(ResourceCategory::Broadcast) => unreachable!("handled above"),
        };
        self.reflect_type_size_with_category(request, type_name, layout_cat)
            .or_else(|| {
                if matches!(
                    category,
                    Some(ResourceCategory::Scattered)
                        | Some(ResourceCategory::StorageImage)
                        | Some(ResourceCategory::Texture)
                        | None
                ) {
                    self.reflect_struct_storage_stride(request, type_name, layout_cat)
                } else {
                    None
                }
            })
    }

    fn reflect_type_size_with_category(
        &self,
        request: *mut SlangCompileRequest,
        type_name: &str,
        layout_cat: SlangParameterCategory,
    ) -> Option<u32> {
        let layout_ptr = self.reflect_type_layout_ptr(request, type_name)?;
        let size = unsafe { (self.library.reflection_type_layout_get_size)(layout_ptr, layout_cat as i32) } as u32;
        if size > 0 {
            Some(size)
        } else {
            None
        }
    }

    /// Structured-buffer element size from per-field offsets (natural struct extent).
    ///
    /// Whole-type `Uniform` layout includes std140 tail padding (e.g. 8-byte struct → 16),
    /// which does not match GPU structured-buffer indexing. Field extents under `Uniform`
    /// omit that padding and match storage-buffer element sizes.
    fn reflect_struct_storage_stride(
        &self,
        request: *mut SlangCompileRequest,
        type_name: &str,
        _layout_cat: SlangParameterCategory,
    ) -> Option<u32> {
        let layout_ptr = self.reflect_type_layout_ptr(request, type_name)?;
        let field_count = unsafe { (self.library.reflection_type_layout_get_field_count)(layout_ptr) };
        if field_count == 0 {
            return None;
        }

        let field_cat = SlangParameterCategory::Uniform as i32;
        let mut extent = 0u32;
        for i in 0..field_count {
            let field_var = unsafe { (self.library.reflection_type_layout_get_field_by_index)(layout_ptr, i) };
            if field_var.is_null() {
                continue;
            }
            let field_type_layout = unsafe { (self.library.reflection_variable_layout_get_type_layout)(field_var) };
            if field_type_layout.is_null() {
                continue;
            }
            let offset = unsafe { (self.library.reflection_variable_layout_get_offset)(field_var, field_cat) } as u32;
            let field_size =
                unsafe { (self.library.reflection_type_layout_get_size)(field_type_layout, field_cat) } as u32;
            let field_extent = offset.saturating_add(field_size.max(1));
            extent = extent.max(field_extent);
        }

        if extent > 0 {
            Some(extent)
        } else {
            None
        }
    }

    fn reflect_type_layout_ptr(
        &self,
        request: *mut SlangCompileRequest,
        type_name: &str,
    ) -> Option<*mut SlangReflectionTypeLayout> {
        let reflection_ptr = unsafe { (self.library.get_reflection)(request) };
        if reflection_ptr.is_null() {
            return None;
        }

        let mut candidates = vec![type_name.to_string()];
        if !type_name.contains('.') {
            candidates.push(format!("shader.{type_name}"));
        }

        for candidate in &candidates {
            let name_cstr = CString::new(candidate.as_str()).ok()?;
            let ty = unsafe { (self.library.reflection_find_type_by_name)(reflection_ptr, name_cstr.as_ptr()) };
            if ty.is_null() {
                continue;
            }
            let layout_ptr =
                unsafe { (self.library.reflection_get_type_layout)(reflection_ptr, ty, SlangLayoutRules::Default) };
            if !layout_ptr.is_null() {
                return Some(layout_ptr);
            }
        }
        None
    }

    fn extract_struct_layout_uniform(
        &self,
        type_layout: *mut SlangReflectionTypeLayout,
        struct_name: &str,
    ) -> Result<StructLayout> {
        let cat = SlangParameterCategory::Uniform as i32;
        let size = unsafe { (self.library.reflection_type_layout_get_size)(type_layout, cat) };
        let alignment = unsafe { (self.library.reflection_type_layout_get_alignment)(type_layout, cat) };

        let field_count = unsafe { (self.library.reflection_type_layout_get_field_count)(type_layout) };

        let mut fields = Vec::new();
        for i in 0..field_count {
            let field_var = unsafe { (self.library.reflection_type_layout_get_field_by_index)(type_layout, i) };
            if field_var.is_null() {
                continue;
            }

            let variable = unsafe { (self.library.reflection_variable_layout_get_variable)(field_var) };
            let name = if !variable.is_null() {
                let name_ptr = unsafe { (self.library.reflection_variable_get_name)(variable) };
                if !name_ptr.is_null() {
                    unsafe { CStr::from_ptr(name_ptr) }.to_string_lossy().into_owned()
                } else {
                    format!("field_{i}")
                }
            } else {
                format!("field_{i}")
            };

            let field_type_layout = unsafe { (self.library.reflection_variable_layout_get_type_layout)(field_var) };
            if field_type_layout.is_null() {
                continue;
            }

            let offset = unsafe { (self.library.reflection_variable_layout_get_offset)(field_var, cat) };
            let fsize = unsafe { (self.library.reflection_type_layout_get_size)(field_type_layout, cat) };

            let field_type = unsafe { (self.library.reflection_type_layout_get_type)(field_type_layout) };
            let type_name = if !field_type.is_null() {
                let type_name_ptr = unsafe { (self.library.reflection_type_get_name)(field_type) };
                if !type_name_ptr.is_null() {
                    unsafe { CStr::from_ptr(type_name_ptr) }.to_string_lossy().into_owned()
                } else {
                    String::new()
                }
            } else {
                String::new()
            };

            fields.push(StructFieldLayout {
                name,
                offset,
                size: fsize,
                type_name,
            });
        }

        Ok(StructLayout {
            name: struct_name.to_string(),
            size,
            alignment,
            fields,
        })
    }

    /// Extract reflection data from a compiled request.
    fn extract_reflection(&self, request: *mut SlangCompileRequest) -> Result<ShaderReflection> {
        let _span = goldy_span!("slang.reflection.extract").entered();

        let reflection_ptr = unsafe { (self.library.get_reflection)(request) };
        if reflection_ptr.is_null() {
            return Ok(ShaderReflection::default());
        }

        let mut parameter_blocks = Vec::new();

        // Get parameter count
        let param_count = unsafe { (self.library.reflection_get_parameter_count)(reflection_ptr) };

        for i in 0..param_count {
            let param = unsafe { (self.library.reflection_get_parameter_by_index)(reflection_ptr, i) };
            if param.is_null() {
                continue;
            }

            // Get parameter name (parameter -> variable -> name)
            let variable = unsafe { (self.library.reflection_variable_layout_get_variable)(param) };
            let name = if !variable.is_null() {
                let name_ptr = unsafe { (self.library.reflection_variable_get_name)(variable) };
                if !name_ptr.is_null() {
                    unsafe { CStr::from_ptr(name_ptr) }.to_string_lossy().into_owned()
                } else {
                    format!("param_{}", i)
                }
            } else {
                format!("param_{}", i)
            };

            // Get type layout
            let type_layout = unsafe { (self.library.reflection_parameter_get_type_layout)(param) };
            if type_layout.is_null() {
                continue;
            }

            // Get the type to check if it's a ParameterBlock
            let type_ptr = unsafe { (self.library.reflection_type_layout_get_type)(type_layout) };
            if type_ptr.is_null() {
                continue;
            }

            let type_kind = unsafe { (self.library.reflection_type_get_kind)(type_ptr) };

            // Check if this is a ParameterBlock
            if type_kind == SlangTypeKind::ParameterBlock as i32 {
                let block_layout = self.extract_parameter_block_layout(param, type_layout, &name)?;
                parameter_blocks.push(block_layout);
            }
        }

        goldy_event!(
            "slang.reflection.extract",
            parameter_blocks = parameter_blocks.len(),
            total_fields = parameter_blocks.iter().map(|pb| pb.fields.len()).sum::<usize>()
        );

        Ok(ShaderReflection {
            parameter_blocks,
            push_constant_categories: Vec::new(),
            #[cfg(all(feature = "dx12", target_os = "windows"))]
            push_constant_slot_kinds: Vec::new(),
            binding_element_strides: Vec::new(),
        })
    }

    /// Extract layout information for a ParameterBlock.
    fn extract_parameter_block_layout(
        &self,
        param: *mut SlangReflectionParameter,
        type_layout: *mut SlangReflectionTypeLayout,
        name: &str,
    ) -> Result<ParameterBlockLayout> {
        // Get binding information
        let binding_slot = unsafe { (self.library.reflection_parameter_get_binding_index)(param) } as u32;
        let binding_space = unsafe { (self.library.reflection_parameter_get_binding_space)(param) } as u32;

        // Get the element type layout (the T in ParameterBlock<T>)
        let element_type_layout = unsafe { (self.library.reflection_type_layout_get_element_type_layout)(type_layout) };

        // Get size, alignment, and fields from the element type
        // Note: Slang returns slot counts, not byte sizes. Each slot = 8 bytes.
        const SLOT_SIZE_BYTES: usize = 8;

        let (mut size, alignment, fields) = if !element_type_layout.is_null() {
            // Try MetalArgumentBufferElement first (for argument buffers with resources)
            let size_slots = unsafe {
                (self.library.reflection_type_layout_get_size)(
                    element_type_layout,
                    SlangParameterCategory::MetalArgumentBufferElement as i32,
                )
            };
            let alignment = unsafe {
                (self.library.reflection_type_layout_get_alignment)(
                    element_type_layout,
                    SlangParameterCategory::MetalArgumentBufferElement as i32,
                )
            };
            let fields = self.extract_struct_fields(element_type_layout)?;
            // Convert slots to bytes
            let size = size_slots * SLOT_SIZE_BYTES;
            (size, alignment, fields)
        } else {
            // Fallback: use the type_layout directly
            let size = unsafe {
                (self.library.reflection_type_layout_get_size)(type_layout, SlangParameterCategory::Uniform as i32)
            };
            let alignment = unsafe {
                (self.library.reflection_type_layout_get_alignment)(type_layout, SlangParameterCategory::Uniform as i32)
            };
            (size, alignment, Vec::new())
        };

        // If size is still 0, calculate from fields (each resource pointer is 8 bytes)
        if size == 0 && !fields.is_empty() {
            size = fields.iter().map(|f| f.offset + f.size).max().unwrap_or(0);
        }

        // Alignment from Slang reflection is also in slots, convert to bytes
        // For Metal argument buffers, minimum alignment is 8 bytes (pointer size)
        let alignment_bytes = if alignment > 0 {
            alignment * SLOT_SIZE_BYTES
        } else {
            SLOT_SIZE_BYTES // Default to 8-byte alignment
        };

        Ok(ParameterBlockLayout {
            name: name.to_string(),
            binding_slot,
            binding_space,
            size,
            alignment: alignment_bytes,
            fields,
        })
    }

    /// Extract field layouts from a struct type (used for ParameterBlock element types).
    fn extract_struct_fields(&self, type_layout: *mut SlangReflectionTypeLayout) -> Result<Vec<FieldLayout>> {
        let mut fields = Vec::new();

        let field_count = unsafe { (self.library.reflection_type_layout_get_field_count)(type_layout) };

        for i in 0..field_count {
            let field_var = unsafe { (self.library.reflection_type_layout_get_field_by_index)(type_layout, i) };
            if field_var.is_null() {
                continue;
            }

            // Get field name (variable layout -> variable -> name)
            let variable = unsafe { (self.library.reflection_variable_layout_get_variable)(field_var) };
            let name = if !variable.is_null() {
                let name_ptr = unsafe { (self.library.reflection_variable_get_name)(variable) };
                if !name_ptr.is_null() {
                    unsafe { CStr::from_ptr(name_ptr) }.to_string_lossy().into_owned()
                } else {
                    format!("field_{}", i)
                }
            } else {
                format!("field_{}", i)
            };

            // Get field type layout
            let field_type_layout = unsafe { (self.library.reflection_variable_layout_get_type_layout)(field_var) };
            if field_type_layout.is_null() {
                continue;
            }

            // Determine resource kind
            let resource_kind = self.determine_resource_kind(field_type_layout);

            // For Metal argument buffers (ParameterBlock context), try MetalArgumentBufferElement
            // category first. This handles buffers, textures, and other resources correctly.
            // Slang returns SLOT indices, not byte offsets. Each slot is 8 bytes (GPU pointer size).
            let offset_slots = unsafe {
                (self.library.reflection_variable_layout_get_offset)(
                    field_var,
                    SlangParameterCategory::MetalArgumentBufferElement as i32,
                )
            };
            let size_slots = unsafe {
                (self.library.reflection_type_layout_get_size)(
                    field_type_layout,
                    SlangParameterCategory::MetalArgumentBufferElement as i32,
                )
            };

            // Convert slot counts to byte offsets/sizes (each slot = 8 bytes = GPU pointer)
            const SLOT_SIZE_BYTES: usize = 8;
            let offset = offset_slots * SLOT_SIZE_BYTES;
            let size = if size_slots > 0 {
                size_slots * SLOT_SIZE_BYTES
            } else {
                SLOT_SIZE_BYTES
            };

            tracing::trace!(
                "Field {} (index {}): offset_slots={}, size_slots={} -> offset={}, size={}, resource_kind={:?}",
                name,
                i,
                offset_slots,
                size_slots,
                offset,
                size,
                resource_kind
            );

            // Get type name
            let field_type = unsafe { (self.library.reflection_type_layout_get_type)(field_type_layout) };
            let type_name = if !field_type.is_null() {
                let type_name_ptr = unsafe { (self.library.reflection_type_get_name)(field_type) };
                if !type_name_ptr.is_null() {
                    unsafe { CStr::from_ptr(type_name_ptr) }.to_string_lossy().into_owned()
                } else {
                    String::new()
                }
            } else {
                String::new()
            };

            fields.push(FieldLayout {
                name,
                offset,
                size,
                resource_kind,
                type_name,
            });
        }

        Ok(fields)
    }

    /// Determine the resource kind from a type layout.
    fn determine_resource_kind(&self, type_layout: *mut SlangReflectionTypeLayout) -> ResourceKind {
        let type_ptr = unsafe { (self.library.reflection_type_layout_get_type)(type_layout) };
        if type_ptr.is_null() {
            return ResourceKind::Other;
        }

        let type_kind = unsafe { (self.library.reflection_type_get_kind)(type_ptr) };
        let binding_type = unsafe { (self.library.reflection_type_layout_get_binding_type)(type_layout) };

        // Debug logging for type detection
        tracing::trace!(
            "determine_resource_kind: type_kind={}, binding_type={}",
            type_kind,
            binding_type
        );

        match type_kind {
            k if k == SlangTypeKind::SamplerState as i32 => ResourceKind::Sampler,
            k if k == SlangTypeKind::ConstantBuffer as i32 => ResourceKind::ConstantBuffer,
            k if k == SlangTypeKind::ParameterBlock as i32 => ResourceKind::ParameterBlock,
            k if k == SlangTypeKind::Resource as i32 => {
                // Check binding type to distinguish buffer vs texture, mutable vs immutable
                match binding_type {
                    b if b == SlangBindingType::Texture as i32 => ResourceKind::Texture,
                    b if b == SlangBindingType::MutableTexture as i32 => ResourceKind::MutableTexture,
                    b if b == SlangBindingType::TypedBuffer as i32 => ResourceKind::Buffer,
                    b if b == SlangBindingType::MutableTypedBuffer as i32 => ResourceKind::MutableBuffer,
                    b if b == SlangBindingType::RawBuffer as i32 => ResourceKind::Buffer,
                    b if b == SlangBindingType::MutableRawBuffer as i32 => ResourceKind::MutableBuffer,
                    _ => ResourceKind::Other,
                }
            }
            k if k == SlangTypeKind::ShaderStorageBuffer as i32 => ResourceKind::MutableBuffer,
            _ => {
                // Try to infer from binding type if type_kind doesn't match expected values
                // This helps with StructuredBuffer which may have different type_kind
                match binding_type {
                    b if b == SlangBindingType::TypedBuffer as i32 => ResourceKind::Buffer,
                    b if b == SlangBindingType::MutableTypedBuffer as i32 => ResourceKind::MutableBuffer,
                    b if b == SlangBindingType::RawBuffer as i32 => ResourceKind::Buffer,
                    b if b == SlangBindingType::MutableRawBuffer as i32 => ResourceKind::MutableBuffer,
                    b if b == SlangBindingType::Texture as i32 => ResourceKind::Texture,
                    b if b == SlangBindingType::MutableTexture as i32 => ResourceKind::MutableTexture,
                    b if b == SlangBindingType::Sampler as i32 => ResourceKind::Sampler,
                    b if b == SlangBindingType::ConstantBuffer as i32 => ResourceKind::ConstantBuffer,
                    _ => ResourceKind::Other,
                }
            }
        }
    }
}

#[cfg(test)]
mod builtin_stride_tests {
    use super::builtin_type_stride;

    #[test]
    fn scalar_types() {
        assert_eq!(builtin_type_stride("uint"), Some(4));
        assert_eq!(builtin_type_stride("int"), Some(4));
        assert_eq!(builtin_type_stride("float"), Some(4));
        assert_eq!(builtin_type_stride("half"), Some(2));
        assert_eq!(builtin_type_stride("double"), Some(8));
    }

    #[test]
    fn vector_types() {
        assert_eq!(builtin_type_stride("float2"), Some(8));
        assert_eq!(builtin_type_stride("float3"), Some(12));
        assert_eq!(builtin_type_stride("float4"), Some(16));
        assert_eq!(builtin_type_stride("uint4"), Some(16));
    }

    #[test]
    fn matrix_types() {
        assert_eq!(builtin_type_stride("float4x4"), Some(64));
    }

    #[test]
    fn user_struct_returns_none() {
        assert_eq!(builtin_type_stride("MyStruct"), None);
        assert_eq!(builtin_type_stride("Particle"), None);
    }

    #[test]
    fn dispatch_shape_stride() {
        assert_eq!(builtin_type_stride("DispatchShape"), Some(12));
    }
}

#[cfg(test)]
mod struct_layout_validate_tests {
    use super::{StructFieldLayout, StructLayout};
    use crate as goldy;

    fn two_float_layout() -> StructLayout {
        StructLayout {
            name: "S".into(),
            size: 8,
            alignment: 4,
            fields: vec![
                StructFieldLayout {
                    name: "a".into(),
                    offset: 0,
                    size: 4,
                    type_name: "float".into(),
                },
                StructFieldLayout {
                    name: "b".into(),
                    offset: 4,
                    size: 4,
                    type_name: "float".into(),
                },
            ],
        }
    }

    /// Slang CB layout: total size padded to 16 with one `float` field (GPU tail padding).
    fn layout_time_only_cb_padded() -> StructLayout {
        StructLayout {
            name: "TimeUniforms".into(),
            size: 16,
            alignment: 16,
            fields: vec![StructFieldLayout {
                name: "time".into(),
                offset: 0,
                size: 4,
                type_name: "float".into(),
            }],
        }
    }

    #[test]
    fn validate_cb_padded_single_field_passes() {
        let slang = layout_time_only_cb_padded();
        let rust_fields = [("time", 0usize, 4usize)];
        slang
            .validate(4, &rust_fields)
            .expect("Rust 4-byte struct should cover Slang data extent");
    }

    #[test]
    fn validate_shader_field_missing_from_rust_errors() {
        let slang = StructLayout {
            name: "U".into(),
            size: 8,
            alignment: 4,
            fields: vec![
                StructFieldLayout {
                    name: "time".into(),
                    offset: 0,
                    size: 4,
                    type_name: "float".into(),
                },
                StructFieldLayout {
                    name: "brightness".into(),
                    offset: 4,
                    size: 4,
                    type_name: "float".into(),
                },
            ],
        };
        let rust_fields = [("time", 0usize, 4usize)];
        let err = slang.validate(4, &rust_fields).unwrap_err();
        let s = err.to_string();
        assert!(
            s.contains("brightness") && s.contains("missing"),
            "expected missing-field error, got: {s}"
        );
    }

    #[test]
    fn validate_rust_too_small_for_data_extent_errors() {
        let slang = layout_time_only_cb_padded();
        let rust_fields = [("time", 0usize, 4usize)];
        let err = slang.validate(2, &rust_fields).unwrap_err();
        assert!(
            err.to_string().contains("smaller than the shader's data extent"),
            "{err}"
        );
    }

    #[test]
    fn validate_extra_rust_field_without_underscore_passes() {
        let slang = layout_time_only_cb_padded();
        let rust_fields = [("time", 0usize, 4usize), ("brightness", 4usize, 4usize)];
        slang
            .validate(8, &rust_fields)
            .expect("extra Rust field is not an error");
    }

    #[test]
    fn validate_extra_rust_field_with_underscore_passes() {
        let slang = layout_time_only_cb_padded();
        let rust_fields = [("time", 0usize, 4usize), ("_pad0", 4usize, 4usize)];
        slang
            .validate(8, &rust_fields)
            .expect("_prefixed extra field is silent");
    }

    #[test]
    fn validate_ok_when_matching() {
        two_float_layout().validate(8, &[("a", 0, 4), ("b", 4, 4)]).unwrap();
    }

    #[test]
    fn validate_does_not_require_rust_struct_to_match_slang_cb_padding() {
        // Slang total `size` can be 16 due to cbuffer rules; Rust only needs to cover data bytes.
        let mut layout = two_float_layout();
        layout.size = 16;
        layout
            .validate(8, &[("a", 0, 4), ("b", 4, 4)])
            .expect("Slang padded size must not force Rust to pad");
    }

    #[test]
    fn validate_err_on_field_count_mismatch() {
        let err = two_float_layout().validate(8, &[("a", 0, 4)]).unwrap_err().to_string();
        assert!(
            err.contains("`b`") && err.contains("missing"),
            "expected shader field b missing in Rust: {err}"
        );
    }

    #[test]
    fn validate_allows_extra_rust_fields_not_in_shader() {
        two_float_layout()
            .validate(12, &[("a", 0, 4), ("b", 4, 4), ("c", 8, 4)])
            .expect("extra Rust-only field should not fail validation");
    }

    #[test]
    fn validate_err_on_field_offset_mismatch() {
        let err = two_float_layout()
            .validate(8, &[("a", 0, 4), ("b", 0, 4)])
            .unwrap_err()
            .to_string();
        assert!(err.contains("offset"), "expected offset mismatch: {err}");
        assert!(err.contains("`b`"), "expected field name b: {err}");
    }

    #[test]
    fn validate_err_on_field_size_mismatch() {
        let err = two_float_layout()
            .validate(8, &[("a", 0, 8), ("b", 4, 4)])
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("size") && err.contains("`a`"),
            "expected field size mismatch for a: {err}"
        );
    }

    #[test]
    fn validate_err_on_field_name_mismatch() {
        let err = two_float_layout()
            .validate(8, &[("x", 0, 4), ("b", 4, 4)])
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("`a`") && err.contains("missing"),
            "expected shader field `a` missing from Rust (got `x` instead): {err}"
        );
    }

    #[test]
    fn validate_reports_multiple_errors() {
        // Only `a` in Rust, wrong offset — missing `b` and offset error for `a`.
        let err = two_float_layout().validate(8, &[("a", 4, 4)]).unwrap_err().to_string();
        assert!(
            err.contains("offset") && err.contains("`a`"),
            "expected offset error for a: {err}"
        );
        assert!(
            err.contains("`b`") && err.contains("missing"),
            "expected missing b: {err}"
        );
    }

    #[test]
    fn layout_checkable_derive_generates_correct_const() {
        #[derive(goldy_derive::LayoutCheckable)]
        #[repr(C)]
        struct TestStruct {
            pos: [f32; 2],
            color: [f32; 4],
        }

        let check = TestStruct::LAYOUT_CHECK;
        assert_eq!(check.type_name, "TestStruct");
        assert_eq!(check.rust_size, std::mem::size_of::<TestStruct>());
        assert_eq!(check.rust_fields.len(), 2);

        let (name, offset, size) = check.rust_fields[0];
        assert_eq!(name, "pos");
        assert_eq!(offset, 0);
        assert_eq!(size, std::mem::size_of::<[f32; 2]>());

        let (name, offset, size) = check.rust_fields[1];
        assert_eq!(name, "color");
        assert_eq!(offset, std::mem::size_of::<[f32; 2]>());
        assert_eq!(size, std::mem::size_of::<[f32; 4]>());
    }

    #[test]
    fn layout_check_validates_against_matching_slang_layout() {
        #[derive(goldy_derive::LayoutCheckable)]
        #[repr(C)]
        struct Uniforms {
            x: f32,
            y: f32,
        }

        let slang = StructLayout {
            name: "Uniforms".into(),
            size: 8,
            alignment: 4,
            fields: vec![
                StructFieldLayout {
                    name: "x".into(),
                    offset: 0,
                    size: 4,
                    type_name: "float".into(),
                },
                StructFieldLayout {
                    name: "y".into(),
                    offset: 4,
                    size: 4,
                    type_name: "float".into(),
                },
            ],
        };

        let check = Uniforms::LAYOUT_CHECK;
        slang.validate(check.rust_size, check.rust_fields).unwrap();
    }

    #[test]
    fn layout_check_detects_mismatch_against_slang_layout() {
        #[derive(goldy_derive::LayoutCheckable)]
        #[repr(C)]
        struct Uniforms {
            x: f32,
            y: f32,
        }

        let slang_with_wrong_offset = StructLayout {
            name: "Uniforms".into(),
            size: 8,
            alignment: 4,
            fields: vec![
                StructFieldLayout {
                    name: "x".into(),
                    offset: 0,
                    size: 4,
                    type_name: "float".into(),
                },
                StructFieldLayout {
                    name: "y".into(),
                    offset: 8,
                    size: 4,
                    type_name: "float".into(),
                },
            ],
        };

        let check = Uniforms::LAYOUT_CHECK;
        let err = slang_with_wrong_offset
            .validate(check.rust_size, check.rust_fields)
            .unwrap_err()
            .to_string();
        assert!(err.contains("offset"), "expected offset mismatch: {err}");
        assert!(err.contains("`y`"), "expected field y: {err}");
    }

    /// Integration test: feeds a deliberate layout mismatch through the full
    /// `compile_with_reflection` path and checks that the error message is
    /// actionable (contains the struct name and "offset").
    ///
    /// This is the path an agent hits when `GOLDY_VALIDATE_LAYOUTS=1` is set
    /// and a `#[derive(LayoutCheckable)]` struct drifts from its Slang counterpart.
    #[test]
    fn layout_validation_end_to_end_catches_mismatch() {
        use super::{OwnedLayoutCheck, ShaderTarget, SlangCompiler, SlangStage};
        use crate::types::OptimizationLevel;

        let compiler = SlangCompiler::new().expect("Slang compiler unavailable; skipping");

        // A minimal compute shader that declares MyUniforms.
        let source = r#"
            struct MyUniforms { float x; float y; };
            [shader("compute")]
            [numthreads(1, 1, 1)]
            void cs_main() {}
        "#;

        // Correct Rust layout for { float x; float y; } — size=8, y at offset 4.
        // We intentionally claim y is at offset 8, which Slang will disagree with.
        let bad_check = OwnedLayoutCheck {
            type_name: "MyUniforms".into(),
            rust_size: 8,
            rust_fields: vec![
                ("x".into(), 0, 4),
                ("y".into(), 8, 4), // wrong: Slang reflects offset 4
            ],
        };

        let err = compiler
            .compile_with_reflection(
                source,
                ShaderTarget::Spirv,
                &[("cs_main", SlangStage::Compute)],
                &[],
                &[],
                &[bad_check],
                OptimizationLevel::None,
            )
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("MyUniforms"),
            "error should name the mismatched struct: {err}"
        );
        assert!(
            err.contains("offset"),
            "error should describe the offset mismatch: {err}"
        );
        assert!(err.contains("`y`"), "error should name the offending field: {err}");
    }

    /// Integration test: compiles a `[goldy_compute]` shader that uses
    /// `Scattered<uint>` and a broadcast struct, then verifies that the
    /// reflected `binding_element_strides` contain the expected values.
    #[test]
    fn stride_extraction_end_to_end() {
        use super::{ShaderTarget, SlangCompiler, SlangStage};
        use crate::types::OptimizationLevel;

        let compiler = SlangCompiler::new().expect("Slang compiler unavailable; skipping");

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let path = manifest_dir.join("shaders").to_string_lossy().into_owned();

        let source = r#"
            import goldy_exp;

            struct Params { float x; float y; };

            [goldy_compute]
            [numthreads(64, 1, 1)]
            void cs_main(Params cfg, Scattered<uint> data, ThreadId id) {
                data[id.x] = uint(cfg.x);
            }
        "#;

        let result = compiler
            .compile_with_reflection(
                source,
                ShaderTarget::Spirv,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[("__SPIRV__", "1")],
                &[],
                OptimizationLevel::None,
            )
            .expect("compilation failed");

        let strides = &result.reflection.binding_element_strides;
        assert_eq!(strides.len(), 2, "expected 2 binding slots: {strides:?}");

        // Broadcast params use reflect_struct_storage_stride: field extent without
        // std140 tail-padding.  Params { float x; float y } = 2 × 4 = 8 bytes.
        assert_eq!(
            strides[0],
            Some(8),
            "Broadcast Params {{float x; float y}} natural stride should be 8 (not cbuffer 16): {strides:?}"
        );
        assert_eq!(
            strides[1],
            Some(4),
            "Scattered<uint> element stride should be 4: {strides:?}"
        );
    }

    #[test]
    fn stride_extraction_structured_buffer_element_uses_storage_layout() {
        use super::{ShaderTarget, SlangCompiler, SlangStage};
        use crate::types::OptimizationLevel;

        let compiler = SlangCompiler::new().expect("Slang compiler unavailable; skipping");

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let path = manifest_dir.join("shaders").to_string_lossy().into_owned();

        let source = r#"
            import goldy_exp;

            struct Pair { uint a; uint b; };

            [goldy_compute]
            [numthreads(64, 1, 1)]
            void cs_main(BufRO<Pair> input, Scattered<Pair> output, ThreadId id) {
                output[id.x] = input[id.x];
            }
        "#;

        let result = compiler
            .compile_with_reflection(
                source,
                ShaderTarget::Spirv,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[("__SPIRV__", "1")],
                &[],
                OptimizationLevel::None,
            )
            .expect("compilation failed");

        let strides = &result.reflection.binding_element_strides;
        assert_eq!(strides.len(), 2, "expected 2 binding slots: {strides:?}");
        assert_eq!(
            strides[0],
            Some(8),
            "BufRO<Pair> element stride should be 8 (not uniform 16): {strides:?}"
        );
        assert_eq!(
            strides[1],
            Some(8),
            "Scattered<Pair> element stride should be 8: {strides:?}"
        );
    }

    /// Regression: Broadcast params (plain struct without Scattered<>) must use
    /// struct_storage_stride (natural field extent) — NOT the std140-padded
    /// cbuffer size.  Before the fix, `reflect_type_size_with_category(Uniform)`
    /// returned 16 for a single-float struct (cbuffer alignment), causing
    /// validate_binding_strides to reject a correctly-created buffer with
    /// element_stride = 4.
    #[test]
    fn broadcast_param_stride_matches_natural_struct_size_not_cbuffer_padded() {
        use super::{ShaderTarget, SlangCompiler, SlangStage};
        use crate::types::OptimizationLevel;

        let compiler = SlangCompiler::new().expect("Slang compiler unavailable; skipping");

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let path = manifest_dir.join("shaders").to_string_lossy().into_owned();

        // SimParams { float deltaTime; } — natural size 4, cbuffer-padded size 16.
        let source = r#"
            import goldy_exp;

            struct SimParams { float deltaTime; };

            [goldy_compute]
            [numthreads(64, 1, 1)]
            void cs_main(Scattered<uint> data, SimParams params, ThreadId id) {
                data[id.x] = uint(params.deltaTime);
            }
        "#;

        let result = compiler
            .compile_with_reflection(
                source,
                ShaderTarget::Spirv,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[("__SPIRV__", "1")],
                &[],
                OptimizationLevel::None,
            )
            .expect("compilation failed");

        let strides = &result.reflection.binding_element_strides;
        assert_eq!(strides.len(), 2, "expected 2 binding slots: {strides:?}");
        assert_eq!(
            strides[0],
            Some(4),
            "Scattered<uint> element stride should be 4: {strides:?}"
        );
        // This was the bug: cbuffer-padded layout returned 16 here, causing
        // validate_binding_strides to fail for a correctly-created buffer.
        assert_eq!(
            strides[1],
            Some(4),
            "Broadcast SimParams{{float deltaTime}} natural stride should be 4, not cbuffer 16: {strides:?}"
        );
    }

    /// Multi-field Broadcast struct: stride must be the sum of fields, not
    /// the std140 whole-struct size.  `Params { float x; float y; }` = 8 bytes
    /// naturally; std140 would pad to 16.
    #[test]
    fn broadcast_two_float_struct_stride_is_eight_not_sixteen() {
        use super::{ShaderTarget, SlangCompiler, SlangStage};
        use crate::types::OptimizationLevel;

        let compiler = SlangCompiler::new().expect("Slang compiler unavailable; skipping");

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let path = manifest_dir.join("shaders").to_string_lossy().into_owned();

        let source = r#"
            import goldy_exp;

            struct Params { float x; float y; };

            [goldy_compute]
            [numthreads(64, 1, 1)]
            void cs_main(Params cfg, Scattered<uint> data, ThreadId id) {
                data[id.x] = uint(cfg.x + cfg.y);
            }
        "#;

        let result = compiler
            .compile_with_reflection(
                source,
                ShaderTarget::Spirv,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[("__SPIRV__", "1")],
                &[],
                OptimizationLevel::None,
            )
            .expect("compilation failed");

        let strides = &result.reflection.binding_element_strides;
        assert_eq!(strides.len(), 2, "expected 2 binding slots: {strides:?}");
        assert_eq!(
            strides[0],
            Some(8),
            "Broadcast Params{{float x; float y}} natural stride = 8: {strides:?}"
        );
        assert_eq!(strides[1], Some(4), "Scattered<uint> = 4: {strides:?}");
    }

    /// Validate that `validate_binding_strides` correctly catches a stride
    /// mismatch (expected vs actual) and passes when they agree.
    #[test]
    fn validate_binding_strides_passes_and_fails_correctly() {
        use crate::backend::validate_binding_strides;

        // Matching strides — must pass.
        let actual = vec![Some(16u32), Some(4u32)];
        let expected = vec![Some(16u32), Some(4u32)];
        assert!(validate_binding_strides(&actual, &expected, "test").is_ok());

        // Slot 1 mismatch: 16 expected, 4 actual — must fail with the slot number.
        let actual_bad = vec![Some(16u32), Some(4u32)];
        let expected_bad = vec![Some(16u32), Some(16u32)];
        let err =
            validate_binding_strides(&actual_bad, &expected_bad, "myshader").expect_err("should fail on mismatch");
        let msg = err.to_string();
        assert!(msg.contains("slot 1"), "error should name the slot: {msg}");
        assert!(msg.contains("myshader"), "error should name the shader: {msg}");
    }
}

impl Drop for SlangCompiler {
    fn drop(&mut self) {
        let _guard = SLANG_PROCESS_LOCK.lock().unwrap();
        if !self.global_session.is_null() {
            unsafe { global_session_release(self.global_session) };
            self.global_session = std::ptr::null_mut();
        }
    }
}

/// Verify that `uniform` entry-point parameters (the replacement for
/// `gGoldyDynamic`) compile correctly for all three backends, and that
/// the resulting code accesses the expected resource-slot / argument-buffer
/// locations.
///
/// SPIR-V: `uniform` params → implemented via push constants at offset 0 (std430).
/// DXIL:   `uniform` params → implemented via root constants at b0/space0.
/// Metal:  Slang wraps them in an `EntryPointParams` struct at buffer index 1.
#[cfg(test)]
mod uniform_entry_point_param_binding_tests {
    use super::*;

    /// A minimal compute shader with typed params and no gGoldyDynamic.
    const TEST_SHADER: &str = r#"
        import goldy_exp;

        [goldy_compute]
        [numthreads(64, 1, 1)]
        void cs_main(BufRO<uint> src, Scattered<uint> dst, uint base, ThreadId id) {
            uint ix = id.x + base;
            dst[ix] = src[ix];
        }
    "#;

    fn shader_path() -> String {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        manifest_dir.join("shaders").to_string_lossy().into_owned()
    }

    #[test]
    fn uniform_params_compile_spirv() {
        let compiler = SlangCompiler::new().expect("Slang unavailable");
        let path = shader_path();

        let output = compiler
            .compile_bindless_with_reflection_and_defines(
                TEST_SHADER,
                ShaderTarget::Spirv,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[],
                &[],
                OptimizationLevel::None,
            )
            .expect("SPIR-V compilation failed for uniform entry-point params");

        assert!(!output.shader.data.is_empty(), "SPIR-V output is empty");

        // Verify SPIR-V magic word (0x07230203).
        let words = output.shader.as_spirv().expect("should be valid SPIR-V");
        assert_eq!(words[0], 0x07230203, "SPIR-V magic number mismatch");

        // StorageClass::PushConstant == 9. This value should appear as a word in
        // the SPIR-V binary when uniform entry-point params are mapped to resource slots.
        assert!(
            words.contains(&9),
            "Expected PushConstant storage class (9) in SPIR-V for uniform params"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn uniform_params_compile_dxil() {
        let compiler = SlangCompiler::new().expect("Slang unavailable");
        let path = shader_path();

        let output = compiler
            .compile_bindless_with_reflection_and_defines(
                TEST_SHADER,
                ShaderTarget::Dxil,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[],
                &[],
                OptimizationLevel::None,
            )
            .expect("DXIL compilation failed for uniform entry-point params");

        assert!(!output.shader.data.is_empty(), "DXIL output is empty");
        // DXIL container magic: "DXBC" = 0x43425844 at byte offset 0.
        let magic = u32::from_le_bytes(output.shader.data[..4].try_into().unwrap());
        assert_eq!(magic, 0x43425844, "DXIL magic 'DXBC' mismatch");
    }

    #[test]
    fn uniform_params_compile_metal() {
        let compiler = SlangCompiler::new().expect("Slang unavailable");
        let path = shader_path();

        let output = compiler
            .compile_bindless_with_reflection_and_defines(
                TEST_SHADER,
                ShaderTarget::Metal,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[],
                &[],
                OptimizationLevel::None,
            )
            .expect("Metal MSL compilation failed for uniform entry-point params");

        let msl = String::from_utf8_lossy(&output.shader.data);
        assert!(!msl.is_empty(), "Metal MSL output is empty");

        // Slang emits uniform entry-point params as a generated struct (EntryPointParams
        // or similar) passed at a specific buffer slot. The struct name may vary by Slang
        // version, but the kernel's argument list should contain a [[buffer(...)]] binding.
        assert!(
            msl.contains("[[buffer(") || msl.contains("buffer("),
            "Expected Metal buffer binding for uniform params in MSL:\n{msl}"
        );
    }

    /// Regression: compiled Metal output must not contain gGoldyDynamic or
    /// GoldyDynamicSlots — both were removed in the gGoldyDynamic migration.
    #[test]
    fn no_ggoldydynamic_in_compiled_output() {
        let compiler = SlangCompiler::new().expect("Slang unavailable");
        let path = shader_path();

        let output = compiler
            .compile_bindless_with_reflection_and_defines(
                TEST_SHADER,
                ShaderTarget::Metal,
                &[("cs_main", SlangStage::Compute)],
                &[&path],
                &[],
                &[],
                OptimizationLevel::None,
            )
            .expect("Metal MSL compilation failed");

        let msl = String::from_utf8_lossy(&output.shader.data);
        assert!(
            !msl.contains("gGoldyDynamic"),
            "gGoldyDynamic must not appear in output MSL"
        );
        assert!(
            !msl.contains("GoldyDynamicSlots"),
            "GoldyDynamicSlots must not appear in output MSL"
        );
    }
}