cabinpkg-core 0.17.0

Stable internal data model for Cabin
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
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
//! Typed C/C++ language standards.
//!
//! Owns the standard enums (ISO levels only; GNU extensions are the
//! orthogonal per-target `gnu-extensions` boolean), the manifest
//! declaration shape shared by `[package]` and `[target.<name>]`,
//! effective-standard resolution (target â–¶ package; there is no
//! built-in default - a target that compiles a language without a
//! declared standard is a manifest error), interface-requirement
//! relevance and fallback, the escape-hatch conflict detector, the
//! interface/implementation contradiction lint, and the per-package
//! summary that feeds `BuildConfiguration` fingerprinting and the
//! metadata view.  Pure data and logic only; no I/O.  See
//! `docs/language-standards.md` for the user-facing contract.

use std::collections::BTreeMap;
use std::marker::PhantomData;

use serde::de::{MapAccess, Visitor, value::MapAccessDeserializer};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{ResolvedProfileFlags, SourceLanguage, Target, classify_source};

/// C language standards Cabin can request, oldest to newest.  The
/// `Ord` derive follows declaration order, which is the plain
/// chronological chain (in particular `c11 < c17`).  Implements the
/// level chain `Level_C` of spec D2
/// (`docs/design/standard-compatibility/spec.md`): chronological
/// enumeration order, not numeric (`c89 < c11`), with no
/// equivalence special case anywhere in the chain.  The `c90` alias
/// is normalized away by [`Self::parse`] and is not an element of
/// the chain (D2 remark).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum CStandard {
    #[serde(rename = "c89")]
    C89,
    #[serde(rename = "c99")]
    C99,
    #[serde(rename = "c11")]
    C11,
    #[serde(rename = "c17")]
    C17,
    #[serde(rename = "c23")]
    C23,
}

impl CStandard {
    pub const ALL: [Self; 5] = [Self::C89, Self::C99, Self::C11, Self::C17, Self::C23];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::C89 => "c89",
            Self::C99 => "c99",
            Self::C11 => "c11",
            Self::C17 => "c17",
            Self::C23 => "c23",
        }
    }

    /// # Errors
    /// Returns [`LanguageStandardParseError`] when `value` is not a
    /// recognized C standard: a dedicated variant for range-like
    /// inputs and for the interface-only `none`, otherwise the
    /// invalid-value error listing the accepted identifiers.
    /// `c90` parses as an alias of `c89`, normalized immediately.
    pub fn parse(value: &str) -> Result<Self, LanguageStandardParseError> {
        reject_non_identifier(SourceLanguage::C, value)?;
        let normalized = if value == "c90" { "c89" } else { value };
        Self::ALL
            .into_iter()
            .find(|s| s.as_str() == normalized)
            .ok_or_else(|| LanguageStandardParseError::Unknown {
                language: SourceLanguage::C,
                value: value.to_owned(),
            })
    }
}

impl std::fmt::Display for CStandard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for CStandard {
    type Err = LanguageStandardParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// C++ language standards Cabin can request, oldest to newest, in
/// the plain chronological chain.  Implements the level chain
/// `Level_C++` of spec D2
/// (`docs/design/standard-compatibility/spec.md`): chronological
/// enumeration order, not numeric (`c++98 < c++11`), with no
/// equivalence special case anywhere in the chain.  The `c++03`
/// alias is normalized away by [`Self::parse`] and is not an
/// element of the chain (D2 remark).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum CxxStandard {
    #[serde(rename = "c++98")]
    Cxx98,
    #[serde(rename = "c++11")]
    Cxx11,
    #[serde(rename = "c++14")]
    Cxx14,
    #[serde(rename = "c++17")]
    Cxx17,
    #[serde(rename = "c++20")]
    Cxx20,
    #[serde(rename = "c++23")]
    Cxx23,
    #[serde(rename = "c++26")]
    Cxx26,
}

impl CxxStandard {
    pub const ALL: [Self; 7] = [
        Self::Cxx98,
        Self::Cxx11,
        Self::Cxx14,
        Self::Cxx17,
        Self::Cxx20,
        Self::Cxx23,
        Self::Cxx26,
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Cxx98 => "c++98",
            Self::Cxx11 => "c++11",
            Self::Cxx14 => "c++14",
            Self::Cxx17 => "c++17",
            Self::Cxx20 => "c++20",
            Self::Cxx23 => "c++23",
            Self::Cxx26 => "c++26",
        }
    }

    /// # Errors
    /// Returns [`LanguageStandardParseError`] when `value` is not a
    /// recognized C++ standard: a dedicated variant for range-like
    /// inputs and for the interface-only `none`, otherwise the
    /// invalid-value error listing the accepted identifiers.
    /// `c++03` parses as an alias of `c++98`, normalized
    /// immediately.
    pub fn parse(value: &str) -> Result<Self, LanguageStandardParseError> {
        reject_non_identifier(SourceLanguage::Cxx, value)?;
        let normalized = if value == "c++03" { "c++98" } else { value };
        Self::ALL
            .into_iter()
            .find(|s| s.as_str() == normalized)
            .ok_or_else(|| LanguageStandardParseError::Unknown {
                language: SourceLanguage::Cxx,
                value: value.to_owned(),
            })
    }
}

impl std::fmt::Display for CxxStandard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for CxxStandard {
    type Err = LanguageStandardParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// The shared pre-lookup checks: range-like inputs and the
/// interface-only `none` get dedicated diagnostics on every field
/// that parses a standard value.
fn reject_non_identifier(
    language: SourceLanguage,
    value: &str,
) -> Result<(), LanguageStandardParseError> {
    // `>=` / `<=` are covered by their first character.
    if value.contains(['>', '<', ',']) {
        return Err(LanguageStandardParseError::RangeReserved {
            language,
            value: value.to_owned(),
        });
    }
    if value == "none" {
        return Err(LanguageStandardParseError::NoneOnImplementation { language });
    }
    Ok(())
}

/// An invalid manifest standard value.  Range-like inputs and the
/// misplaced interface-only `none` get dedicated variants; anything
/// else is the invalid-value error listing the accepted
/// identifiers.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum LanguageStandardParseError {
    #[error(
        "unknown {} standard `{value}`: expected one of {}",
        .language.human_label(),
        valid_standard_values(*.language)
    )]
    Unknown {
        language: SourceLanguage,
        value: String,
    },
    #[error(
        "range requirement `{value}` is reserved for a future version of Cabin; declare a single {} standard",
        .language.human_label()
    )]
    RangeReserved {
        language: SourceLanguage,
        value: String,
    },
    #[error(
        "`none` is only valid on `interface-c-standard` / `interface-cxx-standard`, where it marks the target's headers as not consumable from that language; compiled {} sources need a concrete standard",
        .language.human_label()
    )]
    NoneOnImplementation { language: SourceLanguage },
}

fn valid_standard_values(language: SourceLanguage) -> String {
    match language {
        SourceLanguage::C => CStandard::ALL.map(CStandard::as_str).join(", "),
        SourceLanguage::Cxx => CxxStandard::ALL.map(CxxStandard::as_str).join(", "),
    }
}

/// The implementation-standard field family for `language`
/// (`c-standard` / `cxx-standard`), for diagnostics.
const fn implementation_field(language: SourceLanguage) -> &'static str {
    match language {
        SourceLanguage::C => "c-standard",
        SourceLanguage::Cxx => "cxx-standard",
    }
}

/// One per-compile standard value, carried by the build IR.  Encodes
/// the source language, so the dialect lowering derives both the
/// rule kind and the standard flag from this single field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LanguageStandard {
    C(CStandard),
    Cxx(CxxStandard),
}

impl LanguageStandard {
    pub const fn language(self) -> SourceLanguage {
        match self {
            Self::C(_) => SourceLanguage::C,
            Self::Cxx(_) => SourceLanguage::Cxx,
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::C(s) => s.as_str(),
            Self::Cxx(s) => s.as_str(),
        }
    }

    /// The `/std:` value `cl.exe` accepts for this standard, when a
    /// stable one exists.  `None` marks the MSVC-dialect gaps
    /// (C89/C99/C23, C++98/11/23/26); the planner rejects those
    /// before lowering on the MSVC dialect.
    pub const fn msvc_spelling(self) -> Option<&'static str> {
        match self {
            Self::C(CStandard::C11) => Some("/std:c11"),
            Self::C(CStandard::C17) => Some("/std:c17"),
            Self::Cxx(CxxStandard::Cxx14) => Some("/std:c++14"),
            Self::Cxx(CxxStandard::Cxx17) => Some("/std:c++17"),
            Self::Cxx(CxxStandard::Cxx20) => Some("/std:c++20"),
            _ => None,
        }
    }
}

