compose-lens 0.1.15

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
//! Source-aware native Compose document types.

mod annotation;
mod capability;
mod command;
mod dependency;
mod device;
mod dns;
mod dns_option;
mod dns_search;
mod entrypoint;
mod environment;
mod expose;
mod host;
mod hostname;
mod identity;
mod image;
mod lifecycle;
mod memory;
mod network;
mod pids;
mod port;
mod pull;
mod resource;
mod restart;
mod sections;
mod security_option;
mod shm;
mod sysctl;
mod tmpfs;
mod ulimit;
mod value;
mod volume;

pub use annotation::{Annotations, AnnotationsForm};
pub use capability::{CapabilityAdd, CapabilityAddItem, CapabilityDrop, CapabilityDropItem};
pub use command::Command;
pub use dependency::{
    DependencyCondition, DependsOn, Healthcheck, HealthcheckDuration, HealthcheckRetries, HealthcheckTest,
    HealthcheckTestKind, ServiceDependency,
};
pub(crate) use device::valid_generated_device_string;
pub use device::{Device, Devices, LongDevice, ShortDevice, ShortDeviceKind};
pub use dns::{Dns, DnsForm};
pub use dns_option::DnsOptions;
pub use dns_search::{DnsSearch, DnsSearchForm};
pub use entrypoint::Entrypoint;
pub use environment::{
    Environment, EnvironmentFile, EnvironmentFileFormat, EnvironmentFileFormatKind, EnvironmentListEntry,
    EnvironmentMapEntry, LongEnvironmentFile,
};
pub use expose::{Expose, ExposeItem, ExposeItemKind, ExposePort, ExposeProtocol, ExposeScalarKind};
pub(crate) use expose::{classify_expose_item, valid_generated_expose_item};
pub use host::{ExtraHostSeparator, ExtraHosts, HostAddress, HostAddressKind, LongExtraHost, ShortExtraHost};
pub(crate) use hostname::valid_hostname;
pub use hostname::{Hostname, HostnameKind};
pub use identity::{IdentityComponent, UserNamespaceMode, UserNamespaceModeKind, UserSpec};
pub use image::{ImageDigest, ImageReference};
pub use lifecycle::StopGracePeriod;
pub(crate) use memory::valid_generated_mem_amount;
pub use memory::{MemLimit, MemLimitKind, MemLimitScalarKind, MemLimitUnit};
pub use network::{Ipam, IpamConfig, NetworkDefinition, ServiceNetwork, ServiceNetworks};
pub(crate) use pids::valid_positive_pids_decimal;
pub use pids::{PidsLimit, PidsLimitKind};
pub use port::{LongPort, Port, ShortPort};
pub(crate) use pull::valid_pull_policy_duration;
pub use pull::{PullPolicy, PullPolicyKind};
pub use resource::{ConfigDefinition, ConfigGrant, LongGrant, SecretDefinition, SecretGrant, VolumeDefinition};
pub use restart::{RestartPolicy, RestartPolicyKind};
pub use sections::{
    Build, BuildDefinition, BuildField, BuildFieldKind, DeployDefinition, DeployField, DeployFieldKind,
};
pub(crate) use security_option::{SecurityOptionCandidateCounts, classify_security_option};
pub use security_option::{SecurityOptionItem, SecurityOptionKind, SecurityOptions};
pub(crate) use shm::valid_generated_shm_amount;
pub use shm::{ShmSize, ShmSizeKind, ShmSizeScalarKind, ShmSizeUnit};
pub use sysctl::{Sysctls, SysctlsForm};
pub(crate) use tmpfs::valid_generated_tmpfs_item;
pub use tmpfs::{Tmpfs, TmpfsForm, TmpfsItem, TmpfsItemKind};
pub(crate) use ulimit::valid_ulimit_name;
pub use ulimit::{LimitValue, Ulimit, UlimitRange, UlimitValue, Ulimits};
pub use value::{BooleanValue, ComposeScalar, KeyValueEntry, Labels};
pub use volume::{
    BindOptions, ContainerPath, ContainerPathKind, LongVolumeMount, MountType, SelinuxRelabel, ShortVolumeMount,
    VolumeMount, VolumeSyntax,
};

use crate::diagnostic::{Diagnostic, DiagnosticCode, DiagnosticLabel, Severity};
use crate::source::{SourceId, SourceSpan};
use crate::syntax::{SyntaxDocument, scalar_string_from_source};
use std::collections::{BTreeMap, BTreeSet};
use yaml_edit::{AnchorRegistry, AsYaml, Mapping, ScalarType, ScalarValue, YamlNode};

/// A Compose document root must be a mapping.
pub const DOCUMENT_ROOT_TYPE: DiagnosticCode = DiagnosticCode::new("compose.document.expected-mapping");

/// `ComposeLens` currently types the first document in a multi-document YAML stream.
pub const MULTIPLE_DOCUMENTS: DiagnosticCode = DiagnosticCode::new("compose.document.multiple-documents");

/// A mapping contains a duplicate field.
pub const DUPLICATE_FIELD: DiagnosticCode = DiagnosticCode::new("compose.model.duplicate-field");

/// A Compose value has to be a mapping at this location.
pub const EXPECTED_MAPPING: DiagnosticCode = DiagnosticCode::new("compose.model.expected-mapping");

/// A Compose value has to be a sequence at this location.
pub const EXPECTED_SEQUENCE: DiagnosticCode = DiagnosticCode::new("compose.model.expected-sequence");

/// A Compose value has to be a scalar at this location.
pub const EXPECTED_SCALAR: DiagnosticCode = DiagnosticCode::new("compose.model.expected-scalar");

/// A Compose value has to be a boolean at this location.
pub const EXPECTED_BOOLEAN: DiagnosticCode = DiagnosticCode::new("compose.model.expected-boolean");

/// A field supports multiple Compose syntax forms, but the authored form is invalid here.
pub const EXPECTED_FIELD_FORM: DiagnosticCode = DiagnosticCode::new("compose.model.expected-field-form");

/// A service port is neither scalar short syntax nor mapping long syntax.
pub const PORT_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.port.expected-short-or-long");

/// A long-syntax service port is missing `target`.
pub const PORT_MISSING_TARGET: DiagnosticCode = DiagnosticCode::new("compose.port.long.missing-target");

/// A service config or secret grant is neither scalar short syntax nor mapping long syntax.
pub const GRANT_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.grant.expected-short-or-long");

/// A long-syntax service config or secret grant is missing `source`.
pub const GRANT_MISSING_SOURCE: DiagnosticCode = DiagnosticCode::new("compose.grant.long.missing-source");

/// A top-level resource definition must be a mapping or an explicit null.
pub const RESOURCE_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.resource.expected-mapping-or-null");

/// A service-volume item is neither short nor long syntax.
pub const VOLUME_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.volume.expected-short-or-long");

/// A long-syntax service volume is missing `type`.
pub const VOLUME_MISSING_TYPE: DiagnosticCode = DiagnosticCode::new("compose.volume.long.missing-type");

/// A long-syntax service volume is missing `target`.
pub const VOLUME_MISSING_TARGET: DiagnosticCode = DiagnosticCode::new("compose.volume.long.missing-target");

/// A long-syntax bind mount has an invalid `SELinux` value.
pub const VOLUME_INVALID_SELINUX: DiagnosticCode = DiagnosticCode::new("compose.volume.bind.invalid-selinux");

/// A short `extra_hosts` entry does not contain a hostname/address separator.
pub const EXTRA_HOST_INVALID_ENTRY: DiagnosticCode = DiagnosticCode::new("compose.extra-hosts.invalid-entry");

/// A service limit is neither unlimited, a non-negative integer, nor deferred.
pub const ULIMIT_INVALID_VALUE: DiagnosticCode = DiagnosticCode::new("compose.ulimits.invalid-value");

/// A service limit name is outside Compose's portable lowercase-name grammar.
pub const ULIMIT_INVALID_NAME: DiagnosticCode = DiagnosticCode::new("compose.ulimits.invalid-name");

/// A service limit range is missing its required `soft` or `hard` member.
pub const ULIMIT_MISSING_RANGE_MEMBER: DiagnosticCode = DiagnosticCode::new("compose.ulimits.missing-range-member");

/// A health-check list has no valid command-mode token.
pub const HEALTHCHECK_INVALID_TEST: DiagnosticCode = DiagnosticCode::new("compose.healthcheck.invalid-test");

/// A health-check duration does not follow Compose duration syntax.
pub const HEALTHCHECK_INVALID_DURATION: DiagnosticCode = DiagnosticCode::new("compose.healthcheck.invalid-duration");

/// A health-check retry count is not a non-negative integer or deferred expression.
pub const HEALTHCHECK_INVALID_RETRIES: DiagnosticCode = DiagnosticCode::new("compose.healthcheck.invalid-retries");

/// A service-level restart policy is not one of the Compose-defined forms or an expression.
pub const RESTART_INVALID_POLICY: DiagnosticCode = DiagnosticCode::new("compose.restart.invalid-policy");

/// A service hostname is not authored as a YAML string scalar.
pub const HOSTNAME_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.hostname.expected-string");

/// A resolved service hostname does not satisfy the conservative RFC-1123 grammar.
pub const HOSTNAME_INVALID: DiagnosticCode = DiagnosticCode::new("compose.hostname.invalid-value");

/// A service PID limit is not a number or string scalar.
pub const PIDS_LIMIT_EXPECTED_VALUE: DiagnosticCode =
    DiagnosticCode::new("compose.pids-limit.expected-number-or-string");

/// A service PID limit is neither unlimited, positive integral decimal, nor deferred.
pub const PIDS_LIMIT_INVALID: DiagnosticCode = DiagnosticCode::new("compose.pids-limit.invalid-value");

/// A zero service PID limit has ambiguous and unportable native semantics.
pub const PIDS_LIMIT_AMBIGUOUS_ZERO: DiagnosticCode = DiagnosticCode::new("compose.pids-limit.ambiguous-zero");

/// A service shared-memory size is not a number or string scalar.
pub const SHM_SIZE_EXPECTED_VALUE: DiagnosticCode = DiagnosticCode::new("compose.shm-size.expected-number-or-string");

/// A zero service shared-memory size has no defined Compose semantics.
pub const SHM_SIZE_AMBIGUOUS_ZERO: DiagnosticCode = DiagnosticCode::new("compose.shm-size.ambiguous-zero");

/// A schema-accepted numeric shared-memory size lacks a documented explicit unit.
pub const SHM_SIZE_PROVIDER_DEPENDENT_NUMBER: DiagnosticCode =
    DiagnosticCode::new("compose.shm-size.provider-dependent-number");

/// A schema-accepted string shared-memory size is outside the documented lowercase suffix family.
pub const SHM_SIZE_PROVIDER_DEPENDENT_STRING: DiagnosticCode =
    DiagnosticCode::new("compose.shm-size.provider-dependent-string");

/// A service memory limit is not a number or string scalar.
pub const MEM_LIMIT_EXPECTED_VALUE: DiagnosticCode = DiagnosticCode::new("compose.mem-limit.expected-number-or-string");

/// A zero service memory limit has no portable cross-provider meaning inferred by `ComposeLens`.
pub const MEM_LIMIT_AMBIGUOUS_ZERO: DiagnosticCode = DiagnosticCode::new("compose.mem-limit.ambiguous-zero");

/// A schema-accepted numeric memory limit lacks a documented explicit unit.
pub const MEM_LIMIT_SCHEMA_NUMBER: DiagnosticCode = DiagnosticCode::new("compose.mem-limit.schema-number");

/// A schema-accepted string memory limit is outside the documented lowercase suffix family.
pub const MEM_LIMIT_PROVIDER_DEPENDENT_STRING: DiagnosticCode =
    DiagnosticCode::new("compose.mem-limit.provider-dependent-string");

/// A service image pull policy is not documented, schema-recognized, or deferred.
pub const PULL_POLICY_INVALID: DiagnosticCode = DiagnosticCode::new("compose.pull-policy.invalid-policy");

/// A service stop grace period does not match the raw-preserving policy based on documented Compose units.
pub const STOP_GRACE_PERIOD_INVALID: DiagnosticCode =
    DiagnosticCode::new("compose.lifecycle.invalid-stop-grace-period");

/// A service `cap_drop` value is not a YAML sequence.
pub const CAP_DROP_EXPECTED_SEQUENCE: DiagnosticCode = DiagnosticCode::new("compose.cap-drop.expected-sequence");

/// A service `cap_drop` item is not a YAML string scalar.
pub const CAP_DROP_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.cap-drop.expected-string");

/// A service `cap_drop` sequence contains an exact duplicate string.
pub const CAP_DROP_DUPLICATE_ITEM: DiagnosticCode = DiagnosticCode::new("compose.cap-drop.duplicate-item");

/// A service `cap_add` value is not a YAML sequence.
pub const CAP_ADD_EXPECTED_SEQUENCE: DiagnosticCode = DiagnosticCode::new("compose.cap-add.expected-sequence");

/// A service `cap_add` item is not a YAML string scalar.
pub const CAP_ADD_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.cap-add.expected-string");

/// A service `cap_add` sequence contains an exact duplicate string.
pub const CAP_ADD_DUPLICATE_ITEM: DiagnosticCode = DiagnosticCode::new("compose.cap-add.duplicate-item");

/// A service `devices` value is not a YAML sequence.
pub const DEVICES_EXPECTED_SEQUENCE: DiagnosticCode = DiagnosticCode::new("compose.devices.expected-sequence");

/// A service device item is neither a string scalar nor a mapping.
pub const DEVICE_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.devices.expected-short-or-long");

/// A short device or long-device member is not a YAML string scalar.
pub const DEVICE_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.devices.expected-string");

/// A long-syntax service device is missing its required `source` string.
pub const DEVICE_MISSING_SOURCE: DiagnosticCode = DiagnosticCode::new("compose.devices.long.missing-source");

/// A service `dns` value is neither a YAML string scalar nor a sequence.
pub const DNS_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.dns.expected-string-or-list");

/// A service `dns` list item is not a YAML string scalar.
pub const DNS_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.dns.expected-string");

/// A service `dns_opt` value is not a YAML sequence.
pub const DNS_OPT_EXPECTED_SEQUENCE: DiagnosticCode = DiagnosticCode::new("compose.dns-opt.expected-sequence");

/// A service `dns_opt` item is not a YAML string scalar.
pub const DNS_OPT_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.dns-opt.expected-string");

/// A service `dns_opt` sequence contains an exact duplicate string.
pub const DNS_OPT_DUPLICATE_ITEM: DiagnosticCode = DiagnosticCode::new("compose.dns-opt.duplicate-item");

/// A service `dns_search` value is neither a YAML string scalar nor a sequence.
pub const DNS_SEARCH_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.dns-search.expected-string-or-list");

/// A service `dns_search` list item is not a YAML string scalar.
pub const DNS_SEARCH_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.dns-search.expected-string");

/// A service `dns_search` list contains an exact duplicate string.
pub const DNS_SEARCH_DUPLICATE_ITEM: DiagnosticCode = DiagnosticCode::new("compose.dns-search.duplicate-item");

/// A service `expose` value is not a YAML sequence.
pub const EXPOSE_EXPECTED_SEQUENCE: DiagnosticCode = DiagnosticCode::new("compose.expose.expected-sequence");

/// A service `expose` item is not a YAML string or number scalar.
pub const EXPOSE_EXPECTED_SCALAR: DiagnosticCode = DiagnosticCode::new("compose.expose.expected-string-or-number");

/// A service `expose` item does not match the documented decimal port/range grammar.
pub const EXPOSE_INVALID_ITEM: DiagnosticCode = DiagnosticCode::new("compose.expose.invalid-item");

/// A service `expose` item uses a protocol outside the documented portable set.
pub const EXPOSE_PROVIDER_DEPENDENT: DiagnosticCode = DiagnosticCode::new("compose.expose.provider-dependent-protocol");

/// A service `expose` sequence contains an exact duplicate scalar identity.
pub const EXPOSE_DUPLICATE_ITEM: DiagnosticCode = DiagnosticCode::new("compose.expose.duplicate-item");

/// A service `security_opt` value is not a YAML sequence.
pub const SECURITY_OPT_EXPECTED_SEQUENCE: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.expected-sequence");

/// A service `security_opt` item is not a YAML string scalar.
pub const SECURITY_OPT_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.security-opt.expected-string");

/// A service `security_opt` item is an explicitly empty string.
pub const SECURITY_OPT_EMPTY_ITEM: DiagnosticCode = DiagnosticCode::new("compose.security-opt.empty-item");

/// An AppArmor-shaped service `security_opt` item is not the exact narrow candidate form.
pub const SECURITY_OPT_APPARMOR_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.apparmor-near-miss");

/// More than one exact `AppArmor` candidate remains in a service `security_opt` sequence.
pub const SECURITY_OPT_APPARMOR_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.apparmor-conflict");

/// A seccomp-shaped service `security_opt` item is not the exact narrow candidate form.
pub const SECURITY_OPT_SECCOMP_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.seccomp-near-miss");

/// More than one exact seccomp candidate remains in a service `security_opt` sequence.
pub const SECURITY_OPT_SECCOMP_CONFLICT: DiagnosticCode = DiagnosticCode::new("compose.security-opt.seccomp-conflict");

/// A no-new-privileges-shaped item is not an exact lowercase boolean candidate.
pub const SECURITY_OPT_NO_NEW_PRIVILEGES_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.no-new-privileges-near-miss");

/// More than one exact no-new-privileges candidate remains in one effective sequence.
pub const SECURITY_OPT_NO_NEW_PRIVILEGES_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.no-new-privileges-conflict");

/// A mask-shaped service `security_opt` item is not the exact narrow candidate form.
pub const SECURITY_OPT_MASK_NEAR_MISS: DiagnosticCode = DiagnosticCode::new("compose.security-opt.mask-near-miss");

/// An unmask-shaped service `security_opt` item is not the exact narrow candidate form.
pub const SECURITY_OPT_UNMASK_NEAR_MISS: DiagnosticCode = DiagnosticCode::new("compose.security-opt.unmask-near-miss");

pub(crate) fn security_path_option_diagnostic(kind: &SecurityOptionKind, span: SourceSpan) -> Option<Diagnostic> {
    let (code, message) = match kind {
        SecurityOptionKind::MaskNearMiss => (
            SECURITY_OPT_MASK_NEAR_MISS,
            "mask candidates require exact lowercase `mask=<paths>` spelling with a non-empty whitespace-free payload",
        ),
        SecurityOptionKind::UnmaskNearMiss => (
            SECURITY_OPT_UNMASK_NEAR_MISS,
            "unmask candidates require exact lowercase `unmask=ALL` or colon-separated slash-prefixed paths without whitespace",
        ),
        _ => return None,
    };
    Some(
        Diagnostic::new(code, Severity::Warning, message)
            .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
    )
}