impl std::fmt::Display for LanguageStandard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One interface standard requirement: the minimum standard the
/// target's public headers require from consumers.  `max` is
/// reserved for future range requirements and is never populated
/// today, but it stays in the type and every serialized form so the
/// wire shape does not change when ranges land.  This is the
/// `{ min, max }` pair of spec D4's remark
/// (`docs/design/standard-compatibility/spec.md`): with `max`
/// always absent in v1, a requirement denotes the declared minimum
/// `decl_L(t) = m` of spec D6, which D9 row 2 maps to the
/// compatibility requirement `[m]`
/// ([`crate::standard_compatibility::Requirement::Min`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StandardRequirement<S> {
    pub min: S,
    #[serde(default = "none")]
    pub max: Option<S>,
}

// `#[serde(default)]` needs a fn item; `Option::default` would also
// work but reads as a value default rather than "absent max".
fn none<S>() -> Option<S> {
    None
}

/// One declared interface-standard value: either a requirement or
/// the explicit `none`, meaning the target's headers are not
/// consumable from that language.  Implements the explicit
/// interface declaration `decl_L(t)` of spec D6
/// (`docs/design/standard-compatibility/spec.md`); D6's `⊥` (no
/// declaration) is an absent `Option<InterfaceRequirement>` at the
/// use sites.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterfaceRequirement<S> {
    /// The target's headers are not consumable from this language:
    /// the declared `"none"` of spec D6, which D9 row 1 maps to the
    /// unsatisfiable requirement
    /// ([`crate::standard_compatibility::Requirement::Forbidden`]).
    None,
    Requirement(StandardRequirement<S>),
}

impl<S> InterfaceRequirement<S> {
    /// The minimum standard, when this is a requirement.
    #[must_use]
    pub fn min(self) -> Option<S> {
        match self {
            Self::None => None,
            Self::Requirement(requirement) => Some(requirement.min),
        }
    }
}

/// Parse one `interface-c-standard` value: `none` or a single C
/// standard (ranges are reserved; see [`CStandard::parse`]).
///
/// # Errors
/// Propagates [`CStandard::parse`] errors for anything but `none`.
pub fn parse_interface_c(
    value: &str,
) -> Result<InterfaceRequirement<CStandard>, LanguageStandardParseError> {
    if value == "none" {
        return Ok(InterfaceRequirement::None);
    }
    CStandard::parse(value)
        .map(|min| InterfaceRequirement::Requirement(StandardRequirement { min, max: None }))
}

/// Parse one `interface-cxx-standard` value: `none` or a single C++
/// standard.
///
/// # Errors
/// Propagates [`CxxStandard::parse`] errors for anything but `none`.
pub fn parse_interface_cxx(
    value: &str,
) -> Result<InterfaceRequirement<CxxStandard>, LanguageStandardParseError> {
    if value == "none" {
        return Ok(InterfaceRequirement::None);
    }
    CxxStandard::parse(value)
        .map(|min| InterfaceRequirement::Requirement(StandardRequirement { min, max: None }))
}

impl<S: std::fmt::Display> std::fmt::Display for InterfaceRequirement<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => f.write_str("none"),
            Self::Requirement(StandardRequirement { min, max: None }) => min.fmt(f),
            Self::Requirement(StandardRequirement {
                min,
                max: Some(max),
            }) => write!(f, "{min}..{max}"),
        }
    }
}

// `none` serializes as the bare string; a requirement serializes as
// its `{ min, max }` table (with `max` present even while reserved)
// so the canonical-metadata / index wire format is stable when
// range support lands.
impl<S: Serialize> Serialize for InterfaceRequirement<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        match self {
            Self::None => serializer.serialize_str("none"),
            Self::Requirement(requirement) => requirement.serialize(serializer),
        }
    }
}

impl<'de, S: Deserialize<'de>> Deserialize<'de> for InterfaceRequirement<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct InterfaceRequirementVisitor<S>(PhantomData<S>);

        impl<'de, S: Deserialize<'de>> Visitor<'de> for InterfaceRequirementVisitor<S> {
            type Value = InterfaceRequirement<S>;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("`none` or a `{ min, max }` requirement table")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                if v == "none" {
                    Ok(InterfaceRequirement::None)
                } else {
                    Err(E::invalid_value(serde::de::Unexpected::Str(v), &self))
                }
            }

            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                StandardRequirement::deserialize(MapAccessDeserializer::new(map))
                    .map(InterfaceRequirement::Requirement)
            }
        }

        deserializer.deserialize_any(InterfaceRequirementVisitor(PhantomData))
    }
}

/// One declared standard-field value as it travels from the
/// manifest to the resolved package model.  Mirrors the
/// `DependencySource::Workspace` contract: `cabin-manifest`
/// constructs `Declared` (literal) or `Workspace` (the
/// `{ workspace = true }` opt-in marker), `cabin-workspace`
/// rewrites every marker into `Inherited(value)` before any
/// consumer sees the `Package`, and a marker that survives past
/// the loader is a workspace invariant violation.  Marker
/// semantics deliberately split by consumer: `.is_some()`-based
/// relevance checks (`imposes_requirement`,
/// `find_standard_flag_conflicts`, `is_empty`) count an
/// unresolved marker as a declaration, while the `*_value()`
/// accessors treat it as absent - both cases are unreachable
/// post-loader under the rewrite invariant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StandardDeclaration<S> {
    /// Literal value written in this manifest → source `package`
    /// (or `target` for a target-level field).
    Declared(S),
    /// Unresolved `{ workspace = true }` opt-in marker.
    Workspace,
    /// Value resolved from the workspace root's `[workspace]`
    /// declaration → source `workspace`.
    Inherited(S),
}

impl<S> StandardDeclaration<S> {
    /// The resolved standard value.  `None` only for an unresolved
    /// marker, which must not reach consumers (debug-asserted).
    #[must_use]
    pub fn value(self) -> Option<S> {
        match self {
            Self::Declared(s) | Self::Inherited(s) => Some(s),
            Self::Workspace => {
                debug_assert!(
                    false,
                    "unresolved `{{ workspace = true }}` standard marker reached a consumer"
                );
                None
            }
        }
    }
}

// `Declared` and `Inherited` serialize as the bare value so the
// canonical-metadata / index wire format is identical to a literal
// declaration (publish bakes inherited values).  An unresolved
// marker must never reach a serialization boundary.
impl<S: Serialize> Serialize for StandardDeclaration<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: serde::Serializer,
    {
        match self {
            Self::Declared(s) | Self::Inherited(s) => s.serialize(serializer),
            Self::Workspace => Err(serde::ser::Error::custom(
                "unresolved `{ workspace = true }` standard marker cannot be serialized",
            )),
        }
    }
}

// A bare value deserializes as `Declared`: a consumer re-parsing
// published metadata sees a plain declaration.
impl<'de, S: Deserialize<'de>> Deserialize<'de> for StandardDeclaration<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        S::deserialize(deserializer).map(Self::Declared)
    }
}

/// The language fields shared by `[package]` and `[target.<name>]`:
/// the four standard fields (`c-standard` / `cxx-standard` /
/// `interface-c-standard` / `interface-cxx-standard`) plus the
/// `gnu-extensions` boolean.  At `[package]` level each standard
/// field may also be the `{ workspace = true }` opt-in marker;
/// target-level fields are always `Declared` (the parser rejects
/// markers there).  `gnu-extensions` is a plain boolean (no marker
/// form): target level overrides package level, defaulting to
/// `false`.  It selects GNU-extension compiler flag spellings only
/// and never participates in interface compatibility.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LanguageStandardSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub c_standard: Option<StandardDeclaration<CStandard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cxx_standard: Option<StandardDeclaration<CxxStandard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interface_c_standard: Option<StandardDeclaration<InterfaceRequirement<CStandard>>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interface_cxx_standard: Option<StandardDeclaration<InterfaceRequirement<CxxStandard>>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gnu_extensions: Option<bool>,
}

impl LanguageStandardSettings {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.c_standard.is_none()
            && self.cxx_standard.is_none()
            && self.interface_c_standard.is_none()
            && self.interface_cxx_standard.is_none()
            && self.gnu_extensions.is_none()
    }

    /// Resolved C implementation standard, when declared or
    /// inherited.
    #[must_use]
    pub fn c_standard_value(&self) -> Option<CStandard> {
        self.c_standard.and_then(StandardDeclaration::value)
    }

    /// Resolved C++ implementation standard, when declared or
    /// inherited.
    #[must_use]
    pub fn cxx_standard_value(&self) -> Option<CxxStandard> {
        self.cxx_standard.and_then(StandardDeclaration::value)
    }

    /// Resolved C interface requirement, when declared or inherited.
    #[must_use]
    pub fn interface_c_standard_value(&self) -> Option<InterfaceRequirement<CStandard>> {
        self.interface_c_standard
            .and_then(StandardDeclaration::value)
    }

    /// Resolved C++ interface requirement, when declared or
    /// inherited.
    #[must_use]
    pub fn interface_cxx_standard_value(&self) -> Option<InterfaceRequirement<CxxStandard>> {
        self.interface_cxx_standard
            .and_then(StandardDeclaration::value)
    }

    /// First field carrying the unresolved `{ workspace = true }`
    /// marker, for error reporting.
    #[must_use]
    pub fn workspace_marker_field(&self) -> Option<&'static str> {
        if self.c_standard == Some(StandardDeclaration::Workspace) {
            return Some("c-standard");
        }
        if self.cxx_standard == Some(StandardDeclaration::Workspace) {
            return Some("cxx-standard");
        }
        if self.interface_c_standard == Some(StandardDeclaration::Workspace) {
            return Some("interface-c-standard");
        }
        if self.interface_cxx_standard == Some(StandardDeclaration::Workspace) {
            return Some("interface-cxx-standard");
        }
        None
    }
}

/// Effective `gnu-extensions` value for one target: target override
/// â–¶ package â–¶ `false`.
#[must_use]
pub fn effective_gnu_extensions(package: &LanguageStandardSettings, target: &Target) -> bool {
    target
        .language
        .gnu_extensions
        .or(package.gnu_extensions)
        .unwrap_or(false)
}

/// Literal `[workspace]`-level standard default values that member
/// packages opt into per field with `<field> = { workspace = true }`
/// on `[package]`.  Plain values only - the opt-in marker is not
/// accepted on the `[workspace]` table itself.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct WorkspaceStandardDefaults {
    #[serde(rename = "c-standard", skip_serializing_if = "Option::is_none")]
    pub c_standard: Option<CStandard>,
    #[serde(rename = "cxx-standard", skip_serializing_if = "Option::is_none")]
    pub cxx_standard: Option<CxxStandard>,
    #[serde(
        rename = "interface-c-standard",
        skip_serializing_if = "Option::is_none"
    )]
    pub interface_c_standard: Option<InterfaceRequirement<CStandard>>,
    #[serde(
        rename = "interface-cxx-standard",
        skip_serializing_if = "Option::is_none"
    )]
    pub interface_cxx_standard: Option<InterfaceRequirement<CxxStandard>>,
}

impl WorkspaceStandardDefaults {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.c_standard.is_none()
            && self.cxx_standard.is_none()
            && self.interface_c_standard.is_none()
            && self.interface_cxx_standard.is_none()
    }
}

/// Provenance of an effective implementation standard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LanguageStandardSource {
    Package,
    Target,
    Workspace,
}

impl LanguageStandardSource {
    pub const fn as_key(self) -> &'static str {
        match self {
            Self::Package => "package",
            Self::Target => "target",
            Self::Workspace => "workspace",
        }
    }
}

/// Provenance of an effective interface standard.
/// `CompileStandard` marks the documented default: no interface
/// field was declared, so the requirement equals the target's
/// effective implementation standard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum InterfaceStandardSource {
    Target,
    Package,
    CompileStandard,
    Workspace,
}

impl InterfaceStandardSource {
    pub const fn as_key(self) -> &'static str {
        match self {
            Self::Target => "target",
            Self::Package => "package",
            Self::CompileStandard => "compile-standard",
            Self::Workspace => "workspace",
        }
    }
}

/// A resolved implementation standard plus where it came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedStandard<S> {
    pub standard: S,
    pub source: LanguageStandardSource,
}

/// A resolved interface requirement plus where it came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct InterfaceStandard<S> {
    pub requirement: InterfaceRequirement<S>,
    pub source: InterfaceStandardSource,
}

/// Package-level effective implementation standards.  `None` means
/// no declaration anywhere - there is no built-in default, and a
/// target that compiles the language without an effective standard
/// is rejected at manifest load.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedLanguageStandards {
    pub c: Option<ResolvedStandard<CStandard>>,
    pub cxx: Option<ResolvedStandard<CxxStandard>>,
}

/// Map a package-level declaration to its resolved standard and
/// provenance: literal → `package`, workspace-inherited →
/// `workspace`, absent (or an unresolved marker, debug-asserted
/// here) → `None`.
fn package_resolution<S: Copy>(
    declaration: Option<StandardDeclaration<S>>,
) -> Option<ResolvedStandard<S>> {
    match declaration {
        Some(StandardDeclaration::Declared(standard)) => Some(ResolvedStandard {
            standard,
            source: LanguageStandardSource::Package,
        }),
        Some(StandardDeclaration::Inherited(standard)) => Some(ResolvedStandard {
            standard,
            source: LanguageStandardSource::Workspace,
        }),
        Some(StandardDeclaration::Workspace) => {
            debug_assert!(
                false,
                "unresolved `{{ workspace = true }}` standard marker reached resolution"
            );
            None
        }
        None => None,
    }
}

/// Resolve the package-level effective standards from the
/// `[package]` declarations (literal or workspace-inherited).
#[must_use]
pub fn resolve_language_standards(package: &LanguageStandardSettings) -> ResolvedLanguageStandards {
    ResolvedLanguageStandards {
        c: package_resolution(package.c_standard),
        cxx: package_resolution(package.cxx_standard),
    }
}

/// Effective C implementation standard for one target:
/// target override â–¶ package (literal or workspace-inherited).
/// `None` when neither tier declares one.
#[must_use]
pub fn effective_c(
    package: &ResolvedLanguageStandards,
    target: &Target,
) -> Option<ResolvedStandard<CStandard>> {
    target
        .language
        .c_standard_value()
        .map_or(package.c, |standard| {
            Some(ResolvedStandard {
                standard,
                source: LanguageStandardSource::Target,
            })
        })
}

/// Effective C++ implementation standard for one target.
#[must_use]
pub fn effective_cxx(
    package: &ResolvedLanguageStandards,
    target: &Target,
) -> Option<ResolvedStandard<CxxStandard>> {
    target
        .language
        .cxx_standard_value()
        .map_or(package.cxx, |standard| {
            Some(ResolvedStandard {
                standard,
                source: LanguageStandardSource::Target,
            })
        })
}

/// Map a package-level *interface* declaration to its provenance:
/// literal → `package`, workspace-inherited → `workspace`.
fn interface_resolution<S: Copy>(
    declaration: Option<StandardDeclaration<InterfaceRequirement<S>>>,
) -> Option<InterfaceStandard<S>> {
    match declaration {
        Some(StandardDeclaration::Declared(requirement)) => Some(InterfaceStandard {
            requirement,
            source: InterfaceStandardSource::Package,
        }),
        Some(StandardDeclaration::Inherited(requirement)) => Some(InterfaceStandard {
            requirement,
            source: InterfaceStandardSource::Workspace,
        }),
        Some(StandardDeclaration::Workspace) => {
            debug_assert!(
                false,
                "unresolved `{{ workspace = true }}` standard marker reached resolution"
            );
            None
        }
        None => None,
    }
}

/// Effective C interface requirement for a library-like target:
/// target interface â–¶ package interface (literal or
/// workspace-inherited) â–¶ the target's effective implementation
/// standard, when one is declared (an interface may still default
/// from an explicit implementation standard).  `None` when no tier
/// yields a value.
#[must_use]
pub fn interface_c(
    package: &ResolvedLanguageStandards,
    package_settings: &LanguageStandardSettings,
    target: &Target,
) -> Option<InterfaceStandard<CStandard>> {
    if let Some(requirement) = target.language.interface_c_standard_value() {
        return Some(InterfaceStandard {
            requirement,
            source: InterfaceStandardSource::Target,
        });
    }
    if let Some(interface) = interface_resolution(package_settings.interface_c_standard) {
        return Some(interface);
    }
    effective_c(package, target).map(|resolved| InterfaceStandard {
        requirement: InterfaceRequirement::Requirement(StandardRequirement {
            min: resolved.standard,
            max: None,
        }),
        source: InterfaceStandardSource::CompileStandard,
    })
}

/// Effective C++ interface requirement for a library-like target.
#[must_use]
pub fn interface_cxx(
    package: &ResolvedLanguageStandards,
    package_settings: &LanguageStandardSettings,
    target: &Target,
) -> Option<InterfaceStandard<CxxStandard>> {
    if let Some(requirement) = target.language.interface_cxx_standard_value() {
        return Some(InterfaceStandard {
            requirement,
            source: InterfaceStandardSource::Target,
        });
    }
    if let Some(interface) = interface_resolution(package_settings.interface_cxx_standard) {
        return Some(interface);
    }
    effective_cxx(package, target).map(|resolved| InterfaceStandard {
        requirement: InterfaceRequirement::Requirement(StandardRequirement {
            min: resolved.standard,
            max: None,
        }),
        source: InterfaceStandardSource::CompileStandard,
    })
}