/// A `SELinux` label-disable-shaped item is not the exact lowercase candidate.
pub const SECURITY_OPT_SECURITY_LABEL_DISABLE_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-disable-near-miss");

/// More than one exact `SELinux` label-disable candidate remains in one effective sequence.
pub const SECURITY_OPT_SECURITY_LABEL_DISABLE_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-disable-conflict");

/// A `SELinux` label-filetype-shaped item is not the exact lowercase candidate.
pub const SECURITY_OPT_SECURITY_LABEL_FILETYPE_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-filetype-near-miss");

/// More than one exact `SELinux` label-filetype candidate remains in one effective sequence.
pub const SECURITY_OPT_SECURITY_LABEL_FILETYPE_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-filetype-conflict");

/// A `SELinux` label-level-shaped item is not the exact lowercase candidate.
pub const SECURITY_OPT_SECURITY_LABEL_LEVEL_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-level-near-miss");

/// More than one exact `SELinux` label-level candidate remains in one effective sequence.
pub const SECURITY_OPT_SECURITY_LABEL_LEVEL_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-level-conflict");

/// A `SELinux` label-nested-shaped item is not the exact lowercase candidate.
pub const SECURITY_OPT_SECURITY_LABEL_NESTED_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-nested-near-miss");

/// More than one exact `SELinux` label-nested candidate remains in one effective sequence.
pub const SECURITY_OPT_SECURITY_LABEL_NESTED_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-nested-conflict");

/// A `SELinux` label-type-shaped item is not the exact lowercase candidate.
pub const SECURITY_OPT_SECURITY_LABEL_TYPE_NEAR_MISS: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-type-near-miss");

/// More than one exact `SELinux` label-type candidate remains in one effective sequence.
pub const SECURITY_OPT_SECURITY_LABEL_TYPE_CONFLICT: DiagnosticCode =
    DiagnosticCode::new("compose.security-opt.security-label-type-conflict");

fn authored_security_label_diagnostic(
    kind: &SecurityOptionKind,
    span: SourceSpan,
    candidates: &mut SecurityOptionCandidateCounts,
) -> Option<Diagnostic> {
    match kind {
        SecurityOptionKind::SecurityLabelDisable { .. } => {
            candidates.security_label_disable += 1;
            (candidates.security_label_disable > 1).then(|| {
                Diagnostic::new(
                    SECURITY_OPT_SECURITY_LABEL_DISABLE_CONFLICT,
                    Severity::Warning,
                    "multiple SELinux label-disable candidates are retained; a consumer must resolve the conflict explicitly",
                )
                .with_label(DiagnosticLabel::primary(
                    span,
                    "additional SELinux label-disable candidate retained",
                ))
            })
        }
        SecurityOptionKind::SecurityLabelDisableNearMiss => Some(
            Diagnostic::new(
                SECURITY_OPT_SECURITY_LABEL_DISABLE_NEAR_MISS,
                Severity::Warning,
                "SELinux label-disable candidates require exact lowercase `label:disable` spelling without whitespace",
            )
            .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
        ),
        SecurityOptionKind::SecurityLabelFileType { .. } => {
            candidates.security_label_filetype += 1;
            (candidates.security_label_filetype > 1).then(|| {
                Diagnostic::new(
                    SECURITY_OPT_SECURITY_LABEL_FILETYPE_CONFLICT,
                    Severity::Warning,
                    "multiple SELinux label-filetype candidates are retained; a consumer must resolve the conflict explicitly",
                )
                .with_label(DiagnosticLabel::primary(
                    span,
                    "additional SELinux label-filetype candidate retained",
                ))
            })
        }
        SecurityOptionKind::SecurityLabelFileTypeNearMiss => Some(
            Diagnostic::new(
                SECURITY_OPT_SECURITY_LABEL_FILETYPE_NEAR_MISS,
                Severity::Warning,
                "SELinux label-filetype candidates require exact lowercase `label:filetype:<type>` spelling without whitespace",
            )
            .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
        ),
        SecurityOptionKind::SecurityLabelLevel { .. } => {
            candidates.security_label_level += 1;
            (candidates.security_label_level > 1).then(|| {
                Diagnostic::new(
                    SECURITY_OPT_SECURITY_LABEL_LEVEL_CONFLICT,
                    Severity::Warning,
                    "multiple SELinux label-level candidates are retained; a consumer must resolve the conflict explicitly",
                )
                .with_label(DiagnosticLabel::primary(
                    span,
                    "additional SELinux label-level candidate retained",
                ))
            })
        }
        SecurityOptionKind::SecurityLabelLevelNearMiss => Some(
            Diagnostic::new(
                SECURITY_OPT_SECURITY_LABEL_LEVEL_NEAR_MISS,
                Severity::Warning,
                "SELinux label-level candidates require exact lowercase `label:level:<level>` spelling without whitespace",
            )
            .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
        ),
        SecurityOptionKind::SecurityLabelNested { .. } => {
            candidates.security_label_nested += 1;
            (candidates.security_label_nested > 1).then(|| {
                Diagnostic::new(
                    SECURITY_OPT_SECURITY_LABEL_NESTED_CONFLICT,
                    Severity::Warning,
                    "multiple SELinux label-nested candidates are retained; a consumer must resolve the conflict explicitly",
                )
                .with_label(DiagnosticLabel::primary(
                    span,
                    "additional SELinux label-nested candidate retained",
                ))
            })
        }
        SecurityOptionKind::SecurityLabelNestedNearMiss => Some(
            Diagnostic::new(
                SECURITY_OPT_SECURITY_LABEL_NESTED_NEAR_MISS,
                Severity::Warning,
                "SELinux label-nested candidates require exact lowercase `label:nested` spelling without whitespace",
            )
            .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
        ),
        SecurityOptionKind::SecurityLabelType { .. } | SecurityOptionKind::SecurityLabelTypeNearMiss => {
            authored_security_label_type_diagnostic(kind, span, &mut candidates.security_label_type)
        }
        _ => None,
    }
}

fn authored_security_label_type_diagnostic(
    kind: &SecurityOptionKind,
    span: SourceSpan,
    candidates: &mut usize,
) -> Option<Diagnostic> {
    match kind {
        SecurityOptionKind::SecurityLabelType { .. } => {
            *candidates += 1;
            (*candidates > 1).then(|| {
                Diagnostic::new(
                    SECURITY_OPT_SECURITY_LABEL_TYPE_CONFLICT,
                    Severity::Warning,
                    "multiple SELinux label-type candidates are retained; a consumer must resolve the conflict explicitly",
                )
                .with_label(DiagnosticLabel::primary(
                    span,
                    "additional SELinux label-type candidate retained",
                ))
            })
        }
        SecurityOptionKind::SecurityLabelTypeNearMiss => Some(
            Diagnostic::new(
                SECURITY_OPT_SECURITY_LABEL_TYPE_NEAR_MISS,
                Severity::Warning,
                "SELinux label-type candidates require exact lowercase `label:type:<type>` spelling with one non-empty whitespace-free type",
            )
            .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
        ),
        _ => None,
    }
}

/// A service `annotations` value is neither mapping nor list syntax.
pub const ANNOTATIONS_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.annotations.expected-map-or-list");

/// A service annotation list item is not a YAML string scalar.
pub const ANNOTATIONS_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.annotations.expected-string");

/// A service annotation has an empty semantic name.
pub const ANNOTATIONS_EMPTY_NAME: DiagnosticCode = DiagnosticCode::new("compose.annotations.empty-name");

/// A key-only service annotation list item has no defined explicit value.
pub const ANNOTATIONS_KEY_ONLY: DiagnosticCode = DiagnosticCode::new("compose.annotations.key-only");

/// More than one authored service annotation resolves to the same semantic name.
pub const ANNOTATIONS_DUPLICATE_NAME: DiagnosticCode = DiagnosticCode::new("compose.annotations.duplicate-name");

/// A service-level `tmpfs` value is neither a string scalar nor a sequence.
pub const TMPFS_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.tmpfs.expected-string-or-list");

/// A service-level `tmpfs` sequence item is not a YAML string scalar.
pub const TMPFS_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.tmpfs.expected-string");

/// A service-level `tmpfs` item is malformed or depends on provider- or target-specific behavior.
pub const TMPFS_PROVIDER_DEPENDENT: DiagnosticCode = DiagnosticCode::new("compose.tmpfs.provider-dependent-item");

/// A service `sysctls` value is neither a mapping nor a sequence.
pub const SYSCTLS_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.sysctls.expected-map-or-list");

/// A service `sysctls` mapping contains an empty key.
pub const SYSCTLS_EMPTY_KEY: DiagnosticCode = DiagnosticCode::new("compose.sysctls.empty-key");

/// A service `sysctls` mapping value is not a scalar or null.
pub const SYSCTLS_EXPECTED_SCALAR: DiagnosticCode = DiagnosticCode::new("compose.sysctls.expected-scalar");

/// A service `sysctls` list item is not a YAML string scalar.
pub const SYSCTLS_EXPECTED_STRING: DiagnosticCode = DiagnosticCode::new("compose.sysctls.expected-string");

/// A service `sysctls` list contains an exact duplicate string.
pub const SYSCTLS_DUPLICATE_ITEM: DiagnosticCode = DiagnosticCode::new("compose.sysctls.duplicate-item");

/// A service environment-file item is neither scalar short syntax nor mapping long syntax.
pub const ENVIRONMENT_FILE_EXPECTED_FORM: DiagnosticCode =
    DiagnosticCode::new("compose.environment-file.expected-short-or-long");

/// A long-syntax service environment-file entry is missing `path`.
pub const ENVIRONMENT_FILE_MISSING_PATH: DiagnosticCode =
    DiagnosticCode::new("compose.environment-file.long.missing-path");

/// A long-syntax service environment-file format is not defined by Compose.
pub const ENVIRONMENT_FILE_INVALID_FORMAT: DiagnosticCode =
    DiagnosticCode::new("compose.environment-file.invalid-format");

/// A long dependency uses an unrecognized condition.
pub const DEPENDENCY_INVALID_CONDITION: DiagnosticCode = DiagnosticCode::new("compose.dependencies.invalid-condition");

/// A typed dependency names a service missing from the same document.
pub const DEPENDENCY_MISSING_SERVICE: DiagnosticCode = DiagnosticCode::new("compose.dependencies.missing-service");

/// A `service_healthy` dependency has no enabled health check.
pub const DEPENDENCY_MISSING_HEALTHCHECK: DiagnosticCode =
    DiagnosticCode::new("compose.dependencies.missing-healthcheck");

/// A `service_healthy` dependency may rely on health metadata from its image.
pub const DEPENDENCY_HEALTHCHECK_UNVERIFIED: DiagnosticCode =
    DiagnosticCode::new("compose.dependencies.healthcheck-unverified");

/// A typed value and the exact source span from which it was read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Located<T> {
    value: T,
    span: SourceSpan,
}

impl<T> Located<T> {
    pub(crate) const fn new(value: T, span: SourceSpan) -> Self {
        Self { value, span }
    }

    /// Returns the typed value.
    #[must_use]
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns the value's source span.
    #[must_use]
    pub const fn span(&self) -> SourceSpan {
        self.span
    }

    /// Removes the source wrapper and returns the typed value.
    #[must_use]
    pub fn into_value(self) -> T {
        self.value
    }
}

/// Source provenance for an extension or not-yet-typed field.
///
/// The loss-aware [`SyntaxDocument`] retains the actual value and spelling. This reference lets
/// typed callers locate it without exposing the private YAML implementation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldReference {
    name: Located<String>,
    span: SourceSpan,
    value_span: Option<SourceSpan>,
}

impl FieldReference {
    /// Returns the semantic field name and its source span.
    #[must_use]
    pub const fn name(&self) -> &Located<String> {
        &self.name
    }

    /// Returns the span covering the key and value when both are available.
    #[must_use]
    pub const fn span(&self) -> SourceSpan {
        self.span
    }

    /// Returns the value span when the YAML node exposes one.
    #[must_use]
    pub const fn value_span(&self) -> Option<SourceSpan> {
        self.value_span
    }
}

/// A source-aware typed Compose service.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Service {
    name: Located<String>,
    span: SourceSpan,
    hostname: Option<Hostname>,
    container_name: Option<Located<String>>,
    image: Option<Located<ImageReference>>,
    entrypoint: Option<Entrypoint>,
    command: Option<Command>,
    init: Option<Located<BooleanValue>>,
    environment: Option<Environment>,
    environment_files: Vec<EnvironmentFile>,
    labels: Option<Labels>,
    annotations: Option<Annotations>,
    extra_hosts: Option<ExtraHosts>,
    user: Option<UserSpec>,
    userns_mode: Option<UserNamespaceMode>,
    group_add: Vec<Located<String>>,
    cap_add: Option<CapabilityAdd>,
    cap_drop: Option<CapabilityDrop>,
    devices: Option<Devices>,
    dns: Option<Dns>,
    dns_options: Option<DnsOptions>,
    dns_search: Option<DnsSearch>,
    expose: Option<Expose>,
    security_options: Option<SecurityOptions>,
    working_dir: Option<Located<String>>,
    read_only: Option<Located<BooleanValue>>,
    pids_limit: Option<PidsLimit>,
    shm_size: Option<ShmSize>,
    mem_limit: Option<MemLimit>,
    tmpfs: Option<Tmpfs>,
    sysctls: Option<Sysctls>,
    pull_policy: Option<PullPolicy>,
    restart: Option<RestartPolicy>,
    stop_signal: Option<Located<String>>,
    stop_grace_period: Option<Located<StopGracePeriod>>,
    ulimits: Option<Ulimits>,
    depends_on: Option<DependsOn>,
    healthcheck: Option<Healthcheck>,
    build: Option<Build>,
    deploy: Option<DeployDefinition>,
    ports: Vec<Port>,
    volumes: Vec<VolumeMount>,
    networks: Option<ServiceNetworks>,
    profiles: Vec<Located<String>>,
    configs: Vec<ConfigGrant>,
    secrets: Vec<SecretGrant>,
    extension_fields: Vec<FieldReference>,
    unknown_fields: Vec<FieldReference>,
}

impl Service {
    fn new(name: Located<String>, span: SourceSpan) -> Self {
        Self {
            name,
            span,
            hostname: None,
            container_name: None,
            image: None,
            entrypoint: None,
            command: None,
            init: None,
            environment: None,
            environment_files: Vec::new(),
            labels: None,
            annotations: None,
            extra_hosts: None,
            user: None,
            userns_mode: None,
            group_add: Vec::new(),
            cap_add: None,
            cap_drop: None,
            devices: None,
            dns: None,
            dns_options: None,
            dns_search: None,
            expose: None,
            security_options: None,
            working_dir: None,
            read_only: None,
            pids_limit: None,
            shm_size: None,
            mem_limit: None,
            tmpfs: None,
            sysctls: None,
            pull_policy: None,
            restart: None,
            stop_signal: None,
            stop_grace_period: None,
            ulimits: None,
            depends_on: None,
            healthcheck: None,
            build: None,
            deploy: None,
            ports: Vec::new(),
            volumes: Vec::new(),
            networks: None,
            profiles: Vec::new(),
            configs: Vec::new(),
            secrets: Vec::new(),
            extension_fields: Vec::new(),
            unknown_fields: Vec::new(),
        }
    }

    /// Returns the service name.
    #[must_use]
    pub const fn name(&self) -> &Located<String> {
        &self.name
    }

    /// Returns the complete service definition span.
    #[must_use]
    pub const fn span(&self) -> SourceSpan {
        self.span
    }

    /// Returns the explicitly authored raw-preserving service hostname.
    #[must_use]
    pub const fn hostname(&self) -> Option<&Hostname> {
        self.hostname.as_ref()
    }

    /// Returns the explicitly authored runtime container name.
    #[must_use]
    pub const fn container_name(&self) -> Option<&Located<String>> {
        self.container_name.as_ref()
    }

    /// Returns the explicitly authored image reference.
    #[must_use]
    pub const fn image(&self) -> Option<&Located<ImageReference>> {
        self.image.as_ref()
    }

    /// Returns the entrypoint without normalizing its authored form.
    #[must_use]
    pub const fn entrypoint(&self) -> Option<&Entrypoint> {
        self.entrypoint.as_ref()
    }

    /// Returns the command without normalizing its authored form.
    #[must_use]
    pub const fn command(&self) -> Option<&Command> {
        self.command.as_ref()
    }

    /// Returns whether Compose should run its platform-specific init process.
    #[must_use]
    pub const fn init(&self) -> Option<&Located<BooleanValue>> {
        self.init.as_ref()
    }

    /// Returns environment variables with list and mapping forms kept distinct.
    #[must_use]
    pub const fn environment(&self) -> Option<&Environment> {
        self.environment.as_ref()
    }

    /// Returns service environment files in authored order with syntax retained.
    #[must_use]
    pub fn environment_files(&self) -> &[EnvironmentFile] {
        &self.environment_files
    }

    /// Returns service metadata labels with list and mapping forms kept distinct.
    #[must_use]
    pub const fn labels(&self) -> Option<&Labels> {
        self.labels.as_ref()
    }

    /// Returns service annotations with list and mapping forms kept distinct.
    #[must_use]
    pub const fn annotations(&self) -> Option<&Annotations> {
        self.annotations.as_ref()
    }

    /// Returns additional host mappings with short and long forms retained.
    #[must_use]
    pub const fn extra_hosts(&self) -> Option<&ExtraHosts> {
        self.extra_hosts.as_ref()
    }

    /// Returns the raw-preserving container user/group value.
    #[must_use]
    pub const fn user(&self) -> Option<&UserSpec> {
        self.user.as_ref()
    }

    /// Returns the raw-preserving user-namespace mode.
    #[must_use]
    pub const fn userns_mode(&self) -> Option<&UserNamespaceMode> {
        self.userns_mode.as_ref()
    }

    /// Returns supplementary groups in authored order without resolving names or IDs.
    #[must_use]
    pub fn group_add(&self) -> &[Located<String>] {
        &self.group_add
    }

    /// Returns the explicitly authored capability-add sequence, including an explicit empty one.
    #[must_use]
    pub const fn cap_add(&self) -> Option<&CapabilityAdd> {
        self.cap_add.as_ref()
    }

    /// Returns the explicitly authored capability-drop sequence, including an explicit empty one.
    #[must_use]
    pub const fn cap_drop(&self) -> Option<&CapabilityDrop> {
        self.cap_drop.as_ref()
    }