/// Whether a dependency target imposes an interface requirement for
/// `language` on its consumers.  A language is relevant when the
/// target has sources of that language, declares a target-level
/// field for it (implementation or interface), or is header-only
/// while the package declares a package-level *interface* standard
/// for it.  Package-level implementation defaults never create
/// relevance by themselves.
#[must_use]
pub fn imposes_requirement(
    target: &Target,
    package_settings: &LanguageStandardSettings,
    language: SourceLanguage,
) -> bool {
    let has_sources = target
        .sources
        .iter()
        .any(|s| classify_source(s) == Some(language));
    let target_declares = match language {
        SourceLanguage::C => {
            target.language.c_standard.is_some() || target.language.interface_c_standard.is_some()
        }
        SourceLanguage::Cxx => {
            target.language.cxx_standard.is_some()
                || target.language.interface_cxx_standard.is_some()
        }
    };
    let header_only_package_interface = target.kind.is_header_only()
        && match language {
            SourceLanguage::C => package_settings.interface_c_standard.is_some(),
            SourceLanguage::Cxx => package_settings.interface_cxx_standard.is_some(),
        };
    has_sources || target_declares || header_only_package_interface
}

/// Token prefixes that select a language standard inside an
/// escape-hatch flag list.
pub const STANDARD_FLAG_PREFIXES: [&str; 3] = ["-std=", "--std=", "/std:"];

/// A first-class standard declaration conflicting with an explicit
/// standard flag in the same package's manifest-derived flags.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[error(
    "package `{package}` declares a first-class {} standard (`{field}`) but its `{flag_list}` also select one via `{flag}`; remove the flag, or drop the `{field}` declaration and keep the raw flag",
    .language.human_label()
)]
pub struct StandardFlagConflict {
    pub package: String,
    pub language: SourceLanguage,
    /// The manifest field family that was declared (`c-standard` or
    /// `cxx-standard`, at package or target level).
    pub field: &'static str,
    /// The flag list carrying the conflicting token (`cflags` or
    /// `cxxflags`).
    pub flag_list: &'static str,
    pub flag: String,
    /// Scope of the conflicting declaration: `Some(target)` when a
    /// target-level field created it (the ambiguity exists only on
    /// that target's compiles), `None` when the package-level field
    /// did (every compile of the language is ambiguous).  The build
    /// planner uses the scope to surface a conflict only when a
    /// matching compile is planned.
    pub target: Option<String>,
}

fn first_standard_token(flags: &[String]) -> Option<String> {
    flags
        .iter()
        .find(|f| STANDARD_FLAG_PREFIXES.iter().any(|p| f.starts_with(p)))
        .cloned()
}

/// Detect the documented conflict candidates: an explicit
/// first-class implementation standard declaration (package or
/// target level) for a language whose manifest-derived flag list
/// also pins a standard.  Runs on resolved flags *before* env /
/// pkg-config augmentation so `CFLAGS` / `CXXFLAGS` remain exempt.
///
/// These are *candidates*, scoped per declaration: the build
/// planner surfaces one only when a compile its scope covers is
/// planned, so an unbuilt sibling target's declaration
/// never gates a command that does not compile it.
#[must_use]
pub fn find_standard_flag_conflicts(
    package: &str,
    settings: &LanguageStandardSettings,
    targets: &[Target],
    flags: &ResolvedProfileFlags,
) -> Vec<StandardFlagConflict> {
    let mut out = Vec::new();
    // C and C++ follow identical conflict logic; only the language,
    // field / flag-list names, and standard declarations differ.
    let mut check = |language: SourceLanguage,
                     field: &'static str,
                     flag_list: &'static str,
                     list: &[String],
                     package_declares: bool,
                     target_declares: fn(&Target) -> bool| {
        let Some(flag) = first_standard_token(list) else {
            return;
        };
        let mut push = |flag: String, target: Option<String>| {
            out.push(StandardFlagConflict {
                package: package.to_owned(),
                language,
                field,
                flag_list,
                flag,
                target,
            });
        };
        if package_declares {
            push(flag, None);
        } else {
            for target in targets {
                if target_declares(target) {
                    push(flag.clone(), Some(target.name.as_str().to_owned()));
                }
            }
        }
    };
    check(
        SourceLanguage::C,
        "c-standard",
        "cflags",
        &flags.cflags,
        settings.c_standard.is_some(),
        |target| target.language.c_standard.is_some(),
    );
    check(
        SourceLanguage::Cxx,
        "cxx-standard",
        "cxxflags",
        &flags.cxxflags,
        settings.cxx_standard.is_some(),
        |target| target.language.cxx_standard.is_some(),
    );
    out
}

/// A target whose declared interface minimum is newer than the
/// implementation standard its own sources compile with - a
/// manifest contradiction, rejected at load.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[error(
    "target `{target}` in package `{package}` sets `{field} = \"{interface_min}\"` but compiles its {} sources as `{implementation}`; the target's own translation units could not include its own public headers - raise `{}` or lower the interface minimum",
    .language.human_label(),
    implementation_field(*.language)
)]
pub struct InterfaceStandardContradiction {
    pub package: String,
    pub target: String,
    pub language: SourceLanguage,
    /// The interface field family that was declared
    /// (`interface-c-standard` or `interface-cxx-standard`).
    pub field: &'static str,
    pub implementation: LanguageStandard,
    pub interface_min: LanguageStandard,
}

/// Detect interface/implementation contradictions: for each
/// library-like target and language it compiles, the effective
/// interface minimum must not be newer than the effective
/// implementation standard (the target's own translation units
/// include its own public headers).  Runs on resolved declarations,
/// after workspace-marker resolution.  The compile-standard
/// interface fallback equals the implementation standard, so it can
/// never contradict.
#[must_use]
pub fn find_interface_standard_contradictions(
    package: &crate::Package,
) -> Vec<InterfaceStandardContradiction> {
    let resolved = resolve_language_standards(&package.language);
    let mut out = Vec::new();
    for target in &package.targets {
        let library_like = target.kind.is_library_like();
        if !library_like {
            continue;
        }
        let compiles = |language: SourceLanguage| {
            target
                .sources
                .iter()
                .any(|s| classify_source(s) == Some(language))
        };
        if compiles(SourceLanguage::C)
            && let (Some(implementation), Some(interface)) = (
                effective_c(&resolved, target),
                interface_c(&resolved, &package.language, target),
            )
            && let Some(min) = interface.requirement.min()
            && min > implementation.standard
        {
            out.push(InterfaceStandardContradiction {
                package: package.name.as_str().to_owned(),
                target: target.name.as_str().to_owned(),
                language: SourceLanguage::C,
                field: "interface-c-standard",
                implementation: LanguageStandard::C(implementation.standard),
                interface_min: LanguageStandard::C(min),
            });
        }
        if compiles(SourceLanguage::Cxx)
            && let (Some(implementation), Some(interface)) = (
                effective_cxx(&resolved, target),
                interface_cxx(&resolved, &package.language, target),
            )
            && let Some(min) = interface.requirement.min()
            && min > implementation.standard
        {
            out.push(InterfaceStandardContradiction {
                package: package.name.as_str().to_owned(),
                target: target.name.as_str().to_owned(),
                language: SourceLanguage::Cxx,
                field: "interface-cxx-standard",
                implementation: LanguageStandard::Cxx(implementation.standard),
                interface_min: LanguageStandard::Cxx(min),
            });
        }
    }
    out
}

/// Per-package language-standard summary carried by
/// `BuildConfiguration`: package-level effective standards plus the
/// effective values for every target.  Values (not provenance) feed
/// the fingerprint; the whole struct feeds `cabin metadata` /
/// `cabin explain build-config`.  Absent entries mean the language
/// has no declared standard anywhere for that scope.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LanguageStandardsSummary {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub c: Option<ResolvedStandard<CStandard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cxx: Option<ResolvedStandard<CxxStandard>>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub targets: BTreeMap<String, TargetStandardsSummary>,
}

/// Effective standards for one target.  Interface entries are
/// present only for `library` / `header-only` kinds.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TargetStandardsSummary {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub c: Option<ResolvedStandard<CStandard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cxx: Option<ResolvedStandard<CxxStandard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interface_c: Option<InterfaceStandard<CStandard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interface_cxx: Option<InterfaceStandard<CxxStandard>>,
    /// Effective `gnu-extensions` value (target â–¶ package â–¶
    /// `false`).  Omitted from the serialized form when `false`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub gnu_extensions: bool,
}

impl LanguageStandardsSummary {
    /// Compute the summary from a package's declarations.
    #[must_use]
    pub fn from_package(package: &crate::Package) -> Self {
        let resolved = resolve_language_standards(&package.language);
        let targets = package
            .targets
            .iter()
            .map(|target| {
                let library_like = target.kind.is_library_like();
                let summary = TargetStandardsSummary {
                    c: effective_c(&resolved, target),
                    cxx: effective_cxx(&resolved, target),
                    interface_c: library_like
                        .then(|| interface_c(&resolved, &package.language, target))
                        .flatten(),
                    interface_cxx: library_like
                        .then(|| interface_cxx(&resolved, &package.language, target))
                        .flatten(),
                    gnu_extensions: effective_gnu_extensions(&package.language, target),
                };
                (target.name.as_str().to_owned(), summary)
            })
            .collect();
        Self {
            c: resolved.c,
            cxx: resolved.cxx,
            targets,
        }
    }

    /// Stable line serialization for the build-configuration
    /// fingerprint.  Values only - provenance must not move the
    /// fingerprint, and absent standards (and the default
    /// `gnu-extensions = false`) contribute no line.
    #[must_use]
    pub fn fingerprint_lines(&self) -> Vec<String> {
        let mut lines = Vec::new();
        if let Some(resolved) = &self.c {
            lines.push(format!("c={}", resolved.standard));
        }
        if let Some(resolved) = &self.cxx {
            lines.push(format!("cxx={}", resolved.standard));
        }
        for (name, target) in &self.targets {
            lines.push(format!("target={name}"));
            if let Some(resolved) = &target.c {
                lines.push(format!("c={}", resolved.standard));
            }
            if let Some(resolved) = &target.cxx {
                lines.push(format!("cxx={}", resolved.standard));
            }
            if let Some(interface) = &target.interface_c {
                lines.push(format!("interface-c={}", interface.requirement));
            }
            if let Some(interface) = &target.interface_cxx {
                lines.push(format!("interface-cxx={}", interface.requirement));
            }
            if target.gnu_extensions {
                lines.push("gnu-extensions=true".to_owned());
            }
        }
        lines
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{TargetKind, TargetName};
    use camino::Utf8PathBuf;

    fn target(kind: TargetKind, sources: &[&str], language: LanguageStandardSettings) -> Target {
        Target {
            name: TargetName::new("t").unwrap(),
            kind,
            sources: sources.iter().map(Utf8PathBuf::from).collect(),
            include_dirs: Vec::new(),
            defines: Vec::new(),
            deps: Vec::new(),
            required_features: Vec::new(),
            language,
        }
    }

    fn requirement<S>(min: S) -> InterfaceRequirement<S> {
        InterfaceRequirement::Requirement(StandardRequirement { min, max: None })
    }

    #[test]
    fn every_accepted_identifier_parses_and_round_trips() {
        for s in CStandard::ALL {
            assert_eq!(CStandard::parse(s.as_str()).unwrap(), s);
        }
        for s in CxxStandard::ALL {
            assert_eq!(CxxStandard::parse(s.as_str()).unwrap(), s);
        }
    }

    #[test]
    fn aliases_normalize_immediately() {
        assert_eq!(CStandard::parse("c90").unwrap(), CStandard::C89);
        assert_eq!(CxxStandard::parse("c++03").unwrap(), CxxStandard::Cxx98);
        // The alias never survives as a spelling of its own.
        assert_eq!(CStandard::parse("c90").unwrap().as_str(), "c89");
        assert_eq!(CxxStandard::parse("c++03").unwrap().as_str(), "c++98");
    }

    #[test]
    fn unknown_values_list_the_accepted_identifiers() {
        let err = CStandard::parse("c++17").unwrap_err();
        assert_eq!(
            err.to_string(),
            "unknown C standard `c++17`: expected one of c89, c99, c11, c17, c23"
        );
        let err = CxxStandard::parse("c++29").unwrap_err();
        assert_eq!(
            err.to_string(),
            "unknown C++ standard `c++29`: expected one of c++98, c++11, c++14, c++17, c++20, c++23, c++26"
        );
    }

    #[test]
    fn gnu_spellings_are_ordinary_unknown_values() {
        for value in ["gnu89", "gnu99", "gnu11", "gnu17", "gnu23", "gnu90"] {
            let err = CStandard::parse(value).unwrap_err();
            assert!(
                matches!(&err, LanguageStandardParseError::Unknown { value: v, .. } if v == value),
                "unexpected error for {value}: {err}"
            );
            // No special-cased hint: gnu spellings are unknown
            // values like any other.
            assert!(!err.to_string().contains("gnu-extensions"));
        }
        for value in [
            "gnu++98", "gnu++03", "gnu++11", "gnu++14", "gnu++17", "gnu++20", "gnu++23", "gnu++26",
        ] {
            let err = CxxStandard::parse(value).unwrap_err();
            assert!(
                matches!(&err, LanguageStandardParseError::Unknown { value: v, .. } if v == value),
                "unexpected error for {value}: {err}"
            );
            assert!(!err.to_string().contains("gnu-extensions"));
        }
    }

    #[test]
    fn range_like_values_get_the_reserved_diagnostic() {
        for value in [">=c11", "<=c17", ">c99", "<c23", "c11,c17", "c11, c17"] {
            let err = CStandard::parse(value).unwrap_err();
            assert!(
                matches!(err, LanguageStandardParseError::RangeReserved { .. }),
                "expected reserved-range error for {value}, got: {err}"
            );
            assert!(err.to_string().contains("reserved for a future version"));
        }
        for value in [">=c++17", "<=c++20", ">c++11", "<c++23", "c++17,c++20"] {
            let err = CxxStandard::parse(value).unwrap_err();
            assert!(
                matches!(err, LanguageStandardParseError::RangeReserved { .. }),
                "expected reserved-range error for {value}, got: {err}"
            );
        }
        // The interface parsers share the same rejection.
        assert!(matches!(
            parse_interface_c(">=c11").unwrap_err(),
            LanguageStandardParseError::RangeReserved { .. }
        ));
        assert!(matches!(
            parse_interface_cxx(">=c++17").unwrap_err(),
            LanguageStandardParseError::RangeReserved { .. }
        ));
    }

    #[test]
    fn none_is_interface_only() {
        assert_eq!(
            parse_interface_c("none").unwrap(),
            InterfaceRequirement::None
        );
        assert_eq!(
            parse_interface_cxx("none").unwrap(),
            InterfaceRequirement::None
        );
        let err = CStandard::parse("none").unwrap_err();
        assert!(
            matches!(err, LanguageStandardParseError::NoneOnImplementation { .. }),
            "expected misplaced-none error, got: {err}"
        );
        assert!(err.to_string().contains("interface-c-standard"));
        let err = CxxStandard::parse("none").unwrap_err();
        assert!(matches!(
            err,
            LanguageStandardParseError::NoneOnImplementation { .. }
        ));
    }

    #[test]
    fn interface_parsers_accept_every_identifier_and_alias() {
        for s in CStandard::ALL {
            assert_eq!(parse_interface_c(s.as_str()).unwrap(), requirement(s));
        }
        for s in CxxStandard::ALL {
            assert_eq!(parse_interface_cxx(s.as_str()).unwrap(), requirement(s));
        }
        assert_eq!(
            parse_interface_c("c90").unwrap(),
            requirement(CStandard::C89)
        );
        assert_eq!(
            parse_interface_cxx("c++03").unwrap(),
            requirement(CxxStandard::Cxx98)
        );
    }

    #[test]
    fn standards_order_chronologically() {
        assert!(CStandard::C89 < CStandard::C99);
        assert!(CStandard::C99 < CStandard::C11);
        assert!(CStandard::C11 < CStandard::C17);
        assert!(CStandard::C17 < CStandard::C23);
        assert!(CxxStandard::Cxx98 < CxxStandard::Cxx11);
        assert!(CxxStandard::Cxx11 < CxxStandard::Cxx14);
        assert!(CxxStandard::Cxx14 < CxxStandard::Cxx17);
        assert!(CxxStandard::Cxx17 < CxxStandard::Cxx20);
        assert!(CxxStandard::Cxx20 < CxxStandard::Cxx23);
        assert!(CxxStandard::Cxx23 < CxxStandard::Cxx26);
    }

    #[test]
    fn msvc_spellings_cover_exactly_the_stable_flags() {
        assert_eq!(
            LanguageStandard::Cxx(CxxStandard::Cxx20).msvc_spelling(),
            Some("/std:c++20")
        );
        assert_eq!(
            LanguageStandard::C(CStandard::C17).msvc_spelling(),
            Some("/std:c17")
        );
        assert_eq!(LanguageStandard::C(CStandard::C99).msvc_spelling(), None);
        assert_eq!(
            LanguageStandard::Cxx(CxxStandard::Cxx23).msvc_spelling(),
            None
        );
        assert_eq!(
            LanguageStandard::Cxx(CxxStandard::Cxx26).msvc_spelling(),
            None
        );
        assert_eq!(
            LanguageStandard::Cxx(CxxStandard::Cxx11).msvc_spelling(),
            None
        );
    }

    #[test]
    fn standard_requirement_serde_round_trips_preserving_max() {
        let min_only = StandardRequirement {
            min: CxxStandard::Cxx17,
            max: None,
        };
        let json = serde_json::to_string(&min_only).unwrap();
        // `max` stays in the serialized form even while reserved.
        assert_eq!(json, r#"{"min":"c++17","max":null}"#);
        let parsed: StandardRequirement<CxxStandard> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, min_only);

        let with_max = StandardRequirement {
            min: CStandard::C11,
            max: Some(CStandard::C17),
        };
        let json = serde_json::to_string(&with_max).unwrap();
        assert_eq!(json, r#"{"min":"c11","max":"c17"}"#);
        let parsed: StandardRequirement<CStandard> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, with_max);

        // A missing `max` still deserializes (as unpopulated).
        let parsed: StandardRequirement<CStandard> =
            serde_json::from_str(r#"{"min":"c11"}"#).unwrap();
        assert_eq!(parsed.max, None);
        // Unknown future range syntax falls through
        // `deny_unknown_fields`.
        assert!(
            serde_json::from_str::<StandardRequirement<CStandard>>(
                r#"{"min":"c11","exact":"c17"}"#
            )
            .is_err()
        );
    }

    #[test]
    fn interface_requirement_serde_round_trips() {
        let none: InterfaceRequirement<CxxStandard> = InterfaceRequirement::None;
        let json = serde_json::to_string(&none).unwrap();
        assert_eq!(json, "\"none\"");
        let parsed: InterfaceRequirement<CxxStandard> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, none);

        let req = requirement(CxxStandard::Cxx20);
        let json = serde_json::to_string(&req).unwrap();
        assert_eq!(json, r#"{"min":"c++20","max":null}"#);
        let parsed: InterfaceRequirement<CxxStandard> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, req);

        // A bare standard string is not a serialized requirement.
        assert!(serde_json::from_str::<InterfaceRequirement<CxxStandard>>("\"c++20\"").is_err());
    }

    #[test]
    fn interface_requirement_displays_min_max_and_none() {
        assert_eq!(
            InterfaceRequirement::<CxxStandard>::None.to_string(),
            "none"
        );
        assert_eq!(requirement(CxxStandard::Cxx17).to_string(), "c++17");
        assert_eq!(
            InterfaceRequirement::Requirement(StandardRequirement {
                min: CStandard::C11,
                max: Some(CStandard::C17),
            })
            .to_string(),
            "c11..c17"
        );
    }

    #[test]
    fn gnu_extensions_default_false_with_target_over_package() {
        let plain = target(
            TargetKind::Executable,
            &["a.cc"],
            LanguageStandardSettings::default(),
        );
        let none = LanguageStandardSettings::default();
        assert!(!effective_gnu_extensions(&none, &plain));

        let package_on = LanguageStandardSettings {
            gnu_extensions: Some(true),
            ..Default::default()
        };
        assert!(effective_gnu_extensions(&package_on, &plain));

        let target_off = target(
            TargetKind::Executable,
            &["a.cc"],
            LanguageStandardSettings {
                gnu_extensions: Some(false),
                ..Default::default()
            },
        );
        assert!(!effective_gnu_extensions(&package_on, &target_off));

        let target_on = target(
            TargetKind::Executable,
            &["a.cc"],
            LanguageStandardSettings {
                gnu_extensions: Some(true),
                ..Default::default()
            },
        );
        assert!(effective_gnu_extensions(&none, &target_on));
    }

    #[test]
    fn effective_standard_prefers_target_then_package_then_none() {
        let undeclared = resolve_language_standards(&LanguageStandardSettings::default());
        let plain = target(
            TargetKind::Executable,
            &["a.cc"],
            LanguageStandardSettings::default(),
        );
        assert_eq!(effective_cxx(&undeclared, &plain), None);
        assert_eq!(effective_c(&undeclared, &plain), None);

        let package = resolve_language_standards(&LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx14)),
            ..Default::default()
        });
        let effective = effective_cxx(&package, &plain).unwrap();
        assert_eq!(effective.standard, CxxStandard::Cxx14);
        assert_eq!(effective.source, LanguageStandardSource::Package);
        // A declared C++ standard yields no effective C standard.
        assert_eq!(effective_c(&package, &plain), None);

        let overridden = target(
            TargetKind::Executable,
            &["a.cc"],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                ..Default::default()
            },
        );
        let effective = effective_cxx(&package, &overridden).unwrap();
        assert_eq!(effective.standard, CxxStandard::Cxx20);
        assert_eq!(effective.source, LanguageStandardSource::Target);
    }

    #[test]
    fn interface_standard_falls_back_to_explicit_compile_standard_or_none() {
        let package_settings = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
            ..Default::default()
        };
        let resolved = resolve_language_standards(&package_settings);
        let lib = target(
            TargetKind::Library,
            &["a.cc"],
            LanguageStandardSettings::default(),
        );
        let interface = interface_cxx(&resolved, &package_settings, &lib).unwrap();
        assert_eq!(interface.requirement, requirement(CxxStandard::Cxx20));
        assert_eq!(interface.source, InterfaceStandardSource::CompileStandard);
        // No implementation or interface standard anywhere: no
        // interface value either (there is no built-in default).
        let undeclared = LanguageStandardSettings::default();
        let resolved_undeclared = resolve_language_standards(&undeclared);
        assert_eq!(interface_cxx(&resolved_undeclared, &undeclared, &lib), None);
        assert_eq!(interface_c(&resolved_undeclared, &undeclared, &lib), None);

        let package_interface = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
            interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                CxxStandard::Cxx17,
            ))),
            ..Default::default()
        };
        let resolved = resolve_language_standards(&package_interface);
        let interface = interface_cxx(&resolved, &package_interface, &lib).unwrap();
        assert_eq!(interface.requirement, requirement(CxxStandard::Cxx17));
        assert_eq!(interface.source, InterfaceStandardSource::Package);

        let lib_override = target(
            TargetKind::Library,
            &["a.cc"],
            LanguageStandardSettings {
                interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                    CxxStandard::Cxx14,
                ))),
                ..Default::default()
            },
        );
        let interface = interface_cxx(&resolved, &package_interface, &lib_override).unwrap();
        assert_eq!(interface.requirement, requirement(CxxStandard::Cxx14));
        assert_eq!(interface.source, InterfaceStandardSource::Target);
    }

    #[test]
    fn declared_none_interface_survives_resolution() {
        let package_settings = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
            ..Default::default()
        };
        let resolved = resolve_language_standards(&package_settings);
        let lib = target(
            TargetKind::Library,
            &["a.cc"],
            LanguageStandardSettings {
                interface_cxx_standard: Some(StandardDeclaration::Declared(
                    InterfaceRequirement::None,
                )),
                ..Default::default()
            },
        );
        let interface = interface_cxx(&resolved, &package_settings, &lib).unwrap();
        assert_eq!(interface.requirement, InterfaceRequirement::None);
        assert_eq!(interface.source, InterfaceStandardSource::Target);
        assert_eq!(interface.requirement.min(), None);
    }

    #[test]
    fn imposes_requirement_relevance_rules() {
        let none = LanguageStandardSettings::default();
        // A pure-C library imposes no C++ requirement.
        let c_lib = target(
            TargetKind::Library,
            &["a.c"],
            LanguageStandardSettings::default(),
        );
        assert!(imposes_requirement(&c_lib, &none, SourceLanguage::C));
        assert!(!imposes_requirement(&c_lib, &none, SourceLanguage::Cxx));

        // A package-level *implementation* default alone creates no
        // relevance for a target without that language.
        let package_impl = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
            ..Default::default()
        };
        assert!(!imposes_requirement(
            &c_lib,
            &package_impl,
            SourceLanguage::Cxx
        ));

        // A target-level field (implementation or interface) does.
        let declared = target(
            TargetKind::Library,
            &["a.c"],
            LanguageStandardSettings {
                interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                    CxxStandard::Cxx17,
                ))),
                ..Default::default()
            },
        );
        assert!(imposes_requirement(&declared, &none, SourceLanguage::Cxx));

        // Header-only + package-level *interface* standard does.
        let header_only = target(
            TargetKind::HeaderOnly,
            &[],
            LanguageStandardSettings::default(),
        );
        assert!(!imposes_requirement(
            &header_only,
            &none,
            SourceLanguage::Cxx
        ));
        let package_interface = LanguageStandardSettings {
            interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                CxxStandard::Cxx20,
            ))),
            ..Default::default()
        };
        assert!(imposes_requirement(
            &header_only,
            &package_interface,
            SourceLanguage::Cxx
        ));
        // ... but not via a package-level implementation default.
        assert!(!imposes_requirement(
            &header_only,
            &package_impl,
            SourceLanguage::Cxx
        ));
    }

    #[test]
    fn conflict_fires_only_for_declared_language_and_matching_bucket() {
        let flags = ResolvedProfileFlags {
            cxxflags: vec!["-std=c++14".to_owned()],
            ..Default::default()
        };
        let declared_cxx = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
            ..Default::default()
        };

        // Nothing declared: never a conflict.
        assert!(
            find_standard_flag_conflicts("p", &LanguageStandardSettings::default(), &[], &flags)
                .is_empty()
        );

        // Declared C++ + `-std=` in cxxflags: a package-scoped
        // conflict candidate.
        let conflicts = find_standard_flag_conflicts("p", &declared_cxx, &[], &flags);
        let conflict = conflicts.first().unwrap();
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflict.language, SourceLanguage::Cxx);
        assert_eq!(conflict.flag, "-std=c++14");
        assert_eq!(conflict.field, "cxx-standard");
        assert_eq!(conflict.target, None);
        assert!(conflict.to_string().contains("cxx-standard"));

        // Declared C++ + `-std=` in cflags only: no conflict.
        let c_only_flags = ResolvedProfileFlags {
            cflags: vec!["-std=c99".to_owned()],
            ..Default::default()
        };
        assert!(find_standard_flag_conflicts("p", &declared_cxx, &[], &c_only_flags).is_empty());

        // A target-level declaration counts as declared.
        let t = target(
            TargetKind::Executable,
            &["a.c"],
            LanguageStandardSettings {
                c_standard: Some(StandardDeclaration::Declared(CStandard::C17)),
                ..Default::default()
            },
        );
        let conflicts = find_standard_flag_conflicts(
            "p",
            &LanguageStandardSettings::default(),
            std::slice::from_ref(&t),
            &c_only_flags,
        );
        let conflict = conflicts.first().unwrap();
        assert_eq!(conflict.language, SourceLanguage::C);
        assert_eq!(conflict.flag_list, "cflags");
        // A target-level declaration scopes the candidate to that
        // target so the planner only surfaces it when the target's
        // compile is planned.
        assert_eq!(conflict.target.as_deref(), Some("t"));

        // `/std:` and `--std=` prefixes are recognized too.
        let msvc_flags = ResolvedProfileFlags {
            cxxflags: vec!["/std:c++latest".to_owned()],
            ..Default::default()
        };
        assert!(!find_standard_flag_conflicts("p", &declared_cxx, &[], &msvc_flags).is_empty());
    }

    fn package_with(targets: Vec<Target>, language: LanguageStandardSettings) -> crate::Package {
        use crate::{Package, PackageName};
        Package::new(
            PackageName::new("demo").unwrap(),
            semver::Version::parse("0.1.0").unwrap(),
            targets,
            Vec::new(),
        )
        .unwrap()
        .with_language(language)
    }

    #[test]
    fn contradiction_fires_when_interface_minimum_exceeds_implementation() {
        // Target-level interface newer than the package
        // implementation standard the target compiles with.
        let lib = target(
            TargetKind::Library,
            &["a.cc"],
            LanguageStandardSettings {
                interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                    CxxStandard::Cxx20,
                ))),
                ..Default::default()
            },
        );
        let package = package_with(
            vec![lib],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                ..Default::default()
            },
        );
        let contradictions = find_interface_standard_contradictions(&package);
        assert_eq!(contradictions.len(), 1);
        let contradiction = &contradictions[0];
        assert_eq!(contradiction.target, "t");
        assert_eq!(contradiction.field, "interface-cxx-standard");
        assert_eq!(
            contradiction.implementation,
            LanguageStandard::Cxx(CxxStandard::Cxx17)
        );
        assert_eq!(
            contradiction.interface_min,
            LanguageStandard::Cxx(CxxStandard::Cxx20)
        );
        let message = contradiction.to_string();
        assert!(
            message.contains("could not include its own public headers"),
            "message must state the reason plainly: {message}"
        );

        // Same shape on the C side, via package-level interface.
        let c_lib = target(
            TargetKind::Library,
            &["a.c"],
            LanguageStandardSettings::default(),
        );
        let package = package_with(
            vec![c_lib],
            LanguageStandardSettings {
                c_standard: Some(StandardDeclaration::Declared(CStandard::C11)),
                interface_c_standard: Some(StandardDeclaration::Declared(requirement(
                    CStandard::C23,
                ))),
                ..Default::default()
            },
        );
        let contradictions = find_interface_standard_contradictions(&package);
        assert_eq!(contradictions.len(), 1);
        assert_eq!(contradictions[0].field, "interface-c-standard");
    }

    #[test]
    fn contradiction_ignores_equal_older_none_and_non_compiling_targets() {
        // Interface at or below the implementation standard is fine.
        for interface in [CxxStandard::Cxx17, CxxStandard::Cxx14] {
            let lib = target(
                TargetKind::Library,
                &["a.cc"],
                LanguageStandardSettings {
                    interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                        interface,
                    ))),
                    ..Default::default()
                },
            );
            let package = package_with(
                vec![lib],
                LanguageStandardSettings {
                    cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                    ..Default::default()
                },
            );
            assert!(find_interface_standard_contradictions(&package).is_empty());
        }

        // `none` imposes no minimum, so it cannot contradict.
        let lib = target(
            TargetKind::Library,
            &["a.cc"],
            LanguageStandardSettings {
                interface_cxx_standard: Some(StandardDeclaration::Declared(
                    InterfaceRequirement::None,
                )),
                ..Default::default()
            },
        );
        let package = package_with(
            vec![lib],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                ..Default::default()
            },
        );
        assert!(find_interface_standard_contradictions(&package).is_empty());

        // A header-only target has no translation units, so a newer
        // interface minimum is not a contradiction.
        let header_only = target(
            TargetKind::HeaderOnly,
            &[],
            LanguageStandardSettings::default(),
        );
        let package = package_with(
            vec![header_only],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                    CxxStandard::Cxx20,
                ))),
                ..Default::default()
            },
        );
        assert!(find_interface_standard_contradictions(&package).is_empty());

        // A pure-C library with a newer C++ interface minimum has no
        // C++ translation units of its own.
        let c_lib = target(
            TargetKind::Library,
            &["a.c"],
            LanguageStandardSettings {
                interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                    CxxStandard::Cxx26,
                ))),
                ..Default::default()
            },
        );
        let package = package_with(
            vec![c_lib],
            LanguageStandardSettings {
                c_standard: Some(StandardDeclaration::Declared(CStandard::C11)),
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                ..Default::default()
            },
        );
        assert!(find_interface_standard_contradictions(&package).is_empty());

        // Executables never carry interface requirements.
        let exe = target(
            TargetKind::Executable,
            &["a.cc"],
            LanguageStandardSettings::default(),
        );
        let package = package_with(
            vec![exe],
            LanguageStandardSettings {
                cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
                interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                    CxxStandard::Cxx20,
                ))),
                ..Default::default()
            },
        );
        assert!(find_interface_standard_contradictions(&package).is_empty());
    }

    #[test]
    fn summary_lists_every_target_with_interface_only_for_library_like() {
        use crate::{Package, PackageName};
        let package = Package::new(
            PackageName::new("demo").unwrap(),
            semver::Version::parse("0.1.0").unwrap(),
            vec![
                target(
                    TargetKind::Executable,
                    &["main.cc"],
                    LanguageStandardSettings::default(),
                ),
                Target {
                    name: TargetName::new("core").unwrap(),
                    kind: TargetKind::Library,
                    sources: vec![Utf8PathBuf::from("core.cc")],
                    include_dirs: Vec::new(),
                    defines: Vec::new(),
                    deps: Vec::new(),
                    required_features: Vec::new(),
                    language: LanguageStandardSettings {
                        cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
                        interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                            CxxStandard::Cxx17,
                        ))),
                        gnu_extensions: Some(true),
                        ..Default::default()
                    },
                },
            ],
            Vec::new(),
        )
        .unwrap()
        .with_language(LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx17)),
            ..Default::default()
        });
        let summary = LanguageStandardsSummary::from_package(&package);
        assert_eq!(summary.cxx.unwrap().standard, CxxStandard::Cxx17);
        assert_eq!(summary.c, None);
        assert_eq!(summary.targets.len(), 2);
        let exe = &summary.targets["t"];
        assert!(exe.interface_c.is_none() && exe.interface_cxx.is_none());
        assert!(!exe.gnu_extensions);
        let core = &summary.targets["core"];
        assert_eq!(core.cxx.unwrap().standard, CxxStandard::Cxx20);
        assert_eq!(
            core.interface_cxx.unwrap().requirement,
            requirement(CxxStandard::Cxx17)
        );
        assert!(core.gnu_extensions);
        // No C standard is declared anywhere, so the library gets
        // no C interface entry either.
        assert_eq!(core.interface_c, None);
    }

    #[test]
    fn package_level_interface_fields_are_inert_without_library_like_targets() {
        use crate::{Package, PackageName};
        // docs/language-standards.md: package-level interface fields
        // are "allowed, and inert, in packages without any"
        // library-like target - the summary must not attach them to
        // executables.
        let package = Package::new(
            PackageName::new("demo").unwrap(),
            semver::Version::parse("0.1.0").unwrap(),
            vec![target(
                TargetKind::Executable,
                &["main.cc"],
                LanguageStandardSettings::default(),
            )],
            Vec::new(),
        )
        .unwrap()
        .with_language(LanguageStandardSettings {
            interface_c_standard: Some(StandardDeclaration::Declared(requirement(CStandard::C17))),
            interface_cxx_standard: Some(StandardDeclaration::Declared(requirement(
                CxxStandard::Cxx20,
            ))),
            ..Default::default()
        });
        let summary = LanguageStandardsSummary::from_package(&package);
        let exe = &summary.targets["t"];
        assert!(
            exe.interface_c.is_none() && exe.interface_cxx.is_none(),
            "package-level interface fields must stay inert on executables"
        );
    }

    #[test]
    fn fingerprint_lines_are_values_only_and_deterministic() {
        let mut summary = LanguageStandardsSummary::default();
        // Nothing declared anywhere: nothing to fingerprint.
        assert!(summary.fingerprint_lines().is_empty());

        summary.c = Some(ResolvedStandard {
            standard: CStandard::C11,
            source: LanguageStandardSource::Package,
        });
        summary.cxx = Some(ResolvedStandard {
            standard: CxxStandard::Cxx17,
            source: LanguageStandardSource::Package,
        });
        let lines = summary.fingerprint_lines();
        assert_eq!(lines, vec!["c=c11".to_owned(), "cxx=c++17".to_owned()]);

        // Provenance must not appear in the lines.
        summary.cxx = Some(ResolvedStandard {
            standard: CxxStandard::Cxx17,
            source: LanguageStandardSource::Workspace,
        });
        assert_eq!(summary.fingerprint_lines(), lines);

        summary.targets.insert(
            "core".to_owned(),
            TargetStandardsSummary {
                c: summary.c,
                cxx: Some(ResolvedStandard {
                    standard: CxxStandard::Cxx20,
                    source: LanguageStandardSource::Target,
                }),
                interface_c: Some(InterfaceStandard {
                    requirement: InterfaceRequirement::None,
                    source: InterfaceStandardSource::Target,
                }),
                interface_cxx: Some(InterfaceStandard {
                    requirement: requirement(CxxStandard::Cxx17),
                    source: InterfaceStandardSource::Target,
                }),
                gnu_extensions: true,
            },
        );
        assert_eq!(
            summary.fingerprint_lines(),
            vec![
                "c=c11".to_owned(),
                "cxx=c++17".to_owned(),
                "target=core".to_owned(),
                "c=c11".to_owned(),
                "cxx=c++20".to_owned(),
                "interface-c=none".to_owned(),
                "interface-cxx=c++17".to_owned(),
                "gnu-extensions=true".to_owned(),
            ]
        );
    }

    #[test]
    fn standard_declaration_serde_is_a_bare_value_and_rejects_markers() {
        let declared: StandardDeclaration<CxxStandard> =
            StandardDeclaration::Declared(CxxStandard::Cxx20);
        let inherited: StandardDeclaration<CxxStandard> =
            StandardDeclaration::Inherited(CxxStandard::Cxx20);
        assert_eq!(serde_json::to_string(&declared).unwrap(), "\"c++20\"");
        assert_eq!(serde_json::to_string(&inherited).unwrap(), "\"c++20\"");
        let marker: StandardDeclaration<CxxStandard> = StandardDeclaration::Workspace;
        assert!(serde_json::to_string(&marker).is_err());
        let parsed: StandardDeclaration<CxxStandard> = serde_json::from_str("\"c++20\"").unwrap();
        assert_eq!(parsed, StandardDeclaration::Declared(CxxStandard::Cxx20));

        // Interface declarations carry the `{ min, max }` shape (or
        // `none`) through the same bare-value contract.
        let declared_interface: StandardDeclaration<InterfaceRequirement<CxxStandard>> =
            StandardDeclaration::Declared(requirement(CxxStandard::Cxx20));
        let json = serde_json::to_string(&declared_interface).unwrap();
        assert_eq!(json, r#"{"min":"c++20","max":null}"#);
        let parsed: StandardDeclaration<InterfaceRequirement<CxxStandard>> =
            serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed,
            StandardDeclaration::Declared(requirement(CxxStandard::Cxx20))
        );
        let parsed: StandardDeclaration<InterfaceRequirement<CxxStandard>> =
            serde_json::from_str("\"none\"").unwrap();
        assert_eq!(
            parsed,
            StandardDeclaration::Declared(InterfaceRequirement::None)
        );
    }

    #[test]
    fn inherited_standard_resolves_with_workspace_source() {
        let settings = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Inherited(CxxStandard::Cxx20)),
            ..Default::default()
        };
        let resolved = resolve_language_standards(&settings);
        let cxx = resolved.cxx.unwrap();
        assert_eq!(cxx.standard, CxxStandard::Cxx20);
        assert_eq!(cxx.source, LanguageStandardSource::Workspace);
        assert_eq!(resolved.c, None);
    }

    #[test]
    fn inherited_interface_standard_resolves_with_workspace_source() {
        let settings = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Declared(CxxStandard::Cxx20)),
            interface_cxx_standard: Some(StandardDeclaration::Inherited(requirement(
                CxxStandard::Cxx17,
            ))),
            ..Default::default()
        };
        let resolved = resolve_language_standards(&settings);
        let lib = target(
            TargetKind::Library,
            &["a.cc"],
            LanguageStandardSettings::default(),
        );
        let interface = interface_cxx(&resolved, &settings, &lib).unwrap();
        assert_eq!(interface.requirement, requirement(CxxStandard::Cxx17));
        assert_eq!(interface.source, InterfaceStandardSource::Workspace);
    }

    #[test]
    fn inherited_values_behave_like_declarations_for_conflicts_and_relevance() {
        let flags = ResolvedProfileFlags {
            cxxflags: vec!["-std=c++20".to_owned()],
            ..Default::default()
        };
        let inherited = LanguageStandardSettings {
            cxx_standard: Some(StandardDeclaration::Inherited(CxxStandard::Cxx17)),
            ..Default::default()
        };
        assert_eq!(
            find_standard_flag_conflicts("p", &inherited, &[], &flags).len(),
            1
        );

        let header_only = target(
            TargetKind::HeaderOnly,
            &[],
            LanguageStandardSettings::default(),
        );
        let pkg = LanguageStandardSettings {
            interface_cxx_standard: Some(StandardDeclaration::Inherited(requirement(
                CxxStandard::Cxx20,
            ))),
            ..Default::default()
        };
        assert!(imposes_requirement(&header_only, &pkg, SourceLanguage::Cxx));
    }

    #[test]
    fn fingerprint_is_identical_for_declared_and_inherited_values() {
        use crate::{Package, PackageName};
        let make = |decl: StandardDeclaration<CxxStandard>| {
            let package = Package::new(
                PackageName::new("demo").unwrap(),
                semver::Version::parse("0.1.0").unwrap(),
                vec![target(
                    TargetKind::Executable,
                    &["main.cc"],
                    LanguageStandardSettings::default(),
                )],
                Vec::new(),
            )
            .unwrap()
            .with_language(LanguageStandardSettings {
                cxx_standard: Some(decl),
                ..Default::default()
            });
            LanguageStandardsSummary::from_package(&package).fingerprint_lines()
        };
        assert_eq!(
            make(StandardDeclaration::Declared(CxxStandard::Cxx20)),
            make(StandardDeclaration::Inherited(CxxStandard::Cxx20))
        );
    }

    #[test]
    fn workspace_marker_field_reports_the_first_marker() {
        assert_eq!(
            LanguageStandardSettings::default().workspace_marker_field(),
            None
        );
        let settings = LanguageStandardSettings {
            interface_c_standard: Some(StandardDeclaration::Workspace),
            ..Default::default()
        };
        assert_eq!(
            settings.workspace_marker_field(),
            Some("interface-c-standard")
        );
        let settings = LanguageStandardSettings {
            c_standard: Some(StandardDeclaration::Workspace),
            interface_c_standard: Some(StandardDeclaration::Workspace),
            ..Default::default()
        };
        assert_eq!(settings.workspace_marker_field(), Some("c-standard"));
    }
}