    /// Returns the explicitly authored ordered device sequence, including an explicit empty one.
    #[must_use]
    pub const fn devices(&self) -> Option<&Devices> {
        self.devices.as_ref()
    }

    /// Returns raw service DNS servers with scalar and ordered-list forms retained.
    #[must_use]
    pub const fn dns(&self) -> Option<&Dns> {
        self.dns.as_ref()
    }

    /// Returns the explicitly authored ordered DNS resolver-option sequence.
    #[must_use]
    pub const fn dns_options(&self) -> Option<&DnsOptions> {
        self.dns_options.as_ref()
    }

    /// Returns raw DNS search domains with scalar and ordered-list forms retained.
    #[must_use]
    pub const fn dns_search(&self) -> Option<&DnsSearch> {
        self.dns_search.as_ref()
    }

    /// Returns the explicitly authored ordered exposed-port sequence.
    #[must_use]
    pub const fn expose(&self) -> Option<&Expose> {
        self.expose.as_ref()
    }

    /// Returns the explicitly authored ordered raw service security options.
    #[must_use]
    pub const fn security_options(&self) -> Option<&SecurityOptions> {
        self.security_options.as_ref()
    }

    /// Returns the container working-directory override.
    #[must_use]
    pub const fn working_dir(&self) -> Option<&Located<String>> {
        self.working_dir.as_ref()
    }

    /// Returns the explicit read-only root-filesystem choice.
    #[must_use]
    pub const fn read_only(&self) -> Option<&Located<BooleanValue>> {
        self.read_only.as_ref()
    }

    /// Returns the raw-preserving service PID limit.
    #[must_use]
    pub const fn pids_limit(&self) -> Option<&PidsLimit> {
        self.pids_limit.as_ref()
    }

    /// Returns the raw-preserving service shared-memory size.
    #[must_use]
    pub const fn shm_size(&self) -> Option<&ShmSize> {
        self.shm_size.as_ref()
    }

    /// Returns the raw-preserving service memory limit.
    #[must_use]
    pub const fn mem_limit(&self) -> Option<&MemLimit> {
        self.mem_limit.as_ref()
    }

    /// Returns service-level temporary filesystems with scalar and list forms retained.
    #[must_use]
    pub const fn tmpfs(&self) -> Option<&Tmpfs> {
        self.tmpfs.as_ref()
    }

    /// Returns service sysctls with mapping/list form and scalar spelling retained.
    #[must_use]
    pub const fn sysctls(&self) -> Option<&Sysctls> {
        self.sysctls.as_ref()
    }

    /// Returns the raw-preserving service image pull policy.
    #[must_use]
    pub const fn pull_policy(&self) -> Option<&PullPolicy> {
        self.pull_policy.as_ref()
    }

    /// Returns the service-level container restart policy.
    #[must_use]
    pub const fn restart(&self) -> Option<&RestartPolicy> {
        self.restart.as_ref()
    }

    /// Returns the explicitly authored signal used to stop the service.
    #[must_use]
    pub const fn stop_signal(&self) -> Option<&Located<String>> {
        self.stop_signal.as_ref()
    }

    /// Returns the raw-preserving service stop grace period.
    #[must_use]
    pub const fn stop_grace_period(&self) -> Option<&Located<StopGracePeriod>> {
        self.stop_grace_period.as_ref()
    }

    /// Returns explicitly authored service resource limits.
    #[must_use]
    pub const fn ulimits(&self) -> Option<&Ulimits> {
        self.ulimits.as_ref()
    }

    /// Returns service dependencies with short and long forms retained.
    #[must_use]
    pub const fn depends_on(&self) -> Option<&DependsOn> {
        self.depends_on.as_ref()
    }

    /// Returns the service health-check definition.
    #[must_use]
    pub const fn healthcheck(&self) -> Option<&Healthcheck> {
        self.healthcheck.as_ref()
    }

    /// Returns the build declaration with short and long forms retained.
    #[must_use]
    pub const fn build(&self) -> Option<&Build> {
        self.build.as_ref()
    }

    /// Returns independently classified deploy subfields.
    #[must_use]
    pub const fn deploy(&self) -> Option<&DeployDefinition> {
        self.deploy.as_ref()
    }

    /// Returns published ports in authored order.
    #[must_use]
    pub fn ports(&self) -> &[Port] {
        &self.ports
    }

    /// Returns service-volume mounts in authored order.
    #[must_use]
    pub fn volumes(&self) -> &[VolumeMount] {
        &self.volumes
    }

    /// Returns service network attachments with short and long forms kept distinct.
    #[must_use]
    pub const fn networks(&self) -> Option<&ServiceNetworks> {
        self.networks.as_ref()
    }

    /// Returns explicitly authored profile names.
    #[must_use]
    pub fn profiles(&self) -> &[Located<String>] {
        &self.profiles
    }

    /// Returns service config grants in authored order.
    #[must_use]
    pub fn configs(&self) -> &[ConfigGrant] {
        &self.configs
    }

    /// Returns service secret grants in authored order.
    #[must_use]
    pub fn secrets(&self) -> &[SecretGrant] {
        &self.secrets
    }

    /// Returns retained service `x-` extension fields.
    #[must_use]
    pub fn extension_fields(&self) -> &[FieldReference] {
        &self.extension_fields
    }

    /// Returns service fields not yet represented by the typed subset.
    #[must_use]
    pub fn unknown_fields(&self) -> &[FieldReference] {
        &self.unknown_fields
    }
}

/// A source-aware native Compose document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComposeDocument {
    source_id: SourceId,
    span: SourceSpan,
    name: Option<Located<String>>,
    services: Vec<Service>,
    networks: Vec<NetworkDefinition>,
    volumes: Vec<VolumeDefinition>,
    configs: Vec<ConfigDefinition>,
    secrets: Vec<SecretDefinition>,
    extension_fields: Vec<FieldReference>,
    unknown_fields: Vec<FieldReference>,
}

impl ComposeDocument {
    /// Extracts the initial typed Compose subset from a loss-aware syntax document.
    ///
    /// Parsing does not interpolate values, apply defaults, normalize short and long forms, or
    /// access the environment. Structural problems produce diagnostics and as much typed data as
    /// can be recovered.
    #[must_use]
    pub fn parse(syntax: &SyntaxDocument) -> ModelParse {
        Parser::new(syntax).parse()
    }

    /// Returns the source identifier.
    #[must_use]
    pub const fn source_id(&self) -> SourceId {
        self.source_id
    }

    /// Returns the typed root mapping span.
    #[must_use]
    pub const fn span(&self) -> SourceSpan {
        self.span
    }

    /// Returns the explicitly authored project name.
    #[must_use]
    pub const fn name(&self) -> Option<&Located<String>> {
        self.name.as_ref()
    }

    /// Returns services in authored order.
    #[must_use]
    pub fn services(&self) -> &[Service] {
        &self.services
    }

    /// Finds the first service with the requested name.
    #[must_use]
    pub fn service(&self, name: &str) -> Option<&Service> {
        self.services.iter().find(|service| service.name.value == name)
    }

    /// Validates dependency targets and `service_healthy` health-check requirements in this document.
    ///
    /// Multi-file callers should validate the merged project view through
    /// [`crate::resolution::validate_references`] instead.
    #[must_use]
    pub fn validate_dependencies(&self) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();
        for service in &self.services {
            let Some(depends_on) = service.depends_on() else {
                continue;
            };
            match depends_on {
                DependsOn::Short { services, .. } => {
                    for target in services {
                        if self.service(target.value()).is_none() {
                            diagnostics.push(missing_dependency_diagnostic(target.span(), false, true));
                        }
                    }
                }
                DependsOn::Long { services, .. } => {
                    for dependency in services {
                        let required = !matches!(
                            dependency.required().map(Located::value),
                            Some(BooleanValue::Literal(false))
                        );
                        let Some(target) = self.service(dependency.service().value()) else {
                            diagnostics.push(missing_dependency_diagnostic(
                                dependency.service().span(),
                                false,
                                required,
                            ));
                            continue;
                        };
                        let needs_healthcheck = matches!(
                            dependency.condition().map(Located::value),
                            Some(DependencyCondition::ServiceHealthy)
                        );
                        if needs_healthcheck && target.healthcheck().is_none() {
                            let span = dependency
                                .condition()
                                .map_or_else(|| dependency.service().span(), Located::span);
                            diagnostics.push(unverified_healthcheck_diagnostic(span));
                        } else if needs_healthcheck && target.healthcheck().is_some_and(Healthcheck::is_disabled) {
                            let span = dependency
                                .condition()
                                .map_or_else(|| dependency.service().span(), Located::span);
                            diagnostics.push(missing_dependency_diagnostic(span, true, required));
                        }
                    }
                }
            }
        }
        diagnostics
    }

    /// Returns top-level network definitions in authored order.
    #[must_use]
    pub fn networks(&self) -> &[NetworkDefinition] {
        &self.networks
    }

    /// Returns top-level volume definitions in authored order.
    #[must_use]
    pub fn volumes(&self) -> &[VolumeDefinition] {
        &self.volumes
    }

    /// Returns top-level config definitions in authored order.
    #[must_use]
    pub fn configs(&self) -> &[ConfigDefinition] {
        &self.configs
    }

    /// Returns top-level secret definitions in authored order.
    #[must_use]
    pub fn secrets(&self) -> &[SecretDefinition] {
        &self.secrets
    }

    /// Returns retained top-level `x-` extension fields.
    #[must_use]
    pub fn extension_fields(&self) -> &[FieldReference] {
        &self.extension_fields
    }

    /// Returns top-level fields not yet represented by the typed subset.
    #[must_use]
    pub fn unknown_fields(&self) -> &[FieldReference] {
        &self.unknown_fields
    }
}

/// A recoverable typed-model parse result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelParse {
    document: Option<ComposeDocument>,
    diagnostics: Vec<Diagnostic>,
}

impl ModelParse {
    /// Returns the typed document when the root could be interpreted.
    #[must_use]
    pub const fn document(&self) -> Option<&ComposeDocument> {
        self.document.as_ref()
    }

    /// Returns structural typed-model diagnostics in source order.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether no error diagnostics were emitted.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity() == Severity::Error)
    }

    /// Separates the recovered document and diagnostics.
    #[must_use]
    pub fn into_parts(self) -> (Option<ComposeDocument>, Vec<Diagnostic>) {
        (self.document, self.diagnostics)
    }
}

fn missing_dependency_diagnostic(span: SourceSpan, healthcheck: bool, required: bool) -> Diagnostic {
    let severity = if required { Severity::Error } else { Severity::Warning };
    if healthcheck {
        Diagnostic::new(
            DEPENDENCY_MISSING_HEALTHCHECK,
            severity,
            if required {
                "service_healthy dependency requires an enabled health check"
            } else {
                "optional service_healthy dependency has no enabled health check"
            },
        )
        .with_label(DiagnosticLabel::primary(span, "dependency cannot become healthy"))
    } else {
        Diagnostic::new(
            DEPENDENCY_MISSING_SERVICE,
            severity,
            if required {
                "service dependency is not declared in this Compose document"
            } else {
                "optional service dependency is not declared in this Compose document"
            },
        )
        .with_label(DiagnosticLabel::primary(span, "missing dependency service"))
    }
}

fn unverified_healthcheck_diagnostic(span: SourceSpan) -> Diagnostic {
    Diagnostic::new(
        DEPENDENCY_HEALTHCHECK_UNVERIFIED,
        Severity::Warning,
        "service_healthy dependency has no Compose healthcheck to validate",
    )
    .with_label(DiagnosticLabel::primary(span, "image health metadata is not available"))
    .with_note("the dependency image may still define a health check; verify it at build or runtime")
}

fn annotation_diagnostic(
    code: DiagnosticCode,
    severity: Severity,
    span: SourceSpan,
    message: &'static str,
    label: &'static str,
) -> Diagnostic {
    Diagnostic::new(code, severity, message).with_label(DiagnosticLabel::primary(span, label))
}

#[derive(Debug)]
struct Parser {
    source_id: SourceId,
    source_span: SourceSpan,
    source: String,
    tree: yaml_edit::YamlFile,
    anchors: AnchorRegistry,
    diagnostics: Vec<Diagnostic>,
}

impl Parser {
    fn new(syntax: &SyntaxDocument) -> Self {
        let tree = syntax.yaml_file();
        let anchors = tree
            .document()
            .map_or_else(AnchorRegistry::new, |document| AnchorRegistry::from_document(&document));
        Self {
            source_id: syntax.source_id(),
            source_span: syntax.source_span(),
            source: syntax.source_text().to_owned(),
            tree,
            anchors,
            diagnostics: Vec::new(),
        }
    }

    fn parse(mut self) -> ModelParse {
        if self.tree.documents().count() > 1 {
            self.diagnostics.push(
                Diagnostic::new(
                    MULTIPLE_DOCUMENTS,
                    Severity::Error,
                    "Compose input must contain one YAML document",
                )
                .with_label(DiagnosticLabel::primary(self.source_span, "multiple YAML documents")),
            );
        }

        let Some(root) = self.tree.document() else {
            self.diagnostics.push(
                Diagnostic::new(
                    DOCUMENT_ROOT_TYPE,
                    Severity::Error,
                    "Compose document root must be a mapping",
                )
                .with_label(DiagnosticLabel::primary(self.source_span, "empty document")),
            );
            return ModelParse {
                document: None,
                diagnostics: self.diagnostics,
            };
        };
        let root_span = span_from_position(self.source_id, root.byte_range());
        let Some(mapping) = root.as_mapping() else {
            self.diagnostics.push(
                Diagnostic::new(
                    DOCUMENT_ROOT_TYPE,
                    Severity::Error,
                    "Compose document root must be a mapping",
                )
                .with_label(DiagnosticLabel::primary(root_span, "not a mapping")),
            );
            return ModelParse {
                document: None,
                diagnostics: self.diagnostics,
            };
        };

        let document = self.parse_root(&mapping, root_span);
        ModelParse {
            document: Some(document),
            diagnostics: self.diagnostics,
        }
    }

    fn parse_root(&mut self, mapping: &Mapping, span: SourceSpan) -> ComposeDocument {
        let mut document = ComposeDocument {
            source_id: self.source_id,
            span,
            name: None,
            services: Vec::new(),
            networks: Vec::new(),
            volumes: Vec::new(),
            configs: Vec::new(),
            secrets: Vec::new(),
            extension_fields: Vec::new(),
            unknown_fields: Vec::new(),
        };
        let mut seen = BTreeMap::new();

        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "name" if !duplicate => {
                    document.name = self.parse_string(&field, "project name");
                }
                "services" if !duplicate => {
                    document.services = self.parse_services(&field);
                }
                "networks" if !duplicate => {
                    document.networks = self.parse_network_definitions(&field);
                }
                "volumes" if !duplicate => {
                    document.volumes = self.parse_volume_definitions(&field);
                }
                "configs" if !duplicate => {
                    document.configs = self.parse_config_definitions(&field);
                }
                "secrets" if !duplicate => {
                    document.secrets = self.parse_secret_definitions(&field);
                }
                name if name.starts_with("x-") => {
                    document.extension_fields.push(field.reference());
                }
                _ if duplicate => {}
                _ => document.unknown_fields.push(field.reference()),
            }
        }
        document
    }

    fn parse_services(&mut self, field: &ParsedField) -> Vec<Service> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, "services must be a mapping");
            return Vec::new();
        };
        let mut services = Vec::new();
        let mut seen = BTreeMap::new();
        for service_field in self.fields(mapping) {
            self.record_duplicate(&mut seen, &service_field);
            let Some(service_mapping) = service_field.value.as_ref().and_then(YamlNode::as_mapping) else {
                self.expected(EXPECTED_MAPPING, &service_field, "service definition must be a mapping");
                continue;
            };
            services.push(self.parse_service(&service_field, service_mapping));
        }
        services
    }

    fn parse_service(&mut self, field: &ParsedField, mapping: &Mapping) -> Service {
        let mut service = Service::new(field.name.clone(), field.span);
        let mut seen = BTreeMap::new();
        for service_field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &service_field);
            match service_field.name.value.as_str() {
                "hostname" if !duplicate => service.hostname = self.parse_hostname(&service_field),
                "container_name" if !duplicate => {
                    service.container_name = self.parse_string(&service_field, "container name");
                }
                "image" if !duplicate => service.image = self.parse_image(&service_field),
                "entrypoint" if !duplicate => service.entrypoint = self.parse_entrypoint(&service_field),
                "command" if !duplicate => service.command = self.parse_command(&service_field),
                "init" if !duplicate => service.init = self.parse_boolean(&service_field, "service init"),
                "environment" if !duplicate => service.environment = self.parse_environment(&service_field),
                "env_file" if !duplicate => {
                    service.environment_files = self.parse_environment_files(&service_field);
                }
                "labels" if !duplicate => service.labels = self.parse_labels(&service_field),
                "annotations" if !duplicate => service.annotations = self.parse_annotations(&service_field),
                "extra_hosts" if !duplicate => service.extra_hosts = self.parse_extra_hosts(&service_field),
                "user" if !duplicate => {
                    service.user = self.parse_string(&service_field, "service user").map(UserSpec::parse);
                }
                "userns_mode" if !duplicate => {
                    service.userns_mode = self
                        .parse_string(&service_field, "service user namespace mode")
                        .map(UserNamespaceMode::parse);
                }
                "group_add" if !duplicate => {
                    service.group_add = self.parse_string_sequence(&service_field, "service supplementary groups");
                }
                "cap_add" if !duplicate => service.cap_add = self.parse_cap_add(&service_field),
                "cap_drop" if !duplicate => service.cap_drop = self.parse_cap_drop(&service_field),
                "devices" if !duplicate => service.devices = self.parse_devices(&service_field),
                "dns" if !duplicate => service.dns = self.parse_dns(&service_field),
                "dns_opt" if !duplicate => service.dns_options = self.parse_dns_options(&service_field),
                "dns_search" if !duplicate => service.dns_search = self.parse_dns_search(&service_field),
                "expose" if !duplicate => service.expose = self.parse_expose(&service_field),
                "security_opt" if !duplicate => service.security_options = self.parse_security_options(&service_field),
                "working_dir" if !duplicate => {
                    service.working_dir = self.parse_string(&service_field, "service working directory");
                }
                "read_only" if !duplicate => {
                    service.read_only = self.parse_boolean(&service_field, "service read_only");
                }
                "pids_limit" if !duplicate => service.pids_limit = self.parse_pids_limit(&service_field),
                "shm_size" if !duplicate => service.shm_size = self.parse_shm_size(&service_field),
                "mem_limit" if !duplicate => service.mem_limit = self.parse_mem_limit(&service_field),
                "tmpfs" if !duplicate => service.tmpfs = self.parse_tmpfs(&service_field),
                "sysctls" if !duplicate => service.sysctls = self.parse_sysctls(&service_field),
                "pull_policy" if !duplicate => service.pull_policy = self.parse_pull_policy(&service_field),
                "restart" if !duplicate => service.restart = self.parse_restart_policy(&service_field),
                "stop_signal" if !duplicate => {
                    service.stop_signal = self.parse_string(&service_field, "service stop signal");
                }
                "stop_grace_period" if !duplicate => {
                    service.stop_grace_period = self.parse_stop_grace_period(&service_field);
                }
                "ulimits" if !duplicate => {
                    service.ulimits = self.parse_ulimits(&service_field);
                }
                "depends_on" if !duplicate => {
                    service.depends_on = self.parse_depends_on(&service_field);
                }
                "healthcheck" if !duplicate => {
                    service.healthcheck = self.parse_healthcheck(&service_field);
                }
                "build" if !duplicate => {
                    service.build = self.parse_build(&service_field);
                }
                "deploy" if !duplicate => {
                    service.deploy = self.parse_deploy(&service_field);
                }
                "ports" if !duplicate => {
                    service.ports = self.parse_service_ports(&service_field);
                }
                "volumes" if !duplicate => {
                    service.volumes = self.parse_service_volumes(&service_field);
                }
                "networks" if !duplicate => {
                    service.networks = self.parse_service_networks(&service_field);
                }
                "profiles" if !duplicate => {
                    service.profiles = self.parse_string_sequence(&service_field, "service profiles");
                }
                "configs" if !duplicate => {
                    service.configs = self.parse_config_grants(&service_field);
                }
                "secrets" if !duplicate => {
                    service.secrets = self.parse_secret_grants(&service_field);
                }
                name if name.starts_with("x-") => {
                    service.extension_fields.push(service_field.reference());
                }
                _ if duplicate => {}
                _ => service.unknown_fields.push(service_field.reference()),
            }
        }
        service
    }

    fn parse_hostname(&mut self, field: &ParsedField) -> Option<Hostname> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(HOSTNAME_EXPECTED_STRING, field, "hostname must be a YAML string scalar");
            return None;
        };
        if ScalarValue::from_scalar(scalar).scalar_type() != ScalarType::String {
            self.expected(HOSTNAME_EXPECTED_STRING, field, "hostname must be a YAML string scalar");
            return None;
        }
        let span = span_from_position(self.source_id, scalar.byte_range());
        let hostname = Hostname::parse(Located::new(scalar_string_from_source(&self.source, scalar), span));
        if hostname.kind() == &HostnameKind::Invalid {
            self.diagnostics.push(
                Diagnostic::new(
                    HOSTNAME_INVALID,
                    Severity::Error,
                    "hostname must be an ASCII RFC-1123 name of 1 to 253 characters with dot-separated labels of 1 to 63 alphanumeric or hyphen characters",
                )
                .with_label(DiagnosticLabel::primary(span, "invalid service hostname"))
                .with_note("each label must start and end with an ASCII letter or digit"),
            );
        }
        Some(hostname)
    }

    fn parse_image(&mut self, field: &ParsedField) -> Option<Located<ImageReference>> {
        self.parse_string(field, "service image")
            .map(|value| Located::new(ImageReference::parse(value.value), value.span))
    }

    fn parse_cap_drop(&mut self, field: &ParsedField) -> Option<CapabilityDrop> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(
                CAP_DROP_EXPECTED_SEQUENCE,
                field,
                "cap_drop must be a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        let mut seen = BTreeMap::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    CAP_DROP_EXPECTED_STRING,
                    &node,
                    field.span,
                    "cap_drop entries must be string scalars",
                );
                continue;
            };
            let scalar_type = ScalarValue::from_scalar(&scalar).scalar_type();
            if !matches!(
                scalar_type,
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    CAP_DROP_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "cap_drop entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let value = scalar_string_from_source(&self.source, &scalar);
            if let Some(first) = seen.get(&value) {
                self.diagnostics.push(
                    Diagnostic::new(
                        CAP_DROP_DUPLICATE_ITEM,
                        Severity::Error,
                        "cap_drop entries must be unique exact strings",
                    )
                    .with_label(DiagnosticLabel::primary(item_span, "duplicate capability string"))
                    .with_label(DiagnosticLabel::secondary(*first, "first identical string")),
                );
            } else {
                seen.insert(value.clone(), item_span);
            }
            items.push(CapabilityDropItem::new(Located::new(value, item_span)));
        }
        Some(CapabilityDrop::new(span, items))
    }

    fn parse_cap_add(&mut self, field: &ParsedField) -> Option<CapabilityAdd> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(
                CAP_ADD_EXPECTED_SEQUENCE,
                field,
                "cap_add must be a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        let mut seen = BTreeMap::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    CAP_ADD_EXPECTED_STRING,
                    &node,
                    field.span,
                    "cap_add entries must be string scalars",
                );
                continue;
            };
            let scalar_type = ScalarValue::from_scalar(&scalar).scalar_type();
            if !matches!(
                scalar_type,
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    CAP_ADD_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "cap_add entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let value = scalar_string_from_source(&self.source, &scalar);
            if let Some(first) = seen.get(&value) {
                self.diagnostics.push(
                    Diagnostic::new(
                        CAP_ADD_DUPLICATE_ITEM,
                        Severity::Error,
                        "cap_add entries must be unique exact strings",
                    )
                    .with_label(DiagnosticLabel::primary(item_span, "duplicate capability string"))
                    .with_label(DiagnosticLabel::secondary(*first, "first identical string")),
                );
            } else {
                seen.insert(value.clone(), item_span);
            }
            items.push(CapabilityAddItem::new(Located::new(value, item_span)));
        }
        Some(CapabilityAdd::new(span, items))
    }

    fn parse_devices(&mut self, field: &ParsedField) -> Option<Devices> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(
                DEVICES_EXPECTED_SEQUENCE,
                field,
                "service devices must be a sequence of string scalars or mappings",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut devices = Vec::new();
        for node in sequence.values() {
            match node {
                YamlNode::Scalar(scalar)
                    if matches!(
                        ScalarValue::from_scalar(&scalar).scalar_type(),
                        ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
                    ) =>
                {
                    let item_span = span_from_position(self.source_id, scalar.byte_range());
                    let raw = Located::new(scalar_string_from_source(&self.source, &scalar), item_span);
                    devices.push(Device::Short(ShortDevice::new(raw)));
                }
                YamlNode::Mapping(mapping) => devices.push(Device::Long(self.parse_long_device(&mapping))),
                other => self.unsupported_sequence_item(
                    DEVICE_EXPECTED_FORM,
                    &other,
                    field.span,
                    "service device must use string short syntax or mapping long syntax",
                ),
            }
        }
        Some(Devices::new(span, devices))
    }

    fn parse_long_device(&mut self, mapping: &Mapping) -> LongDevice {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut device = LongDevice::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "source" if !duplicate => self
                    .parse_device_string(&field, "device source")
                    .into_iter()
                    .for_each(|value| device.set_source(value)),
                "target" if !duplicate => self
                    .parse_device_string(&field, "device target")
                    .into_iter()
                    .for_each(|value| device.set_target(value)),
                "permissions" if !duplicate => self
                    .parse_device_string(&field, "device permissions")
                    .into_iter()
                    .for_each(|value| device.set_permissions(value)),
                name if name.starts_with("x-") => device.push_extension(field.reference()),
                _ if duplicate => {}
                _ => device.push_unknown(field.reference()),
            }
        }
        if device.source().is_none() {
            self.missing(
                DEVICE_MISSING_SOURCE,
                span,
                "long service device is missing required string `source`",
            );
        }
        device
    }

    fn parse_device_string(&mut self, field: &ParsedField, description: &str) -> Option<Located<String>> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(
                DEVICE_EXPECTED_STRING,
                field,
                format!("{description} must be a string scalar"),
            );
            return None;
        };
        if !matches!(
            ScalarValue::from_scalar(scalar).scalar_type(),
            ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
        ) {
            self.expected(
                DEVICE_EXPECTED_STRING,
                field,
                format!("{description} must be a string scalar"),
            );
            return None;
        }
        Some(Located::new(
            scalar_string_from_source(&self.source, scalar),
            span_from_position(self.source_id, scalar.byte_range()),
        ))
    }

    fn parse_dns(&mut self, field: &ParsedField) -> Option<Dns> {
        let value = field.value.as_ref()?;
        if let Some(scalar) = value.as_scalar() {
            if !matches!(
                ScalarValue::from_scalar(scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.expected(
                    DNS_EXPECTED_FORM,
                    field,
                    "dns must be a string scalar or a sequence of string scalars",
                );
                return None;
            }
            let span = span_from_position(self.source_id, scalar.byte_range());
            return Some(Dns::new(
                span,
                DnsForm::Scalar(Located::new(scalar_string_from_source(&self.source, scalar), span)),
            ));
        }

        let Some(sequence) = value.as_sequence() else {
            self.expected(
                DNS_EXPECTED_FORM,
                field,
                "dns must be a string scalar or a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    DNS_EXPECTED_STRING,
                    &node,
                    field.span,
                    "dns entries must be string scalars",
                );
                continue;
            };
            if !matches!(
                ScalarValue::from_scalar(&scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    DNS_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "dns entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            items.push(Located::new(
                scalar_string_from_source(&self.source, &scalar),
                item_span,
            ));
        }
        Some(Dns::new(span, DnsForm::List(items)))
    }

    fn parse_dns_options(&mut self, field: &ParsedField) -> Option<DnsOptions> {
        let value = field.value.as_ref()?;
        let Some(sequence) = value.as_sequence() else {
            self.expected(
                DNS_OPT_EXPECTED_SEQUENCE,
                field,
                "dns_opt must be a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        let mut seen = BTreeSet::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    DNS_OPT_EXPECTED_STRING,
                    &node,
                    field.span,
                    "dns_opt entries must be string scalars",
                );
                continue;
            };
            if !matches!(
                ScalarValue::from_scalar(&scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    DNS_OPT_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "dns_opt entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let option = scalar_string_from_source(&self.source, &scalar);
            if !seen.insert(option.clone()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        DNS_OPT_DUPLICATE_ITEM,
                        Severity::Warning,
                        "dns_opt entries must be unique exact strings",
                    )
                    .with_label(DiagnosticLabel::primary(item_span, "duplicate DNS option retained")),
                );
            }
            items.push(Located::new(option, item_span));
        }
        Some(DnsOptions::new(span, items))
    }

    fn parse_dns_search(&mut self, field: &ParsedField) -> Option<DnsSearch> {
        let value = field.value.as_ref()?;
        if let Some(scalar) = value.as_scalar() {
            if !matches!(
                ScalarValue::from_scalar(scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.expected(
                    DNS_SEARCH_EXPECTED_FORM,
                    field,
                    "dns_search must be a string scalar or a sequence of string scalars",
                );
                return None;
            }
            let span = span_from_position(self.source_id, scalar.byte_range());
            return Some(DnsSearch::new(
                span,
                DnsSearchForm::Scalar(Located::new(scalar_string_from_source(&self.source, scalar), span)),
            ));
        }

        let Some(sequence) = value.as_sequence() else {
            self.expected(
                DNS_SEARCH_EXPECTED_FORM,
                field,
                "dns_search must be a string scalar or a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        let mut seen = BTreeSet::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    DNS_SEARCH_EXPECTED_STRING,
                    &node,
                    field.span,
                    "dns_search entries must be string scalars",
                );
                continue;
            };
            if !matches!(
                ScalarValue::from_scalar(&scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    DNS_SEARCH_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "dns_search entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let search = scalar_string_from_source(&self.source, &scalar);
            if !seen.insert(search.clone()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        DNS_SEARCH_DUPLICATE_ITEM,
                        Severity::Warning,
                        "dns_search schema entries are unique, but duplicate merge behavior is ambiguous",
                    )
                    .with_label(DiagnosticLabel::primary(
                        item_span,
                        "duplicate DNS search domain retained",
                    )),
                );
            }
            items.push(Located::new(search, item_span));
        }
        Some(DnsSearch::new(span, DnsSearchForm::List(items)))
    }

    fn parse_expose(&mut self, field: &ParsedField) -> Option<Expose> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(
                EXPOSE_EXPECTED_SEQUENCE,
                field,
                "expose must be a sequence of string or number scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        let mut seen = Vec::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    EXPOSE_EXPECTED_SCALAR,
                    &node,
                    field.span,
                    "expose entries must be string or number scalars",
                );
                continue;
            };
            let scalar_kind = match ScalarValue::from_scalar(&scalar).scalar_type() {
                ScalarType::Integer | ScalarType::Float => ExposeScalarKind::Number,
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex => ExposeScalarKind::String,
                ScalarType::Null | ScalarType::Boolean => {
                    self.unsupported_sequence_item(
                        EXPOSE_EXPECTED_SCALAR,
                        &YamlNode::Scalar(scalar),
                        field.span,
                        "expose entries must be string or number scalars",
                    );
                    continue;
                }
            };
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let raw = scalar_string_from_source(&self.source, &scalar);
            if seen.contains(&(scalar_kind, raw.clone())) {
                self.diagnostics.push(
                    Diagnostic::new(
                        EXPOSE_DUPLICATE_ITEM,
                        Severity::Warning,
                        "expose entries must be unique by exact scalar identity",
                    )
                    .with_label(DiagnosticLabel::primary(
                        item_span,
                        "duplicate exposed-port item retained",
                    )),
                );
            } else {
                seen.push((scalar_kind, raw.clone()));
            }
            let item = ExposeItem::parse(Located::new(raw, item_span), scalar_kind);
            self.diagnose_expose_item(&item);
            items.push(item);
        }
        Some(Expose::new(span, items))
    }

    fn diagnose_expose_item(&mut self, item: &ExposeItem) {
        match item.kind() {
            ExposeItemKind::Documented { .. } | ExposeItemKind::Expression => {}
            ExposeItemKind::Sctp { .. } | ExposeItemKind::UnknownProtocol { .. } => {
                self.diagnostics.push(
                    Diagnostic::new(
                        EXPOSE_PROVIDER_DEPENDENT,
                        Severity::Warning,
                        "expose protocol is outside the documented portable `tcp` and `udp` set",
                    )
                    .with_label(DiagnosticLabel::primary(
                        item.span(),
                        "provider-dependent exposed-port protocol retained",
                    ))
                    .with_note("ComposeLens does not normalize or reject the raw protocol spelling"),
                );
            }
            ExposeItemKind::Malformed => {
                self.diagnostics.push(
                    Diagnostic::new(
                        EXPOSE_INVALID_ITEM,
                        Severity::Error,
                        "expose item must be a decimal port or range with an optional protocol",
                    )
                    .with_label(DiagnosticLabel::primary(
                        item.span(),
                        "malformed exposed-port item retained",
                    ))
                    .with_note("use `PORT`, `START-END`, `PORT/tcp`, or `PORT/udp` for documented portable syntax"),
                );
            }
        }
    }

    fn parse_security_options(&mut self, field: &ParsedField) -> Option<SecurityOptions> {
        let value = field.value.as_ref()?;
        let Some(sequence) = value.as_sequence() else {
            self.expected(
                SECURITY_OPT_EXPECTED_SEQUENCE,
                field,
                "security_opt must be a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        let mut candidates = SecurityOptionCandidateCounts::default();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    SECURITY_OPT_EXPECTED_STRING,
                    &node,
                    field.span,
                    "security_opt entries must be string scalars",
                );
                continue;
            };
            if !matches!(
                ScalarValue::from_scalar(&scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    SECURITY_OPT_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "security_opt entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let raw = scalar_string_from_source(&self.source, &scalar);
            let item = SecurityOptionItem::parse(Located::new(raw, item_span));
            self.diagnose_security_option_item(item.kind(), item_span, &mut candidates);
            items.push(item);
        }
        Some(SecurityOptions::new(span, items))
    }

    fn diagnose_security_option_item(
        &mut self,
        kind: &SecurityOptionKind,
        span: SourceSpan,
        candidates: &mut SecurityOptionCandidateCounts,
    ) {
        let diagnostic = match kind {
            SecurityOptionKind::AppArmor { .. } => {
                candidates.apparmor += 1;
                (candidates.apparmor > 1).then(|| {
                    Diagnostic::new(
                        SECURITY_OPT_APPARMOR_CONFLICT,
                        Severity::Warning,
                        "multiple AppArmor candidates are retained; a consumer must resolve the conflict explicitly",
                    )
                    .with_label(DiagnosticLabel::primary(span, "additional AppArmor candidate retained"))
                })
            }
            SecurityOptionKind::AppArmorNearMiss => Some(
                Diagnostic::new(
                    SECURITY_OPT_APPARMOR_NEAR_MISS,
                    Severity::Warning,
                    "AppArmor candidates require exact lowercase `apparmor=<profile>` spelling without whitespace",
                )
                .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
            ),
            SecurityOptionKind::Seccomp { .. } => {
                candidates.seccomp += 1;
                (candidates.seccomp > 1).then(|| {
                    Diagnostic::new(
                        SECURITY_OPT_SECCOMP_CONFLICT,
                        Severity::Warning,
                        "multiple seccomp candidates are retained; a consumer must resolve the conflict explicitly",
                    )
                    .with_label(DiagnosticLabel::primary(span, "additional seccomp candidate retained"))
                })
            }
            SecurityOptionKind::SeccompNearMiss => Some(
                Diagnostic::new(
                    SECURITY_OPT_SECCOMP_NEAR_MISS,
                    Severity::Warning,
                    "seccomp candidates require exact lowercase `seccomp=<profile>` spelling without whitespace",
                )
                .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
            ),
            SecurityOptionKind::NoNewPrivileges { .. } => {
                candidates.no_new_privileges += 1;
                (candidates.no_new_privileges > 1).then(|| {
                    Diagnostic::new(
                        SECURITY_OPT_NO_NEW_PRIVILEGES_CONFLICT,
                        Severity::Warning,
                        "multiple no-new-privileges candidates are retained; a consumer must resolve the conflict explicitly",
                    )
                    .with_label(DiagnosticLabel::primary(
                        span,
                        "additional no-new-privileges candidate retained",
                    ))
                })
            }
            SecurityOptionKind::NoNewPrivilegesNearMiss => Some(
                Diagnostic::new(
                    SECURITY_OPT_NO_NEW_PRIVILEGES_NEAR_MISS,
                    Severity::Warning,
                    "no-new-privileges candidates require exact lowercase `no-new-privileges:true` or `no-new-privileges:false` spelling without whitespace",
                )
                .with_label(DiagnosticLabel::primary(span, "raw near-miss security option retained")),
            ),
            SecurityOptionKind::Mask { .. }
            | SecurityOptionKind::MaskNearMiss
            | SecurityOptionKind::Unmask { .. }
            | SecurityOptionKind::UnmaskNearMiss => security_path_option_diagnostic(kind, span),
            SecurityOptionKind::SecurityLabelDisable { .. }
            | SecurityOptionKind::SecurityLabelDisableNearMiss
            | SecurityOptionKind::SecurityLabelFileType { .. }
            | SecurityOptionKind::SecurityLabelFileTypeNearMiss
            | SecurityOptionKind::SecurityLabelLevel { .. }
            | SecurityOptionKind::SecurityLabelLevelNearMiss
            | SecurityOptionKind::SecurityLabelNested { .. }
            | SecurityOptionKind::SecurityLabelNestedNearMiss
            | SecurityOptionKind::SecurityLabelType { .. }
            | SecurityOptionKind::SecurityLabelTypeNearMiss => {
                authored_security_label_diagnostic(kind, span, candidates)
            }
            SecurityOptionKind::Empty => Some(
                Diagnostic::new(
                    SECURITY_OPT_EMPTY_ITEM,
                    Severity::Error,
                    "security_opt entries must not be empty strings",
                )
                .with_label(DiagnosticLabel::primary(span, "empty security option retained")),
            ),
            SecurityOptionKind::Expression | SecurityOptionKind::Other => None,
        };
        if let Some(diagnostic) = diagnostic {
            self.diagnostics.push(diagnostic);
        }
    }

    fn parse_tmpfs(&mut self, field: &ParsedField) -> Option<Tmpfs> {
        let value = field.value.as_ref()?;
        if let Some(scalar) = value.as_scalar() {
            if !matches!(
                ScalarValue::from_scalar(scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.expected(
                    TMPFS_EXPECTED_FORM,
                    field,
                    "tmpfs must be a string scalar or a sequence of string scalars",
                );
                return None;
            }
            let span = span_from_position(self.source_id, scalar.byte_range());
            let item = TmpfsItem::parse(Located::new(scalar_string_from_source(&self.source, scalar), span));
            self.diagnose_tmpfs_item(&item);
            return Some(Tmpfs::new(span, TmpfsForm::Scalar(item)));
        }

        let Some(sequence) = value.as_sequence() else {
            self.expected(
                TMPFS_EXPECTED_FORM,
                field,
                "tmpfs must be a string scalar or a sequence of string scalars",
            );
            return None;
        };
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut items = Vec::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    TMPFS_EXPECTED_STRING,
                    &node,
                    field.span,
                    "tmpfs entries must be string scalars",
                );
                continue;
            };
            if !matches!(
                ScalarValue::from_scalar(&scalar).scalar_type(),
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
            ) {
                self.unsupported_sequence_item(
                    TMPFS_EXPECTED_STRING,
                    &YamlNode::Scalar(scalar),
                    field.span,
                    "tmpfs entries must be string scalars",
                );
                continue;
            }
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let raw = scalar_string_from_source(&self.source, &scalar);
            let item = TmpfsItem::parse(Located::new(raw, item_span));
            self.diagnose_tmpfs_item(&item);
            items.push(item);
        }
        Some(Tmpfs::new(span, TmpfsForm::List(items)))
    }

    fn diagnose_tmpfs_item(&mut self, item: &TmpfsItem) {
        if item.kind() != TmpfsItemKind::ProviderDependent {
            return;
        }
        self.diagnostics.push(
            Diagnostic::new(
                TMPFS_PROVIDER_DEPENDENT,
                Severity::Warning,
                "tmpfs item is malformed or uses provider- or target-specific options",
            )
            .with_label(DiagnosticLabel::primary(
                item.span(),
                "provider-dependent temporary-filesystem item",
            ))
            .with_note("use a non-empty path with only non-empty `mode`, `uid`, or `gid` assignments for documented portable syntax"),
        );
    }

    fn parse_sysctls(&mut self, field: &ParsedField) -> Option<Sysctls> {
        match field.value.as_ref() {
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let mut entries = Vec::new();
                let mut seen = BTreeMap::new();
                for entry in self.fields(mapping) {
                    if self.record_duplicate(&mut seen, &entry) {
                        continue;
                    }
                    if entry.name.value.is_empty() {
                        self.diagnostics.push(
                            Diagnostic::new(
                                SYSCTLS_EMPTY_KEY,
                                Severity::Error,
                                "sysctls mapping keys must not be empty",
                            )
                            .with_label(DiagnosticLabel::primary(entry.name.span, "empty sysctl name")),
                        );
                        continue;
                    }
                    if entry.value.as_ref().is_some_and(|value| value.as_scalar().is_none()) {
                        self.diagnostics.push(
                            Diagnostic::new(
                                SYSCTLS_EXPECTED_SCALAR,
                                Severity::Error,
                                "sysctls mapping values must be scalar strings, numbers, booleans, or null",
                            )
                            .with_label(DiagnosticLabel::primary(
                                entry.value_span.unwrap_or(entry.span),
                                "non-scalar sysctl value",
                            )),
                        );
                        continue;
                    }
                    let Some(value) = self.parse_compose_scalar(&entry, "sysctls mapping values must be scalars")
                    else {
                        continue;
                    };
                    entries.push(KeyValueEntry::new(entry.name, value, entry.span));
                }
                Some(Sysctls::new(span, SysctlsForm::Map(entries)))
            }
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let mut items = Vec::new();
                let mut seen = BTreeMap::new();
                for node in sequence.values() {
                    let YamlNode::Scalar(scalar) = node else {
                        self.unsupported_sequence_item(
                            SYSCTLS_EXPECTED_STRING,
                            &node,
                            field.span,
                            "sysctls list entries must be YAML string scalars",
                        );
                        continue;
                    };
                    if !matches!(
                        ScalarValue::from_scalar(&scalar).scalar_type(),
                        ScalarType::String | ScalarType::Timestamp | ScalarType::Regex
                    ) {
                        self.unsupported_sequence_item(
                            SYSCTLS_EXPECTED_STRING,
                            &YamlNode::Scalar(scalar),
                            field.span,
                            "sysctls list entries must be YAML string scalars",
                        );
                        continue;
                    }
                    let item_span = span_from_position(self.source_id, scalar.byte_range());
                    let value = scalar_string_from_source(&self.source, &scalar);
                    if let Some(first) = seen.get(&value) {
                        self.diagnostics.push(
                            Diagnostic::new(
                                SYSCTLS_DUPLICATE_ITEM,
                                Severity::Error,
                                "sysctls list entries must be unique exact strings",
                            )
                            .with_label(DiagnosticLabel::primary(item_span, "duplicate sysctl string"))
                            .with_label(DiagnosticLabel::secondary(*first, "first identical string")),
                        );
                    } else {
                        seen.insert(value.clone(), item_span);
                    }
                    items.push(Located::new(value, item_span));
                }
                Some(Sysctls::new(span, SysctlsForm::List(items)))
            }
            _ => {
                self.expected(
                    SYSCTLS_EXPECTED_FORM,
                    field,
                    "sysctls must be a mapping or a sequence of string scalars",
                );
                None
            }
        }
    }

    fn parse_restart_policy(&mut self, field: &ParsedField) -> Option<RestartPolicy> {
        let value = self.parse_string(field, "service restart policy")?;
        let policy = RestartPolicy::parse(value);
        if !policy.is_valid() {
            self.diagnostics.push(
                Diagnostic::new(
                    RESTART_INVALID_POLICY,
                    Severity::Error,
                    "restart must be `no`, `always`, `on-failure[:max-retries]`, `unless-stopped`, or interpolation",
                )
                .with_label(DiagnosticLabel::primary(
                    policy.raw().span(),
                    "invalid service restart policy",
                )),
            );
        }
        Some(policy)
    }

    fn parse_pids_limit(&mut self, field: &ParsedField) -> Option<PidsLimit> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(
                PIDS_LIMIT_EXPECTED_VALUE,
                field,
                "pids_limit must be a number or string scalar",
            );
            return None;
        };
        if matches!(
            ScalarValue::from_scalar(scalar).scalar_type(),
            ScalarType::Boolean | ScalarType::Null
        ) {
            self.expected(
                PIDS_LIMIT_EXPECTED_VALUE,
                field,
                "pids_limit must be a number or string scalar",
            );
            return None;
        }
        let span = span_from_position(self.source_id, scalar.byte_range());
        let limit = PidsLimit::parse(Located::new(scalar_string_from_source(&self.source, scalar), span));
        match limit.kind() {
            PidsLimitKind::Zero => self.diagnostics.push(
                Diagnostic::new(
                    PIDS_LIMIT_AMBIGUOUS_ZERO,
                    Severity::Warning,
                    "pids_limit zero is preserved as an ambiguous and unportable native state",
                )
                .with_label(DiagnosticLabel::primary(span, "ambiguous zero PID limit")),
            ),
            PidsLimitKind::Other => self.diagnostics.push(
                Diagnostic::new(
                    PIDS_LIMIT_INVALID,
                    Severity::Error,
                    "pids_limit must be `-1`, a positive integral decimal, or interpolation",
                )
                .with_label(DiagnosticLabel::primary(span, "unsupported service PID limit")),
            ),
            _ => {}
        }
        Some(limit)
    }

    fn parse_shm_size(&mut self, field: &ParsedField) -> Option<ShmSize> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(
                SHM_SIZE_EXPECTED_VALUE,
                field,
                "shm_size must be a YAML number or string scalar",
            );
            return None;
        };
        let scalar_kind = match ScalarValue::from_scalar(scalar).scalar_type() {
            ScalarType::Integer | ScalarType::Float => ShmSizeScalarKind::Number,
            ScalarType::String | ScalarType::Timestamp | ScalarType::Regex => ShmSizeScalarKind::String,
            ScalarType::Boolean | ScalarType::Null => {
                self.expected(
                    SHM_SIZE_EXPECTED_VALUE,
                    field,
                    "shm_size must be a YAML number or string scalar",
                );
                return None;
            }
        };
        let span = span_from_position(self.source_id, scalar.byte_range());
        let size = ShmSize::parse(
            Located::new(scalar_string_from_source(&self.source, scalar), span),
            scalar_kind,
        );
        self.diagnose_shm_size(&size);
        Some(size)
    }

    fn diagnose_shm_size(&mut self, size: &ShmSize) {
        let (code, message, label, note) = match size.kind() {
            ShmSizeKind::Zero { .. } => (
                SHM_SIZE_AMBIGUOUS_ZERO,
                "shm_size zero is preserved because Compose does not define its semantics",
                "ambiguous zero shared-memory size",
                "choose a positive size with an explicit documented lowercase unit",
            ),
            ShmSizeKind::ProviderDependentNumber => (
                SHM_SIZE_PROVIDER_DEPENDENT_NUMBER,
                "numeric shm_size is schema-accepted but lacks a documented explicit unit",
                "provider-dependent numeric shared-memory size",
                "use a positive quoted value with `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` for portable intent",
            ),
            ShmSizeKind::ProviderDependentString => (
                SHM_SIZE_PROVIDER_DEPENDENT_STRING,
                "string shm_size is schema-accepted but falls outside the documented lowercase suffix family",
                "provider-dependent string shared-memory size",
                "use an explicit lowercase `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` suffix when that is the intended unit",
            ),
            ShmSizeKind::Documented { .. } | ShmSizeKind::Expression => return,
        };
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Warning, message)
                .with_label(DiagnosticLabel::primary(size.raw().span(), label))
                .with_note(note),
        );
    }

    fn parse_mem_limit(&mut self, field: &ParsedField) -> Option<MemLimit> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(
                MEM_LIMIT_EXPECTED_VALUE,
                field,
                "mem_limit must be a YAML number or string scalar",
            );
            return None;
        };
        let scalar_kind = match ScalarValue::from_scalar(scalar).scalar_type() {
            ScalarType::Integer | ScalarType::Float => MemLimitScalarKind::Number,
            ScalarType::String | ScalarType::Timestamp | ScalarType::Regex => MemLimitScalarKind::String,
            ScalarType::Boolean | ScalarType::Null => {
                self.expected(
                    MEM_LIMIT_EXPECTED_VALUE,
                    field,
                    "mem_limit must be a YAML number or string scalar",
                );
                return None;
            }
        };
        let span = span_from_position(self.source_id, scalar.byte_range());
        let limit = MemLimit::parse(
            Located::new(scalar_string_from_source(&self.source, scalar), span),
            scalar_kind,
        );
        self.diagnose_mem_limit(&limit);
        Some(limit)
    }

    fn diagnose_mem_limit(&mut self, limit: &MemLimit) {
        let (code, message, label, note) = match limit.kind() {
            MemLimitKind::Zero { .. } => (
                MEM_LIMIT_AMBIGUOUS_ZERO,
                "mem_limit zero is preserved without inferring portable runtime behavior",
                "ambiguous zero memory limit",
                "choose a positive size with an explicit documented lowercase unit",
            ),
            MemLimitKind::SchemaNumber => (
                MEM_LIMIT_SCHEMA_NUMBER,
                "numeric mem_limit is schema-accepted but lacks a documented explicit unit",
                "schema-only numeric memory limit",
                "use a positive quoted value with `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` for explicit intent",
            ),
            MemLimitKind::ProviderDependentString => (
                MEM_LIMIT_PROVIDER_DEPENDENT_STRING,
                "string mem_limit is schema-accepted but falls outside the documented lowercase suffix family",
                "provider-dependent string memory limit",
                "use an explicit lowercase `b`, `k`, `kb`, `m`, `mb`, `g`, or `gb` suffix when that is the intended unit",
            ),
            MemLimitKind::Documented { .. } | MemLimitKind::Expression => return,
        };
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Warning, message)
                .with_label(DiagnosticLabel::primary(limit.raw().span(), label))
                .with_note(note),
        );
    }

    fn parse_pull_policy(&mut self, field: &ParsedField) -> Option<PullPolicy> {
        let value = self.parse_string(field, "service pull policy")?;
        let policy = PullPolicy::parse(value);
        if !policy.is_recognized() {
            self.diagnostics.push(
                Diagnostic::new(
                    PULL_POLICY_INVALID,
                    Severity::Error,
                    "pull_policy must be a documented Compose policy, the retained `if_not_present` alias, schema-only `refresh`, an `every_` interval matching integer `w`, `d`, `h`, `m`, and `s` components, or interpolation",
                )
                .with_label(DiagnosticLabel::primary(
                    policy.raw().span(),
                    "invalid or provider-specific service pull policy",
                )),
            );
        }
        Some(policy)
    }

    fn parse_stop_grace_period(&mut self, field: &ParsedField) -> Option<Located<StopGracePeriod>> {
        let value = self.parse_string(field, "service stop grace period")?;
        let period = StopGracePeriod::parse(value.value);
        if !period.is_valid() {
            self.diagnostics.push(
                Diagnostic::new(
                    STOP_GRACE_PERIOD_INVALID,
                    Severity::Error,
                    "stop_grace_period must match the ComposeLens duration policy using `us`, `ms`, `s`, `m`, or `h`, or contain an interpolation marker",
                )
                .with_label(DiagnosticLabel::primary(
                    value.span,
                    "invalid service stop grace period",
                )),
            );
        }
        Some(Located::new(period, value.span))
    }

    fn parse_command(&mut self, field: &ParsedField) -> Option<Command> {
        match field.value.as_ref() {
            Some(YamlNode::Scalar(scalar)) => {
                let span = span_from_position(self.source_id, scalar.byte_range());
                if ScalarValue::from_scalar(scalar).scalar_type() == ScalarType::Null {
                    Some(Command::Null(span))
                } else {
                    Some(Command::String(Located::new(
                        scalar_string_from_source(&self.source, scalar),
                        span,
                    )))
                }
            }
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let values =
                    self.parse_scalar_nodes(sequence.values(), field.span, "command list items must be scalars");
                Some(Command::List { span, values })
            }
            _ => {
                self.expected(
                    EXPECTED_FIELD_FORM,
                    field,
                    "command must be null, a scalar, or a sequence",
                );
                None
            }
        }
    }

    fn parse_entrypoint(&mut self, field: &ParsedField) -> Option<Entrypoint> {
        match field.value.as_ref() {
            Some(YamlNode::Scalar(scalar)) => {
                let span = span_from_position(self.source_id, scalar.byte_range());
                if ScalarValue::from_scalar(scalar).scalar_type() == ScalarType::Null {
                    Some(Entrypoint::Null(span))
                } else {
                    Some(Entrypoint::String(Located::new(
                        scalar_string_from_source(&self.source, scalar),
                        span,
                    )))
                }
            }
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let values =
                    self.parse_scalar_nodes(sequence.values(), field.span, "entrypoint list items must be scalars");
                Some(Entrypoint::List { span, values })
            }
            _ => {
                self.expected(
                    EXPECTED_FIELD_FORM,
                    field,
                    "entrypoint must be null, a scalar, or a sequence",
                );
                None
            }
        }
    }

    fn parse_environment(&mut self, field: &ParsedField) -> Option<Environment> {
        match field.value.as_ref() {
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let entries = self
                    .parse_scalar_nodes(sequence.values(), field.span, "environment list items must be scalars")
                    .into_iter()
                    .map(EnvironmentListEntry::parse)
                    .collect();
                Some(Environment::List { span, entries })
            }
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let entries = self.parse_environment_map(mapping);
                Some(Environment::Map { span, entries })
            }
            _ => {
                self.expected(EXPECTED_FIELD_FORM, field, "environment must be a sequence or mapping");
                None
            }
        }
    }

    fn parse_environment_map(&mut self, mapping: &Mapping) -> Vec<EnvironmentMapEntry> {
        let mut entries = Vec::new();
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            if self.record_duplicate(&mut seen, &field) {
                continue;
            }
            let value = self.parse_compose_scalar(&field, "environment values must be scalars");
            if let Some(value) = value {
                entries.push(EnvironmentMapEntry::new(field.name, value, field.span));
            }
        }
        entries
    }

    fn parse_environment_files(&mut self, field: &ParsedField) -> Vec<EnvironmentFile> {
        match field.value.as_ref() {
            Some(YamlNode::Scalar(_)) => self
                .parse_string(field, "service environment-file path")
                .map(EnvironmentFile::Short)
                .into_iter()
                .collect(),
            Some(YamlNode::Sequence(sequence)) => sequence
                .values()
                .filter_map(|value| match value {
                    YamlNode::Scalar(scalar) => {
                        let span = span_from_position(self.source_id, scalar.byte_range());
                        Some(EnvironmentFile::Short(Located::new(
                            scalar_string_from_source(&self.source, &scalar),
                            span,
                        )))
                    }
                    YamlNode::Mapping(mapping) => Some(EnvironmentFile::Long(Box::new(
                        self.parse_long_environment_file(&mapping),
                    ))),
                    _ => {
                        self.diagnostics.push(
                            Diagnostic::new(
                                ENVIRONMENT_FILE_EXPECTED_FORM,
                                Severity::Error,
                                "env_file item must use scalar short syntax or mapping long syntax",
                            )
                            .with_label(DiagnosticLabel::primary(
                                node_span(self.source_id, &value).unwrap_or(field.span),
                                "invalid environment-file item",
                            )),
                        );
                        None
                    }
                })
                .collect(),
            _ => {
                self.expected(
                    EXPECTED_FIELD_FORM,
                    field,
                    "env_file must be a scalar path or a sequence of short/long entries",
                );
                Vec::new()
            }
        }
    }

    fn parse_long_environment_file(&mut self, mapping: &Mapping) -> LongEnvironmentFile {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut environment_file = LongEnvironmentFile::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "path" if !duplicate => self
                    .parse_string(&field, "environment-file path")
                    .into_iter()
                    .for_each(|value| environment_file.set_path(value)),
                "required" if !duplicate => self
                    .parse_boolean(&field, "environment-file required option")
                    .into_iter()
                    .for_each(|value| environment_file.set_required(value)),
                "format" if !duplicate => {
                    if let Some(raw) = self.parse_string(&field, "environment-file format") {
                        let format = EnvironmentFileFormat::parse(raw);
                        if !format.is_valid() {
                            self.diagnostics.push(
                                Diagnostic::new(
                                    ENVIRONMENT_FILE_INVALID_FORMAT,
                                    Severity::Error,
                                    "environment-file format must be `raw` or interpolation",
                                )
                                .with_label(DiagnosticLabel::primary(format.raw().span(), "invalid format")),
                            );
                        }
                        environment_file.set_format(format);
                    }
                }
                name if name.starts_with("x-") => environment_file.push_extension(field.reference()),
                _ if duplicate => {}
                _ => environment_file.push_unknown(field.reference()),
            }
        }
        if environment_file.path().is_none() {
            self.missing(
                ENVIRONMENT_FILE_MISSING_PATH,
                span,
                "long environment-file entry is missing `path`",
            );
        }
        environment_file
    }

    fn parse_extra_hosts(&mut self, field: &ParsedField) -> Option<ExtraHosts> {
        match field.value.as_ref() {
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let entries = self
                    .parse_scalar_nodes(sequence.values(), field.span, "extra_hosts entries must be scalars")
                    .into_iter()
                    .map(|raw| {
                        let entry = ShortExtraHost::parse(raw);
                        if !entry.is_complete() {
                            self.diagnostics.push(
                                Diagnostic::new(
                                    EXTRA_HOST_INVALID_ENTRY,
                                    Severity::Error,
                                    "short extra_hosts entry must contain a hostname and address",
                                )
                                .with_label(DiagnosticLabel::primary(
                                    entry.raw().span(),
                                    "missing separator or value",
                                )),
                            );
                        }
                        entry
                    })
                    .collect();
                Some(ExtraHosts::Short { span, entries })
            }
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let mut entries = Vec::new();
                let mut seen = BTreeMap::new();
                for host in self.fields(mapping) {
                    if self.record_duplicate(&mut seen, &host) {
                        continue;
                    }
                    if let Some(address) = self.parse_string(&host, "extra host address") {
                        let address = Located::new(HostAddress::parse(address.value), address.span);
                        entries.push(LongExtraHost::new(host.name, address, host.span));
                    }
                }
                Some(ExtraHosts::Long { span, entries })
            }
            _ => {
                self.expected(EXPECTED_FIELD_FORM, field, "extra_hosts must be a sequence or mapping");
                None
            }
        }
    }

    fn parse_ulimits(&mut self, field: &ParsedField) -> Option<Ulimits> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, "ulimits must be a mapping");
            return None;
        };
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut entries = Vec::new();
        let mut seen = BTreeMap::new();
        for limit in self.fields(mapping) {
            if self.record_duplicate(&mut seen, &limit) {
                continue;
            }
            if !valid_ulimit_name(limit.name.value()) {
                self.diagnostics.push(
                    Diagnostic::new(
                        ULIMIT_INVALID_NAME,
                        Severity::Error,
                        "ulimit names must contain only lowercase ASCII letters",
                    )
                    .with_label(DiagnosticLabel::primary(limit.name.span, "invalid ulimit name")),
                );
            }
            let value = match limit.value.as_ref() {
                Some(YamlNode::Scalar(_)) => self.parse_limit_value(&limit, "ulimit value").map(UlimitValue::Single),
                Some(YamlNode::Mapping(range)) => Some(UlimitValue::Range(self.parse_ulimit_range(range))),
                _ => {
                    self.expected(
                        EXPECTED_FIELD_FORM,
                        &limit,
                        "ulimit must be a scalar or soft/hard mapping",
                    );
                    None
                }
            };
            if let Some(value) = value {
                entries.push(Ulimit::new(limit.name, limit.span, value));
            }
        }
        Some(Ulimits::new(span, entries))
    }

    fn parse_ulimit_range(&mut self, mapping: &Mapping) -> UlimitRange {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut range = UlimitRange::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "soft" if !duplicate => self
                    .parse_limit_value(&field, "ulimit soft value")
                    .into_iter()
                    .for_each(|value| range.set_soft(value)),
                "hard" if !duplicate => self
                    .parse_limit_value(&field, "ulimit hard value")
                    .into_iter()
                    .for_each(|value| range.set_hard(value)),
                name if name.starts_with("x-") => range.push_extension(field.reference()),
                _ if duplicate => {}
                _ => range.push_unknown(field.reference()),
            }
        }
        if range.soft().is_none() {
            self.missing(
                ULIMIT_MISSING_RANGE_MEMBER,
                span,
                "ulimit range is missing required `soft`",
            );
        }
        if range.hard().is_none() {
            self.missing(
                ULIMIT_MISSING_RANGE_MEMBER,
                span,
                "ulimit range is missing required `hard`",
            );
        }
        range
    }

    fn parse_limit_value(&mut self, field: &ParsedField, description: &str) -> Option<Located<LimitValue>> {
        let value = self.parse_string(field, description)?;
        let parsed = LimitValue::parse(value.value);
        if !parsed.is_valid() {
            self.diagnostics.push(
                Diagnostic::new(
                    ULIMIT_INVALID_VALUE,
                    Severity::Error,
                    "ulimit must be -1, a non-negative integer, or an interpolation expression",
                )
                .with_label(DiagnosticLabel::primary(value.span, "invalid ulimit value")),
            );
        }
        Some(Located::new(parsed, value.span))
    }

    fn parse_depends_on(&mut self, field: &ParsedField) -> Option<DependsOn> {
        match field.value.as_ref() {
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let services = self.parse_scalar_nodes(
                    sequence.values(),
                    field.span,
                    "dependency service names must be scalars",
                );
                Some(DependsOn::Short { span, services })
            }
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let mut services = Vec::new();
                let mut seen = BTreeMap::new();
                for dependency in self.fields(mapping) {
                    if self.record_duplicate(&mut seen, &dependency) {
                        continue;
                    }
                    let mut parsed = ServiceDependency::new(dependency.name.clone(), dependency.span);
                    if Self::field_is_null(&dependency) {
                        services.push(parsed);
                        continue;
                    }
                    let Some(options) = dependency.value.as_ref().and_then(YamlNode::as_mapping) else {
                        self.expected(
                            EXPECTED_MAPPING,
                            &dependency,
                            "long dependency options must be a mapping or null",
                        );
                        continue;
                    };
                    let mut option_seen = BTreeMap::new();
                    for option in self.fields(options) {
                        let duplicate = self.record_duplicate(&mut option_seen, &option);
                        match option.name.value.as_str() {
                            "condition" if !duplicate => {
                                if let Some(value) = self.parse_string(&option, "dependency condition") {
                                    let condition = DependencyCondition::parse(value.value);
                                    if !condition.is_known() {
                                        self.diagnostics.push(
                                            Diagnostic::new(
                                                DEPENDENCY_INVALID_CONDITION,
                                                Severity::Error,
                                                "dependency condition is not defined by Compose",
                                            )
                                            .with_label(
                                                DiagnosticLabel::primary(value.span, "unknown dependency condition"),
                                            ),
                                        );
                                    }
                                    parsed.set_condition(Located::new(condition, value.span));
                                }
                            }
                            "restart" if !duplicate => self
                                .parse_boolean(&option, "dependency restart")
                                .into_iter()
                                .for_each(|value| parsed.set_restart(value)),
                            "required" if !duplicate => self
                                .parse_boolean(&option, "dependency required")
                                .into_iter()
                                .for_each(|value| parsed.set_required(value)),
                            name if name.starts_with("x-") => parsed.push_extension(option.reference()),
                            _ if duplicate => {}
                            _ => parsed.push_unknown(option.reference()),
                        }
                    }
                    services.push(parsed);
                }
                Some(DependsOn::Long { span, services })
            }
            _ => {
                self.expected(EXPECTED_FIELD_FORM, field, "depends_on must be a sequence or mapping");
                None
            }
        }
    }

    fn parse_healthcheck(&mut self, field: &ParsedField) -> Option<Healthcheck> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, "healthcheck must be a mapping");
            return None;
        };
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut healthcheck = Healthcheck::new(span);
        let mut seen = BTreeMap::new();
        for option in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &option);
            match option.name.value.as_str() {
                "test" if !duplicate => self
                    .parse_healthcheck_test(&option)
                    .into_iter()
                    .for_each(|value| healthcheck.set_test(value)),
                "interval" if !duplicate => self
                    .parse_healthcheck_duration(&option, "healthcheck interval")
                    .into_iter()
                    .for_each(|value| healthcheck.set_interval(value)),
                "timeout" if !duplicate => self
                    .parse_healthcheck_duration(&option, "healthcheck timeout")
                    .into_iter()
                    .for_each(|value| healthcheck.set_timeout(value)),
                "retries" if !duplicate => self
                    .parse_healthcheck_retries(&option)
                    .into_iter()
                    .for_each(|value| healthcheck.set_retries(value)),
                "start_period" if !duplicate => self
                    .parse_healthcheck_duration(&option, "healthcheck start period")
                    .into_iter()
                    .for_each(|value| healthcheck.set_start_period(value)),
                "start_interval" if !duplicate => self
                    .parse_healthcheck_duration(&option, "healthcheck start interval")
                    .into_iter()
                    .for_each(|value| healthcheck.set_start_interval(value)),
                "disable" if !duplicate => self
                    .parse_boolean(&option, "healthcheck disable")
                    .into_iter()
                    .for_each(|value| healthcheck.set_disable(value)),
                name if name.starts_with("x-") => healthcheck.push_extension(option.reference()),
                _ if duplicate => {}
                _ => healthcheck.push_unknown(option.reference()),
            }
        }
        Some(healthcheck)
    }

    fn parse_healthcheck_duration(
        &mut self,
        field: &ParsedField,
        description: &str,
    ) -> Option<Located<HealthcheckDuration>> {
        let value = self.parse_string(field, description)?;
        let duration = HealthcheckDuration::parse(value.value);
        if !duration.is_valid() {
            self.diagnostics.push(
                Diagnostic::new(
                    HEALTHCHECK_INVALID_DURATION,
                    Severity::Error,
                    "healthcheck duration must use Compose duration syntax or interpolation",
                )
                .with_label(DiagnosticLabel::primary(value.span, "invalid healthcheck duration")),
            );
        }
        Some(Located::new(duration, value.span))
    }

    fn parse_healthcheck_retries(&mut self, field: &ParsedField) -> Option<Located<HealthcheckRetries>> {
        let value = self.parse_string(field, "healthcheck retries")?;
        let retries = HealthcheckRetries::parse(value.value);
        if !retries.is_valid() {
            self.diagnostics.push(
                Diagnostic::new(
                    HEALTHCHECK_INVALID_RETRIES,
                    Severity::Error,
                    "healthcheck retries must be a non-negative integer or interpolation expression",
                )
                .with_label(DiagnosticLabel::primary(value.span, "invalid healthcheck retry count")),
            );
        }
        Some(Located::new(retries, value.span))
    }

    fn parse_healthcheck_test(&mut self, field: &ParsedField) -> Option<HealthcheckTest> {
        match field.value.as_ref() {
            Some(YamlNode::Scalar(_)) => self
                .parse_string(field, "healthcheck test")
                .map(HealthcheckTest::String),
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let values =
                    self.parse_scalar_nodes(sequence.values(), field.span, "healthcheck test items must be scalars");
                let kind = values.first().map(|value| HealthcheckTestKind::parse(value.value()));
                if kind.is_none()
                    || kind == Some(HealthcheckTestKind::Other)
                    || (kind == Some(HealthcheckTestKind::None) && values.len() != 1)
                {
                    self.diagnostics.push(
                        Diagnostic::new(
                            HEALTHCHECK_INVALID_TEST,
                            Severity::Error,
                            "healthcheck list must begin with NONE, CMD, or CMD-SHELL",
                        )
                        .with_label(DiagnosticLabel::primary(span, "invalid healthcheck command mode")),
                    );
                }
                Some(HealthcheckTest::List { span, kind, values })
            }
            _ => {
                self.expected(
                    EXPECTED_FIELD_FORM,
                    field,
                    "healthcheck test must be a scalar or sequence",
                );
                None
            }
        }
    }

    fn parse_build(&mut self, field: &ParsedField) -> Option<Build> {
        match field.value.as_ref() {
            Some(YamlNode::Scalar(_)) => self.parse_string(field, "build context").map(Build::Context),
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let mut definition = BuildDefinition::new(span);
                let mut seen = BTreeMap::new();
                for option in self.fields(mapping) {
                    let duplicate = self.record_duplicate(&mut seen, &option);
                    if duplicate {
                        continue;
                    }
                    if let Some(kind) = BuildFieldKind::from_name(option.name.value()) {
                        definition.push_field(BuildField::new(kind, option.reference()));
                    } else if option.name.value().starts_with("x-") {
                        definition.push_extension(option.reference());
                    } else {
                        definition.push_unknown(option.reference());
                    }
                }
                Some(Build::Definition(definition))
            }
            _ => {
                self.expected(EXPECTED_FIELD_FORM, field, "build must be a scalar context or mapping");
                None
            }
        }
    }

    fn parse_deploy(&mut self, field: &ParsedField) -> Option<DeployDefinition> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, "deploy must be a mapping");
            return None;
        };
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut definition = DeployDefinition::new(span);
        let mut seen = BTreeMap::new();
        for option in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &option);
            if duplicate {
                continue;
            }
            if let Some(kind) = DeployFieldKind::from_name(option.name.value()) {
                definition.push_field(DeployField::new(kind, option.reference()));
            } else if option.name.value().starts_with("x-") {
                definition.push_extension(option.reference());
            } else {
                definition.push_unknown(option.reference());
            }
        }
        Some(definition)
    }

    fn source_column(&self, offset: usize) -> usize {
        let prefix = self.source.get(..offset).unwrap_or_default();
        let line_start = prefix.rfind('\n').map_or(0, |index| index + 1);
        self.source[line_start..offset].chars().count()
    }

    fn parse_service_ports(&mut self, field: &ParsedField) -> Vec<Port> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(EXPECTED_SEQUENCE, field, "service ports must be a sequence");
            return Vec::new();
        };

        let mut ports = Vec::new();
        for value in sequence.values() {
            match value {
                YamlNode::Scalar(scalar) => {
                    let span = span_from_position(self.source_id, scalar.byte_range());
                    ports.push(Port::Short(ShortPort::parse(Located::new(
                        scalar_string_from_source(&self.source, &scalar),
                        span,
                    ))));
                }
                YamlNode::Mapping(mapping) => {
                    ports.push(Port::Long(Box::new(self.parse_long_port(&mapping))));
                }
                other => self.unsupported_sequence_item(
                    PORT_EXPECTED_FORM,
                    &other,
                    field.span,
                    "service port must use scalar short syntax or mapping long syntax",
                ),
            }
        }
        ports
    }

    fn parse_long_port(&mut self, mapping: &Mapping) -> LongPort {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut port = LongPort::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "target" if !duplicate => self
                    .parse_string(&field, "port target")
                    .into_iter()
                    .for_each(|value| port.set_target(value)),
                "published" if !duplicate => self
                    .parse_string(&field, "published port")
                    .into_iter()
                    .for_each(|value| port.set_published(value)),
                "host_ip" if !duplicate => self
                    .parse_string(&field, "port host IP")
                    .into_iter()
                    .for_each(|value| port.set_host_ip(value)),
                "protocol" if !duplicate => self
                    .parse_string(&field, "port protocol")
                    .into_iter()
                    .for_each(|value| port.set_protocol(value)),
                "app_protocol" if !duplicate => self
                    .parse_string(&field, "port application protocol")
                    .into_iter()
                    .for_each(|value| port.set_app_protocol(value)),
                "mode" if !duplicate => self
                    .parse_string(&field, "port mode")
                    .into_iter()
                    .for_each(|value| port.set_mode(value)),
                "name" if !duplicate => self
                    .parse_string(&field, "port name")
                    .into_iter()
                    .for_each(|value| port.set_name(value)),
                name if name.starts_with("x-") => port.push_extension(field.reference()),
                _ if duplicate => {}
                _ => port.push_unknown(field.reference()),
            }
        }
        if port.target().is_none() {
            self.missing(PORT_MISSING_TARGET, span, "long port is missing `target`");
        }
        port
    }

    fn parse_service_networks(&mut self, field: &ParsedField) -> Option<ServiceNetworks> {
        match field.value.as_ref() {
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let names =
                    self.parse_scalar_nodes(sequence.values(), field.span, "service network names must be scalars");
                Some(ServiceNetworks::Short { span, names })
            }
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let networks = self.parse_service_network_map(mapping);
                Some(ServiceNetworks::Long { span, networks })
            }
            _ => {
                self.expected(
                    EXPECTED_FIELD_FORM,
                    field,
                    "service networks must be a sequence or mapping",
                );
                None
            }
        }
    }

    fn parse_service_network_map(&mut self, mapping: &Mapping) -> Vec<ServiceNetwork> {
        let mut networks = Vec::new();
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            if self.record_duplicate(&mut seen, &field) {
                continue;
            }
            if Self::field_is_null(&field) {
                networks.push(ServiceNetwork::new(field.name, field.span));
                continue;
            }
            let Some(options) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
                self.expected(
                    EXPECTED_MAPPING,
                    &field,
                    "service network options must be a mapping or null",
                );
                continue;
            };
            networks.push(self.parse_service_network(&field, options));
        }
        networks
    }

    fn parse_service_network(&mut self, field: &ParsedField, mapping: &Mapping) -> ServiceNetwork {
        let mut network = ServiceNetwork::new(field.name.clone(), field.span);
        let mut seen = BTreeMap::new();
        for option in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &option);
            match option.name.value.as_str() {
                "aliases" if !duplicate => network.set_aliases(self.parse_string_sequence(&option, "network aliases")),
                "interface_name" if !duplicate => self
                    .parse_string(&option, "network interface name")
                    .into_iter()
                    .for_each(|value| network.set_interface_name(value)),
                "ipv4_address" if !duplicate => self
                    .parse_string(&option, "network IPv4 address")
                    .into_iter()
                    .for_each(|value| network.set_ipv4_address(value)),
                "ipv6_address" if !duplicate => self
                    .parse_string(&option, "network IPv6 address")
                    .into_iter()
                    .for_each(|value| network.set_ipv6_address(value)),
                "link_local_ips" if !duplicate => {
                    network.set_link_local_ips(self.parse_string_sequence(&option, "link-local IP addresses"));
                }
                "mac_address" if !duplicate => self
                    .parse_string(&option, "network MAC address")
                    .into_iter()
                    .for_each(|value| network.set_mac_address(value)),
                "driver_opts" if !duplicate => {
                    network.set_driver_opts(self.parse_scalar_mapping(&option, "network driver options"));
                }
                "gw_priority" if !duplicate => self
                    .parse_string(&option, "network gateway priority")
                    .into_iter()
                    .for_each(|value| network.set_gw_priority(value)),
                "priority" if !duplicate => self
                    .parse_string(&option, "network priority")
                    .into_iter()
                    .for_each(|value| network.set_priority(value)),
                name if name.starts_with("x-") => network.push_extension(option.reference()),
                _ if duplicate => {}
                _ => network.push_unknown(option.reference()),
            }
        }
        network
    }

    fn parse_config_grants(&mut self, field: &ParsedField) -> Vec<ConfigGrant> {
        self.parse_grants(field)
            .into_iter()
            .map(|grant| match grant {
                ParsedGrant::Short(value) => ConfigGrant::Short(value),
                ParsedGrant::Long(value) => ConfigGrant::Long(value),
            })
            .collect()
    }

    fn parse_secret_grants(&mut self, field: &ParsedField) -> Vec<SecretGrant> {
        self.parse_grants(field)
            .into_iter()
            .map(|grant| match grant {
                ParsedGrant::Short(value) => SecretGrant::Short(value),
                ParsedGrant::Long(value) => SecretGrant::Long(value),
            })
            .collect()
    }

    fn parse_grants(&mut self, field: &ParsedField) -> Vec<ParsedGrant> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(EXPECTED_SEQUENCE, field, "service grants must be a sequence");
            return Vec::new();
        };
        let mut grants = Vec::new();
        for value in sequence.values() {
            match value {
                YamlNode::Scalar(scalar) => {
                    let span = span_from_position(self.source_id, scalar.byte_range());
                    grants.push(ParsedGrant::Short(Located::new(
                        scalar_string_from_source(&self.source, &scalar),
                        span,
                    )));
                }
                YamlNode::Mapping(mapping) => {
                    grants.push(ParsedGrant::Long(Box::new(self.parse_long_grant(&mapping))));
                }
                other => self.unsupported_sequence_item(
                    GRANT_EXPECTED_FORM,
                    &other,
                    field.span,
                    "grant must use scalar short syntax or mapping long syntax",
                ),
            }
        }
        grants
    }

    fn parse_long_grant(&mut self, mapping: &Mapping) -> LongGrant {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut grant = LongGrant::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "source" if !duplicate => self
                    .parse_string(&field, "grant source")
                    .into_iter()
                    .for_each(|value| grant.set_source(value)),
                "target" if !duplicate => self
                    .parse_string(&field, "grant target")
                    .into_iter()
                    .for_each(|value| grant.set_target(value)),
                "uid" if !duplicate => self
                    .parse_string(&field, "grant user ID")
                    .into_iter()
                    .for_each(|value| grant.set_uid(value)),
                "gid" if !duplicate => self
                    .parse_string(&field, "grant group ID")
                    .into_iter()
                    .for_each(|value| grant.set_gid(value)),
                "mode" if !duplicate => self
                    .parse_string(&field, "grant mode")
                    .into_iter()
                    .for_each(|value| grant.set_mode(value)),
                name if name.starts_with("x-") => grant.push_extension(field.reference()),
                _ if duplicate => {}
                _ => grant.push_unknown(field.reference()),
            }
        }
        if grant.source().is_none() {
            self.missing(GRANT_MISSING_SOURCE, span, "long grant is missing `source`");
        }
        grant
    }

    fn parse_service_volumes(&mut self, field: &ParsedField) -> Vec<VolumeMount> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(EXPECTED_SEQUENCE, field, "service volumes must be a sequence");
            return Vec::new();
        };

        sequence
            .values()
            .filter_map(|value| match value {
                YamlNode::Scalar(scalar) => {
                    let span = span_from_position(self.source_id, scalar.byte_range());
                    let raw = Located::new(scalar_string_from_source(&self.source, &scalar), span);
                    Some(VolumeMount::Short(ShortVolumeMount::new(raw)))
                }
                YamlNode::Mapping(mapping) => Some(VolumeMount::Long(Box::new(self.parse_long_volume(&mapping)))),
                other => {
                    let span = node_span(self.source_id, &other).unwrap_or(field.span);
                    self.diagnostics.push(
                        Diagnostic::new(
                            VOLUME_EXPECTED_FORM,
                            Severity::Error,
                            "service volume must use scalar short syntax or mapping long syntax",
                        )
                        .with_label(DiagnosticLabel::primary(span, "unsupported volume form")),
                    );
                    None
                }
            })
            .collect()
    }

    fn parse_long_volume(&mut self, mapping: &Mapping) -> LongVolumeMount {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut mount = LongVolumeMount::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "type" if !duplicate => {
                    if let Some(value) = self.parse_string(&field, "volume type") {
                        mount.set_mount_type(Located::new(MountType::from_text(value.value), value.span));
                    }
                }
                "source" if !duplicate => {
                    if let Some(value) = self.parse_string(&field, "volume source") {
                        mount.set_source(value);
                    }
                }
                "target" if !duplicate => {
                    if let Some(value) = self.parse_string(&field, "volume target") {
                        mount.set_target(value);
                    }
                }
                "read_only" if !duplicate => {
                    if let Some(value) = self.parse_boolean(&field, "read_only") {
                        mount.set_read_only(value);
                    }
                }
                "bind" if !duplicate => {
                    if let Some(value) = self.parse_bind_options(&field) {
                        mount.set_bind(value);
                    }
                }
                name if name.starts_with("x-") => mount.push_extension(field.reference()),
                _ if duplicate => {}
                _ => mount.push_unknown(field.reference()),
            }
        }

        if mount.mount_type().is_none() {
            self.missing(VOLUME_MISSING_TYPE, span, "long volume is missing `type`");
        }
        if mount.target().is_none() {
            self.missing(VOLUME_MISSING_TARGET, span, "long volume is missing `target`");
        }
        mount
    }

    fn parse_bind_options(&mut self, field: &ParsedField) -> Option<BindOptions> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, "bind options must be a mapping");
            return None;
        };
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut bind = BindOptions::new(span);
        let mut seen = BTreeMap::new();
        for bind_field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &bind_field);
            match bind_field.name.value.as_str() {
                "propagation" if !duplicate => {
                    if let Some(value) = self.parse_string(&bind_field, "bind propagation") {
                        bind.set_propagation(value);
                    }
                }
                "create_host_path" if !duplicate => {
                    if let Some(value) = self.parse_boolean(&bind_field, "create_host_path") {
                        bind.set_create_host_path(value);
                    }
                }
                "selinux" if !duplicate => {
                    if let Some(value) = self.parse_string(&bind_field, "SELinux relabel mode") {
                        let mode = match value.value.as_str() {
                            "z" => Some(SelinuxRelabel::Shared),
                            "Z" => Some(SelinuxRelabel::Private),
                            _ => None,
                        };
                        if let Some(mode) = mode {
                            bind.set_selinux(Located::new(mode, value.span));
                        } else {
                            self.diagnostics.push(
                                Diagnostic::new(
                                    VOLUME_INVALID_SELINUX,
                                    Severity::Error,
                                    "SELinux relabel mode must be `z` or `Z`",
                                )
                                .with_label(DiagnosticLabel::primary(value.span, "invalid SELinux mode")),
                            );
                        }
                    }
                }
                name if name.starts_with("x-") => bind.push_extension(bind_field.reference()),
                _ if duplicate => {}
                _ => bind.push_unknown(bind_field.reference()),
            }
        }
        Some(bind)
    }

    fn parse_network_definitions(&mut self, field: &ParsedField) -> Vec<NetworkDefinition> {
        let Some(mapping) = self.resource_collection(field, "networks") else {
            return Vec::new();
        };
        let mut definitions = Vec::new();
        let mut seen = BTreeMap::new();
        for resource in self.fields(&mapping) {
            if self.record_duplicate(&mut seen, &resource) {
                continue;
            }
            if Self::field_is_null(&resource) {
                definitions.push(NetworkDefinition::new(resource.name, resource.span));
                continue;
            }
            let Some(definition) = resource.value.as_ref().and_then(YamlNode::as_mapping) else {
                self.expected(
                    RESOURCE_EXPECTED_FORM,
                    &resource,
                    "network definition must be a mapping or null",
                );
                continue;
            };
            definitions.push(self.parse_network_definition(&resource, definition));
        }
        definitions
    }

    fn parse_network_definition(&mut self, field: &ParsedField, mapping: &Mapping) -> NetworkDefinition {
        let mut network = NetworkDefinition::new(field.name.clone(), field.span);
        let mut seen = BTreeMap::new();
        for option in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &option);
            match option.name.value.as_str() {
                "driver" if !duplicate => self
                    .parse_string(&option, "network driver")
                    .into_iter()
                    .for_each(|value| network.set_driver(value)),
                "driver_opts" if !duplicate => {
                    network.set_driver_opts(self.parse_scalar_mapping(&option, "network driver options"));
                }
                "attachable" if !duplicate => self
                    .parse_boolean(&option, "network attachable")
                    .into_iter()
                    .for_each(|value| network.set_attachable(value)),
                "enable_ipv4" if !duplicate => self
                    .parse_boolean(&option, "network enable_ipv4")
                    .into_iter()
                    .for_each(|value| network.set_enable_ipv4(value)),
                "enable_ipv6" if !duplicate => self
                    .parse_boolean(&option, "network enable_ipv6")
                    .into_iter()
                    .for_each(|value| network.set_enable_ipv6(value)),
                "external" if !duplicate => self
                    .parse_boolean(&option, "network external")
                    .into_iter()
                    .for_each(|value| network.set_external(value)),
                "internal" if !duplicate => self
                    .parse_boolean(&option, "network internal")
                    .into_iter()
                    .for_each(|value| network.set_internal(value)),
                "ipam" if !duplicate => self
                    .parse_ipam(&option)
                    .into_iter()
                    .for_each(|value| network.set_ipam(value)),
                "labels" if !duplicate => self
                    .parse_labels(&option)
                    .into_iter()
                    .for_each(|value| network.set_labels(value)),
                "name" if !duplicate => self
                    .parse_string(&option, "network custom name")
                    .into_iter()
                    .for_each(|value| network.set_custom_name(value)),
                name if name.starts_with("x-") => network.push_extension(option.reference()),
                _ if duplicate => {}
                _ => network.push_unknown(option.reference()),
            }
        }
        network
    }

    fn parse_ipam(&mut self, field: &ParsedField) -> Option<Ipam> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, "network IPAM must be a mapping");
            return None;
        };
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut ipam = Ipam::new(span);
        let mut seen = BTreeMap::new();
        for option in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &option);
            match option.name.value.as_str() {
                "driver" if !duplicate => self
                    .parse_string(&option, "IPAM driver")
                    .into_iter()
                    .for_each(|value| ipam.set_driver(value)),
                "config" if !duplicate => ipam.set_config(self.parse_ipam_configs(&option)),
                "options" if !duplicate => {
                    ipam.set_options(self.parse_scalar_mapping(&option, "IPAM options"));
                }
                name if name.starts_with("x-") => ipam.push_extension(option.reference()),
                _ if duplicate => {}
                _ => ipam.push_unknown(option.reference()),
            }
        }
        Some(ipam)
    }

    fn parse_ipam_configs(&mut self, field: &ParsedField) -> Vec<IpamConfig> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(EXPECTED_SEQUENCE, field, "IPAM config must be a sequence");
            return Vec::new();
        };
        let mut configs = Vec::new();
        for value in sequence.values() {
            let YamlNode::Mapping(mapping) = value else {
                self.unsupported_sequence_item(
                    EXPECTED_MAPPING,
                    &value,
                    field.span,
                    "IPAM config entries must be mappings",
                );
                continue;
            };
            configs.push(self.parse_ipam_config(&mapping));
        }
        configs
    }

    fn parse_ipam_config(&mut self, mapping: &Mapping) -> IpamConfig {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut config = IpamConfig::new(span);
        let mut seen = BTreeMap::new();
        for field in self.fields(mapping) {
            let duplicate = self.record_duplicate(&mut seen, &field);
            match field.name.value.as_str() {
                "subnet" if !duplicate => self
                    .parse_string(&field, "IPAM subnet")
                    .into_iter()
                    .for_each(|value| config.set_subnet(value)),
                "ip_range" if !duplicate => self
                    .parse_string(&field, "IPAM allocation range")
                    .into_iter()
                    .for_each(|value| config.set_ip_range(value)),
                "gateway" if !duplicate => self
                    .parse_string(&field, "IPAM gateway")
                    .into_iter()
                    .for_each(|value| config.set_gateway(value)),
                "aux_addresses" if !duplicate => {
                    config.set_aux_addresses(self.parse_scalar_mapping(&field, "IPAM auxiliary addresses"));
                }
                name if name.starts_with("x-") => config.push_extension(field.reference()),
                _ if duplicate => {}
                _ => config.push_unknown(field.reference()),
            }
        }
        config
    }

    fn parse_volume_definitions(&mut self, field: &ParsedField) -> Vec<VolumeDefinition> {
        let Some(mapping) = self.resource_collection(field, "volumes") else {
            return Vec::new();
        };
        let mut definitions = Vec::new();
        let mut seen = BTreeMap::new();
        for resource in self.fields(&mapping) {
            if self.record_duplicate(&mut seen, &resource) {
                continue;
            }
            let mut volume = VolumeDefinition::new(resource.name.clone(), resource.span);
            if Self::field_is_null(&resource) {
                definitions.push(volume);
                continue;
            }
            let Some(definition) = resource.value.as_ref().and_then(YamlNode::as_mapping) else {
                self.expected(
                    RESOURCE_EXPECTED_FORM,
                    &resource,
                    "volume definition must be a mapping or null",
                );
                continue;
            };
            let mut nested_seen = BTreeMap::new();
            for option in self.fields(definition) {
                let duplicate = self.record_duplicate(&mut nested_seen, &option);
                match option.name.value.as_str() {
                    "driver" if !duplicate => self
                        .parse_string(&option, "volume driver")
                        .into_iter()
                        .for_each(|value| volume.set_driver(value)),
                    "driver_opts" if !duplicate => {
                        volume.set_driver_opts(self.parse_scalar_mapping(&option, "volume driver options"));
                    }
                    "external" if !duplicate => self
                        .parse_boolean(&option, "volume external")
                        .into_iter()
                        .for_each(|value| volume.set_external(value)),
                    "labels" if !duplicate => self
                        .parse_labels(&option)
                        .into_iter()
                        .for_each(|value| volume.set_labels(value)),
                    "name" if !duplicate => self
                        .parse_string(&option, "volume custom name")
                        .into_iter()
                        .for_each(|value| volume.set_custom_name(value)),
                    name if name.starts_with("x-") => volume.push_extension(option.reference()),
                    _ if duplicate => {}
                    _ => volume.push_unknown(option.reference()),
                }
            }
            definitions.push(volume);
        }
        definitions
    }

    fn parse_config_definitions(&mut self, field: &ParsedField) -> Vec<ConfigDefinition> {
        let Some(mapping) = self.resource_collection(field, "configs") else {
            return Vec::new();
        };
        let mut definitions = Vec::new();
        let mut seen = BTreeMap::new();
        for resource in self.fields(&mapping) {
            if self.record_duplicate(&mut seen, &resource) {
                continue;
            }
            let mut config = ConfigDefinition::new(resource.name.clone(), resource.span);
            if Self::field_is_null(&resource) {
                definitions.push(config);
                continue;
            }
            let Some(definition) = resource.value.as_ref().and_then(YamlNode::as_mapping) else {
                self.expected(
                    RESOURCE_EXPECTED_FORM,
                    &resource,
                    "config definition must be a mapping or null",
                );
                continue;
            };
            let mut nested_seen = BTreeMap::new();
            for option in self.fields(definition) {
                let duplicate = self.record_duplicate(&mut nested_seen, &option);
                match option.name.value.as_str() {
                    "file" if !duplicate => self
                        .parse_string(&option, "config file")
                        .into_iter()
                        .for_each(|value| config.set_file(value)),
                    "environment" if !duplicate => self
                        .parse_string(&option, "config environment source")
                        .into_iter()
                        .for_each(|value| config.set_environment(value)),
                    "content" if !duplicate => self
                        .parse_string(&option, "config content")
                        .into_iter()
                        .for_each(|value| config.set_content(value)),
                    "external" if !duplicate => self
                        .parse_boolean(&option, "config external")
                        .into_iter()
                        .for_each(|value| config.set_external(value)),
                    "name" if !duplicate => self
                        .parse_string(&option, "config custom name")
                        .into_iter()
                        .for_each(|value| config.set_custom_name(value)),
                    name if name.starts_with("x-") => config.push_extension(option.reference()),
                    _ if duplicate => {}
                    _ => config.push_unknown(option.reference()),
                }
            }
            definitions.push(config);
        }
        definitions
    }

    fn parse_secret_definitions(&mut self, field: &ParsedField) -> Vec<SecretDefinition> {
        let Some(mapping) = self.resource_collection(field, "secrets") else {
            return Vec::new();
        };
        let mut definitions = Vec::new();
        let mut seen = BTreeMap::new();
        for resource in self.fields(&mapping) {
            if self.record_duplicate(&mut seen, &resource) {
                continue;
            }
            let mut secret = SecretDefinition::new(resource.name.clone(), resource.span);
            if Self::field_is_null(&resource) {
                definitions.push(secret);
                continue;
            }
            let Some(definition) = resource.value.as_ref().and_then(YamlNode::as_mapping) else {
                self.expected(
                    RESOURCE_EXPECTED_FORM,
                    &resource,
                    "secret definition must be a mapping or null",
                );
                continue;
            };
            let mut nested_seen = BTreeMap::new();
            for option in self.fields(definition) {
                let duplicate = self.record_duplicate(&mut nested_seen, &option);
                match option.name.value.as_str() {
                    "file" if !duplicate => self
                        .parse_string(&option, "secret file")
                        .into_iter()
                        .for_each(|value| secret.set_file(value)),
                    "environment" if !duplicate => self
                        .parse_string(&option, "secret environment source")
                        .into_iter()
                        .for_each(|value| secret.set_environment(value)),
                    "external" if !duplicate => self
                        .parse_boolean(&option, "secret external")
                        .into_iter()
                        .for_each(|value| secret.set_external(value)),
                    "name" if !duplicate => self
                        .parse_string(&option, "secret custom name")
                        .into_iter()
                        .for_each(|value| secret.set_custom_name(value)),
                    name if name.starts_with("x-") => secret.push_extension(option.reference()),
                    _ if duplicate => {}
                    _ => secret.push_unknown(option.reference()),
                }
            }
            definitions.push(secret);
        }
        definitions
    }

    fn resource_collection(&mut self, field: &ParsedField, kind: &str) -> Option<Mapping> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, format!("top-level {kind} must be a mapping"));
            return None;
        };
        Some(mapping.clone())
    }

    fn parse_string(&mut self, field: &ParsedField, description: &str) -> Option<Located<String>> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(EXPECTED_SCALAR, field, format!("{description} must be a scalar"));
            return None;
        };
        if ScalarValue::from_scalar(scalar).scalar_type() == ScalarType::Null {
            self.expected(
                EXPECTED_SCALAR,
                field,
                format!("{description} must be a non-null scalar"),
            );
            return None;
        }
        Some(Located::new(
            scalar_string_from_source(&self.source, scalar),
            span_from_position(self.source_id, scalar.byte_range()),
        ))
    }

    fn parse_boolean(&mut self, field: &ParsedField, description: &str) -> Option<Located<BooleanValue>> {
        let Some(scalar) = field.value.as_ref().and_then(YamlNode::as_scalar) else {
            self.expected(EXPECTED_BOOLEAN, field, format!("{description} must be a boolean"));
            return None;
        };
        let span = span_from_position(self.source_id, scalar.byte_range());
        let scalar_value = ScalarValue::from_scalar(scalar);
        if let Some(value) = scalar_value.to_bool() {
            return Some(Located::new(BooleanValue::Literal(value), span));
        }
        let value = scalar_string_from_source(&self.source, scalar);
        if value.contains('$') {
            return Some(Located::new(BooleanValue::Expression(value), span));
        }
        self.diagnostics.push(
            Diagnostic::new(
                EXPECTED_BOOLEAN,
                Severity::Error,
                format!("{description} must be a boolean or interpolation expression"),
            )
            .with_label(DiagnosticLabel::primary(span, "not a boolean expression")),
        );
        None
    }

    fn parse_string_sequence(&mut self, field: &ParsedField, description: &str) -> Vec<Located<String>> {
        let Some(sequence) = field.value.as_ref().and_then(YamlNode::as_sequence) else {
            self.expected(EXPECTED_SEQUENCE, field, format!("{description} must be a sequence"));
            return Vec::new();
        };
        self.parse_scalar_nodes(
            sequence.values(),
            field.span,
            format!("{description} entries must be scalars"),
        )
    }

    fn parse_scalar_nodes(
        &mut self,
        nodes: impl Iterator<Item = YamlNode>,
        fallback_span: SourceSpan,
        message: impl Into<String>,
    ) -> Vec<Located<String>> {
        let message = message.into();
        let mut values = Vec::new();
        for node in nodes {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(EXPECTED_SCALAR, &node, fallback_span, &message);
                continue;
            };
            let scalar_value = ScalarValue::from_scalar(&scalar);
            if scalar_value.scalar_type() == ScalarType::Null {
                self.unsupported_sequence_item(EXPECTED_SCALAR, &YamlNode::Scalar(scalar), fallback_span, &message);
                continue;
            }
            let span = span_from_position(self.source_id, scalar.byte_range());
            values.push(Located::new(scalar_string_from_source(&self.source, &scalar), span));
        }
        values
    }

    fn parse_scalar_mapping(&mut self, field: &ParsedField, description: &str) -> Vec<KeyValueEntry> {
        let Some(mapping) = field.value.as_ref().and_then(YamlNode::as_mapping) else {
            self.expected(EXPECTED_MAPPING, field, format!("{description} must be a mapping"));
            return Vec::new();
        };
        let mut entries = Vec::new();
        let mut seen = BTreeMap::new();
        for entry in self.fields(mapping) {
            if self.record_duplicate(&mut seen, &entry) {
                continue;
            }
            if let Some(value) = self.parse_compose_scalar(&entry, format!("{description} values must be scalars")) {
                entries.push(KeyValueEntry::new(entry.name, value, entry.span));
            }
        }
        entries
    }

    fn parse_compose_scalar(
        &mut self,
        field: &ParsedField,
        message: impl Into<String>,
    ) -> Option<Located<ComposeScalar>> {
        let Some(node) = field.value.as_ref() else {
            return Some(Located::new(ComposeScalar::Null, field.name.span));
        };
        let Some(scalar) = node.as_scalar() else {
            self.expected(EXPECTED_SCALAR, field, message);
            return None;
        };
        let span = span_from_position(self.source_id, scalar.byte_range());
        let value = ScalarValue::from_scalar(scalar);
        let typed = match value.scalar_type() {
            ScalarType::Null => ComposeScalar::Null,
            ScalarType::Boolean => ComposeScalar::Boolean(value.to_bool().unwrap_or(false)),
            ScalarType::Integer | ScalarType::Float => {
                ComposeScalar::Number(scalar_string_from_source(&self.source, scalar))
            }
            ScalarType::String | ScalarType::Timestamp | ScalarType::Regex => {
                ComposeScalar::String(scalar_string_from_source(&self.source, scalar))
            }
        };
        Some(Located::new(typed, span))
    }

    fn parse_labels(&mut self, field: &ParsedField) -> Option<Labels> {
        match field.value.as_ref() {
            Some(YamlNode::Sequence(sequence)) => {
                let span = span_from_position(self.source_id, sequence.byte_range());
                let values =
                    self.parse_scalar_nodes(sequence.values(), field.span, "label list entries must be scalars");
                Some(Labels::List { span, values })
            }
            Some(YamlNode::Mapping(mapping)) => {
                let span = span_from_position(self.source_id, mapping.byte_range());
                let entries = self.parse_scalar_mapping(field, "labels");
                Some(Labels::Map { span, entries })
            }
            _ => {
                self.expected(EXPECTED_FIELD_FORM, field, "labels must be a sequence or mapping");
                None
            }
        }
    }

    fn parse_annotations(&mut self, field: &ParsedField) -> Option<Annotations> {
        match field.value.as_ref() {
            Some(YamlNode::Sequence(sequence)) => Some(self.parse_annotation_list(sequence, field.span)),
            Some(YamlNode::Mapping(mapping)) => Some(self.parse_annotation_map(mapping)),
            _ => {
                self.expected(
                    ANNOTATIONS_EXPECTED_FORM,
                    field,
                    "annotations must be a sequence or mapping",
                );
                None
            }
        }
    }

    fn parse_annotation_list(&mut self, sequence: &yaml_edit::Sequence, fallback: SourceSpan) -> Annotations {
        let span = span_from_position(self.source_id, sequence.byte_range());
        let mut values = Vec::new();
        let mut seen = BTreeSet::new();
        for node in sequence.values() {
            let YamlNode::Scalar(scalar) = node else {
                self.unsupported_sequence_item(
                    ANNOTATIONS_EXPECTED_STRING,
                    &node,
                    fallback,
                    "annotation list entries must be string scalars",
                );
                continue;
            };
            let item_span = span_from_position(self.source_id, scalar.byte_range());
            let scalar_value = ScalarValue::from_scalar(&scalar);
            let value = match scalar_value.scalar_type() {
                ScalarType::Null => ComposeScalar::Null,
                ScalarType::Boolean => ComposeScalar::Boolean(scalar_value.to_bool().unwrap_or(false)),
                ScalarType::Integer | ScalarType::Float => {
                    ComposeScalar::Number(scalar_string_from_source(&self.source, &scalar))
                }
                ScalarType::String | ScalarType::Timestamp | ScalarType::Regex => {
                    ComposeScalar::String(scalar_string_from_source(&self.source, &scalar))
                }
            };
            self.validate_annotation_list_scalar(&value, item_span, &mut seen);
            values.push(Located::new(value, item_span));
        }
        Annotations::new(span, AnnotationsForm::List(values))
    }

    fn validate_annotation_list_scalar(
        &mut self,
        value: &ComposeScalar,
        span: SourceSpan,
        seen: &mut BTreeSet<String>,
    ) {
        let ComposeScalar::String(raw) = value else {
            self.diagnostics.push(annotation_diagnostic(
                ANNOTATIONS_EXPECTED_STRING,
                Severity::Error,
                span,
                "annotation list entries must be string scalars",
                "non-string annotation item retained",
            ));
            return;
        };
        let name = raw.split_once('=').map_or(raw.as_str(), |(name, _)| name);
        if name.is_empty() {
            self.diagnostics.push(annotation_diagnostic(
                ANNOTATIONS_EMPTY_NAME,
                Severity::Error,
                span,
                "service annotation name must not be empty",
                "empty annotation name",
            ));
        } else if !seen.insert(name.to_owned()) {
            self.diagnostics.push(annotation_diagnostic(
                ANNOTATIONS_DUPLICATE_NAME,
                Severity::Error,
                span,
                "service annotation names must be unique",
                "duplicate annotation name",
            ));
        }
        if !raw.contains('=') {
            self.diagnostics.push(annotation_diagnostic(
                ANNOTATIONS_KEY_ONLY,
                Severity::Warning,
                span,
                "key-only service annotation has no explicit value",
                "ambiguous key-only annotation",
            ));
        }
    }

    fn parse_annotation_map(&mut self, mapping: &Mapping) -> Annotations {
        let span = span_from_position(self.source_id, mapping.byte_range());
        let mut entries = Vec::new();
        let mut seen = BTreeMap::new();
        for entry in self.fields(mapping) {
            let _duplicate = self.record_duplicate(&mut seen, &entry);
            if entry.name.value.is_empty() {
                self.diagnostics.push(annotation_diagnostic(
                    ANNOTATIONS_EMPTY_NAME,
                    Severity::Error,
                    entry.name.span,
                    "service annotation name must not be empty",
                    "empty annotation name",
                ));
            }
            if let Some(value) = self.parse_compose_scalar(
                &entry,
                "annotation mapping values must be scalar strings, numbers, booleans, or null",
            ) {
                entries.push(KeyValueEntry::new(entry.name, value, entry.span));
            }
        }
        Annotations::new(span, AnnotationsForm::Map(entries))
    }

    fn field_is_null(field: &ParsedField) -> bool {
        field.value.as_ref().is_none_or(|node| {
            node.as_scalar()
                .is_some_and(|scalar| ScalarValue::from_scalar(scalar).scalar_type() == ScalarType::Null)
        })
    }

    fn unsupported_sequence_item(
        &mut self,
        code: DiagnosticCode,
        node: &YamlNode,
        fallback_span: SourceSpan,
        message: impl Into<String>,
    ) {
        let span = node_span(self.source_id, node).unwrap_or(fallback_span);
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Error, message)
                .with_label(DiagnosticLabel::primary(span, "unsupported value form")),
        );
    }

    fn fields(&mut self, mapping: &Mapping) -> Vec<ParsedField> {
        let fields = self.raw_fields(mapping);
        let mut fields = self.flatten_empty_value_continuations(fields);
        for field in &mut fields {
            field.value = field.value.take().map(|value| self.resolve_alias(value));
        }
        fields
    }

    fn raw_fields(&mut self, mapping: &Mapping) -> Vec<ParsedField> {
        mapping
            .entries()
            .filter_map(|entry| {
                let key = entry.key_node()?;
                let Some(scalar) = key.as_scalar() else {
                    let span = node_span(self.source_id, &key)
                        .unwrap_or_else(|| span_from_position(self.source_id, mapping.byte_range()));
                    self.diagnostics.push(
                        Diagnostic::new(EXPECTED_SCALAR, Severity::Error, "Compose mapping keys must be scalars")
                            .with_label(DiagnosticLabel::primary(span, "non-scalar key")),
                    );
                    return None;
                };
                let name_span = span_from_position(self.source_id, scalar.byte_range());
                let authored_value = entry.value_node();
                let value_span = authored_value
                    .as_ref()
                    .and_then(|value| node_span(self.source_id, value));
                let value = authored_value.map(unwrap_processing_tag);
                let span = value_span.map_or(name_span, |value_span| union(name_span, value_span));
                Some(ParsedField {
                    name: Located::new(scalar_string_from_source(&self.source, scalar), name_span),
                    value,
                    value_span,
                    span,
                })
            })
            .collect()
    }

    fn resolve_alias(&self, node: YamlNode) -> YamlNode {
        let mut node = node;
        let mut visited = BTreeSet::new();
        for _ in 0..64 {
            let YamlNode::Alias(alias) = &node else {
                return node;
            };
            if !visited.insert(alias.name()) {
                return node;
            }
            let Some(target) = self.anchors.resolve(&alias.name()).and_then(|target| {
                YamlNode::from_syntax(target.clone()).or_else(|| target.children().find_map(YamlNode::from_syntax))
            }) else {
                return node;
            };
            node = target;
        }
        node
    }

    fn flatten_empty_value_continuations(&mut self, fields: Vec<ParsedField>) -> Vec<ParsedField> {
        let Some(target_column) = fields.first().map(|field| self.source_column(field.name.span.start())) else {
            return fields;
        };
        self.recover_fields(fields, target_column)
    }

    fn recover_fields(&mut self, fields: Vec<ParsedField>, target_column: usize) -> Vec<ParsedField> {
        let mut flattened = Vec::new();
        for mut field in fields {
            let field_column = self.source_column(field.name.span.start());
            let nested_mapping = field.value.as_ref().and_then(YamlNode::as_mapping).cloned();
            let continuation = nested_mapping.as_ref().is_some_and(|mapping| {
                !self.is_flow_mapping(mapping)
                    && mapping
                        .entries()
                        .find_map(|entry| {
                            let key = entry.key_node()?;
                            let scalar = key.as_scalar()?;
                            Some(scalar.byte_range().start as usize)
                        })
                        .is_some_and(|key_start| self.source_column(key_start) <= field_column)
            });

            if continuation {
                field.value = None;
                field.value_span = None;
                field.span = field.name.span;
            }
            if field_column == target_column {
                flattened.push(field);
            }
            if let Some(mapping) = nested_mapping.filter(|mapping| !self.is_flow_mapping(mapping)) {
                let nested = self.raw_fields(&mapping);
                flattened.extend(self.recover_fields(nested, target_column));
            }
        }
        flattened
    }

    fn is_flow_mapping(&self, mapping: &Mapping) -> bool {
        let position = mapping.byte_range();
        self.source
            .get(position.start as usize..position.end as usize)
            .is_some_and(|text| text.trim_start().starts_with('{'))
    }

    fn record_duplicate(&mut self, seen: &mut BTreeMap<String, SourceSpan>, field: &ParsedField) -> bool {
        if let Some(first) = seen.get(field.name.value()) {
            self.diagnostics.push(
                Diagnostic::new(
                    DUPLICATE_FIELD,
                    Severity::Error,
                    "Compose mapping fields must be unique",
                )
                .with_label(DiagnosticLabel::primary(field.name.span, "duplicate field"))
                .with_label(DiagnosticLabel::secondary(*first, "first field")),
            );
            true
        } else {
            seen.insert(field.name.value.clone(), field.name.span);
            false
        }
    }

    fn expected(&mut self, code: DiagnosticCode, field: &ParsedField, message: impl Into<String>) {
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Error, message)
                .with_label(DiagnosticLabel::primary(field.span, "unexpected value form")),
        );
    }

    fn missing(&mut self, code: DiagnosticCode, span: SourceSpan, message: &'static str) {
        self.diagnostics.push(
            Diagnostic::new(code, Severity::Error, message)
                .with_label(DiagnosticLabel::primary(span, "incomplete long syntax")),
        );
    }
}

fn unwrap_processing_tag(node: YamlNode) -> YamlNode {
    let YamlNode::TaggedNode(tagged) = &node else {
        return node;
    };
    if !matches!(tagged.tag().as_deref(), Some("!reset" | "!override")) {
        return node;
    }
    tagged
        .as_node()
        .and_then(|syntax| syntax.children().find_map(YamlNode::from_syntax))
        .unwrap_or(node)
}

#[derive(Debug, Clone)]
enum ParsedGrant {
    Short(Located<String>),
    Long(Box<LongGrant>),
}

#[derive(Debug, Clone)]
struct ParsedField {
    name: Located<String>,
    value: Option<YamlNode>,
    value_span: Option<SourceSpan>,
    span: SourceSpan,
}

impl ParsedField {
    fn reference(&self) -> FieldReference {
        FieldReference {
            name: self.name.clone(),
            span: self.span,
            value_span: self.value_span,
        }
    }
}

fn node_span(source_id: SourceId, node: &YamlNode) -> Option<SourceSpan> {
    let position = match node {
        YamlNode::Scalar(value) => value.byte_range(),
        YamlNode::Mapping(value) => value.byte_range(),
        YamlNode::Sequence(value) => value.byte_range(),
        YamlNode::Alias(_) | YamlNode::TaggedNode(_) => {
            let range = node.as_node()?.text_range();
            return Some(SourceSpan::from_valid_offsets(
                source_id,
                u32::from(range.start()) as usize,
                u32::from(range.end()) as usize,
            ));
        }
    };
    Some(span_from_position(source_id, position))
}

fn span_from_position(source_id: SourceId, position: yaml_edit::TextPosition) -> SourceSpan {
    SourceSpan::from_valid_offsets(source_id, position.start as usize, position.end as usize)
}

fn union(left: SourceSpan, right: SourceSpan) -> SourceSpan {
    SourceSpan::from_valid_offsets(
        left.source_id(),
        left.start().min(right.start()),
        left.end().max(right.end()),
    )
}