azul-css 0.0.10

Common datatypes used for styling applications using the Azul desktop GUI framework
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
//! High-level types and functions related to CSS parsing.
//!
//! Main entry point: [`new_from_str`] parses a CSS string into a [`Css`] value
//! plus a list of recoverable warnings. Errors are downgraded to warnings so
//! that partially-valid CSS still produces usable output.
//!
//! Supports `@media`, `@theme`, `@os`, `@lang`, and `@container`
//! at-rules, CSS nesting, CSS variables (`var(--name, default)`), and
//! comma-separated selector lists. Tokenisation is delegated to `azul_simplecss`.
//!
//! Most error types come in borrowed/owned pairs (e.g. `CssParseError<'a>` /
//! `CssParseErrorOwned`) so they can be returned across the FFI boundary.
use alloc::{collections::BTreeMap, string::ToString, vec::Vec};
use core::{fmt, num::ParseIntError};

pub use azul_simplecss::Error as SimplecssError;
use azul_simplecss::Tokenizer;

/// FFI-safe position of a CSS syntax error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct CssSyntaxErrorPos {
    pub row: usize,
    pub col: usize,
}

impl From<azul_simplecss::ErrorPos> for CssSyntaxErrorPos {
    fn from(p: azul_simplecss::ErrorPos) -> Self {
        Self { row: p.row, col: p.col }
    }
}

/// FFI-safe wrapper for invalid advance details in CSS syntax errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct CssSyntaxInvalidAdvance {
    pub expected: isize,
    pub total: usize,
    pub pos: CssSyntaxErrorPos,
}

/// FFI-safe CSS syntax error type, mirrors `azul_simplecss::Error`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C, u8)]
pub enum CssSyntaxError {
    UnexpectedEndOfStream(CssSyntaxErrorPos),
    InvalidAdvance(CssSyntaxInvalidAdvance),
    UnsupportedToken(CssSyntaxErrorPos),
    UnknownToken(CssSyntaxErrorPos),
}

impl From<SimplecssError> for CssSyntaxError {
    fn from(e: SimplecssError) -> Self {
        match e {
            SimplecssError::UnexpectedEndOfStream(pos) => Self::UnexpectedEndOfStream(pos.into()),
            SimplecssError::InvalidAdvance { expected, total, pos } => Self::InvalidAdvance(CssSyntaxInvalidAdvance { expected, total, pos: pos.into() }),
            SimplecssError::UnsupportedToken(pos) => Self::UnsupportedToken(pos.into()),
            SimplecssError::UnknownToken(pos) => Self::UnknownToken(pos.into()),
        }
    }
}

pub use crate::props::property::CssParsingError;
use crate::{
    corety::{AzString, OptionString},
    css::{
        AttributeMatchOp, Css, CssAttributeSelector, CssDeclaration, CssNthChildSelector, CssPath,
        CssPathPseudoSelector, CssPathSelector, CssRuleBlock, DynamicCssProperty, NodeTypeTag,
        NodeTypeTagParseError, NodeTypeTagParseErrorOwned,
    },
    dynamic_selector::{
        BoolCondition, DynamicSelector, DynamicSelectorVec, LanguageCondition, MediaType,
        MinMaxRange, OrientationType, OsCondition, ThemeCondition, parse_os_version,
    },
    props::{
        basic::parse::parse_parentheses,
        property::{
            parse_combined_css_property, parse_css_property, CombinedCssPropertyType, CssKeyMap,
            CssParsingErrorOwned, CssPropertyType,
        },
    },
};

/// Error that can happen during the parsing of a CSS value
#[derive(Debug, Clone, PartialEq)]
pub struct CssParseError<'a> {
    pub css_string: &'a str,
    pub error: CssParseErrorInner<'a>,
    pub location: ErrorLocationRange,
}

/// Owned version of `CssParseError`, without references.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct CssParseErrorOwned {
    pub css_string: AzString,
    pub error: CssParseErrorInnerOwned,
    pub location: ErrorLocationRange,
}

impl CssParseError<'_> {
    #[must_use] pub fn to_contained(&self) -> CssParseErrorOwned {
        CssParseErrorOwned {
            css_string: self.css_string.to_string().into(),
            error: self.error.to_contained(),
            location: self.location,
        }
    }
}

impl CssParseErrorOwned {
    #[must_use] pub fn to_shared(&self) -> CssParseError<'_> {
        CssParseError {
            css_string: self.css_string.as_str(),
            error: self.error.to_shared(),
            location: self.location,
        }
    }
}

/// Clamps a byte offset into `s` so it is in-bounds AND on a UTF-8 char boundary,
/// rounding DOWN to the nearest boundary.
///
/// Error locations are recorded as raw byte offsets and are reachable from public,
/// unvalidated fields, so they cannot be fed to a slice directly: an out-of-range or
/// mid-character offset panics. Every error-reporting path routes through here.
#[must_use]
fn clamp_to_char_boundary(s: &str, pos: usize) -> usize {
    let mut pos = pos.min(s.len());
    while pos > 0 && !s.is_char_boundary(pos) {
        pos -= 1;
    }
    pos
}

impl<'a> CssParseError<'a> {
    /// Returns the string between the (start, end) location
    #[must_use] pub fn get_error_string(&self) -> &'a str {
        let (start, end) = (self.location.start.original_pos, self.location.end.original_pos);
        // `location` is a pub field on a pub struct and `CssParseErrorOwned::to_shared`
        // rebuilds one without revalidating, so start/end are NOT trustworthy: they can
        // sit past the end, be reversed, or land inside a multi-byte char. A raw slice
        // panics on all three -- while merely *displaying* an error. Clamp instead.
        let start = clamp_to_char_boundary(self.css_string, start);
        let end = clamp_to_char_boundary(self.css_string, end);
        let (start, end) = (start.min(end), start.max(end));
        self.css_string[start..end].trim()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum CssParseErrorInner<'a> {
    /// A hard error in the CSS syntax
    ParseError(CssSyntaxError),
    /// Braces are not balanced properly
    UnclosedBlock,
    /// Invalid syntax, such as `#div { #div: "my-value" }`
    MalformedCss,
    /// Error parsing dynamic CSS property, such as
    /// `#div { width: {{ my_id }} /* no default case */ }`
    DynamicCssParseError(DynamicCssParseError<'a>),
    /// Error while parsing a pseudo selector (like `:aldkfja`)
    PseudoSelectorParseError(CssPseudoSelectorParseError<'a>),
    /// The path has to be either `*`, `div`, `p` or something like that
    NodeTypeTag(NodeTypeTagParseError<'a>),
    /// A certain property has an unknown key, for example: `alsdfkj: 500px` = `unknown CSS key
    /// "alsdfkj: 500px"`
    UnknownPropertyKey(&'a str, &'a str),
    /// `var()` can't be used on properties that expand to multiple values, since they would be
    /// ambiguous and degrade performance - for example `margin: var(--blah)` would be ambiguous
    /// because it's not clear when setting the variable, whether all sides should be set,
    /// instead, you have to use `margin-top: var(--blah)`, `margin-bottom: var(--baz)` in order
    /// to work around this limitation.
    VarOnShorthandProperty {
        key: CombinedCssPropertyType,
        value: &'a str,
    },
}

/// Wrapper for `UnknownPropertyKey` error.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct UnknownPropertyKeyError {
    pub key: AzString,
    pub value: AzString,
}

/// Wrapper for `VarOnShorthandProperty` error.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct VarOnShorthandPropertyError {
    pub key: CombinedCssPropertyType,
    pub value: AzString,
}

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum CssParseErrorInnerOwned {
    ParseError(CssSyntaxError),
    UnclosedBlock,
    MalformedCss,
    DynamicCssParseError(DynamicCssParseErrorOwned),
    PseudoSelectorParseError(CssPseudoSelectorParseErrorOwned),
    NodeTypeTag(NodeTypeTagParseErrorOwned),
    UnknownPropertyKey(UnknownPropertyKeyError),
    VarOnShorthandProperty(VarOnShorthandPropertyError),
}

impl CssParseErrorInner<'_> {
    #[must_use] pub fn to_contained(&self) -> CssParseErrorInnerOwned {
        match self {
            CssParseErrorInner::ParseError(e) => CssParseErrorInnerOwned::ParseError(*e),
            CssParseErrorInner::UnclosedBlock => CssParseErrorInnerOwned::UnclosedBlock,
            CssParseErrorInner::MalformedCss => CssParseErrorInnerOwned::MalformedCss,
            CssParseErrorInner::DynamicCssParseError(e) => {
                CssParseErrorInnerOwned::DynamicCssParseError(e.to_contained())
            }
            CssParseErrorInner::PseudoSelectorParseError(e) => {
                CssParseErrorInnerOwned::PseudoSelectorParseError(e.to_contained())
            }
            CssParseErrorInner::NodeTypeTag(e) => {
                CssParseErrorInnerOwned::NodeTypeTag(e.to_contained())
            }
            CssParseErrorInner::UnknownPropertyKey(a, b) => {
                CssParseErrorInnerOwned::UnknownPropertyKey(UnknownPropertyKeyError { key: (*a).to_string().into(), value: (*b).to_string().into() })
            }
            CssParseErrorInner::VarOnShorthandProperty { key, value } => {
                CssParseErrorInnerOwned::VarOnShorthandProperty(VarOnShorthandPropertyError {
                    key: *key,
                    value: (*value).to_string().into(),
                })
            }
        }
    }
}

impl CssParseErrorInnerOwned {
    #[must_use] pub fn to_shared(&self) -> CssParseErrorInner<'_> {
        match self {
            Self::ParseError(e) => CssParseErrorInner::ParseError(*e),
            Self::UnclosedBlock => CssParseErrorInner::UnclosedBlock,
            Self::MalformedCss => CssParseErrorInner::MalformedCss,
            Self::DynamicCssParseError(e) => {
                CssParseErrorInner::DynamicCssParseError(e.to_shared())
            }
            Self::PseudoSelectorParseError(e) => {
                CssParseErrorInner::PseudoSelectorParseError(e.to_shared())
            }
            Self::NodeTypeTag(e) => {
                CssParseErrorInner::NodeTypeTag(e.to_shared())
            }
            Self::UnknownPropertyKey(e) => {
                CssParseErrorInner::UnknownPropertyKey(e.key.as_str(), e.value.as_str())
            }
            Self::VarOnShorthandProperty(e) => {
                CssParseErrorInner::VarOnShorthandProperty {
                    key: e.key,
                    value: e.value.as_str(),
                }
            }
        }
    }
}

impl_display! { CssParseErrorInner<'a>, {
    ParseError(e) => format!("Parse Error: {:?}", e),
    UnclosedBlock => "Unclosed block",
    MalformedCss => "Malformed Css",
    DynamicCssParseError(e) => format!("{}", e),
    PseudoSelectorParseError(e) => format!("Failed to parse pseudo-selector: {}", e),
    NodeTypeTag(e) => format!("Failed to parse CSS selector path: {}", e),
    UnknownPropertyKey(k, v) => format!("Unknown CSS key: \"{}: {}\"", k, v),
    VarOnShorthandProperty { key, value } => format!(
        "Error while parsing: \"{}: {};\": var() cannot be used on shorthand properties - use `{}-top` or `{}-x` as the key instead: ",
        key, value, key, key
    ),
}}

impl From<CssSyntaxError> for CssParseErrorInner<'_> {
    fn from(e: CssSyntaxError) -> Self {
        CssParseErrorInner::ParseError(e)
    }
}

impl From<SimplecssError> for CssParseErrorInner<'_> {
    fn from(e: SimplecssError) -> Self {
        CssParseErrorInner::ParseError(CssSyntaxError::from(e))
    }
}

impl_from! { DynamicCssParseError<'a>, CssParseErrorInner::DynamicCssParseError }
impl_from! { NodeTypeTagParseError<'a>, CssParseErrorInner::NodeTypeTag }
impl_from! { CssPseudoSelectorParseError<'a>, CssParseErrorInner::PseudoSelectorParseError }

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CssPseudoSelectorParseError<'a> {
    EmptyNthChild,
    UnknownSelector(&'a str, Option<&'a str>),
    InvalidNthChildPattern(&'a str),
    InvalidNthChild(ParseIntError),
}

impl From<ParseIntError> for CssPseudoSelectorParseError<'_> {
    fn from(e: ParseIntError) -> Self {
        CssPseudoSelectorParseError::InvalidNthChild(e)
    }
}

impl_display! { CssPseudoSelectorParseError<'a>, {
    EmptyNthChild => format!("\
        Empty :nth-child() selector - nth-child() must at least take a number, \
        a pattern (such as \"2n+3\") or the values \"even\" or \"odd\"."
    ),
    UnknownSelector(selector, value) => {
        let format_str = value
            .as_ref()
            .map_or_else(|| (*selector).to_string(), |v| format!("{selector}({v})"));
        format!("Invalid or unknown CSS pseudo-selector: ':{format_str}'")
    },
    InvalidNthChildPattern(selector) => format!(
        "Invalid pseudo-selector :{} - value has to be a \
        number, \"even\" or \"odd\" or a pattern such as \"2n+3\"", selector
    ),
    InvalidNthChild(e) => format!("Invalid :nth-child pseudo-selector: ':{}'", e),
}}

/// Wrapper for `UnknownSelector` error.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct UnknownSelectorError {
    pub selector: AzString,
    pub suggestion: OptionString,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum CssPseudoSelectorParseErrorOwned {
    EmptyNthChild,
    UnknownSelector(UnknownSelectorError),
    InvalidNthChildPattern(AzString),
    InvalidNthChild(crate::props::basic::error::ParseIntError),
}

impl CssPseudoSelectorParseError<'_> {
    #[must_use] pub fn to_contained(&self) -> CssPseudoSelectorParseErrorOwned {
        match self {
            CssPseudoSelectorParseError::EmptyNthChild => {
                CssPseudoSelectorParseErrorOwned::EmptyNthChild
            }
            CssPseudoSelectorParseError::UnknownSelector(a, b) => {
                CssPseudoSelectorParseErrorOwned::UnknownSelector(UnknownSelectorError {
                    selector: (*a).to_string().into(),
                    suggestion: b.map(|s| AzString::from(s.to_string())).into(),
                })
            }
            CssPseudoSelectorParseError::InvalidNthChildPattern(s) => {
                CssPseudoSelectorParseErrorOwned::InvalidNthChildPattern((*s).to_string().into())
            }
            CssPseudoSelectorParseError::InvalidNthChild(e) => {
                CssPseudoSelectorParseErrorOwned::InvalidNthChild(e.clone().into())
            }
        }
    }
}

impl CssPseudoSelectorParseErrorOwned {
    #[must_use] pub fn to_shared(&self) -> CssPseudoSelectorParseError<'_> {
        match self {
            Self::EmptyNthChild => {
                CssPseudoSelectorParseError::EmptyNthChild
            }
            Self::UnknownSelector(e) => {
                CssPseudoSelectorParseError::UnknownSelector(e.selector.as_str(), e.suggestion.as_ref().map(AzString::as_str))
            }
            Self::InvalidNthChildPattern(s) => {
                CssPseudoSelectorParseError::InvalidNthChildPattern(s)
            }
            Self::InvalidNthChild(e) => {
                CssPseudoSelectorParseError::InvalidNthChild(e.to_std())
            }
        }
    }
}

/// Error that can happen during `css_parser::parse_key_value_pair`
#[derive(Debug, Clone, PartialEq)]
pub enum DynamicCssParseError<'a> {
    /// The brace contents aren't valid, i.e. `var(asdlfkjasf)`
    InvalidBraceContents(&'a str),
    /// Unexpected value when parsing the string
    UnexpectedValue(CssParsingError<'a>),
}

impl_display! { DynamicCssParseError<'a>, {
    InvalidBraceContents(e) => format!("Invalid contents of var() function: var({})", e),
    UnexpectedValue(e) => format!("{}", e),
}}

impl<'a> From<CssParsingError<'a>> for DynamicCssParseError<'a> {
    fn from(e: CssParsingError<'a>) -> Self {
        DynamicCssParseError::UnexpectedValue(e)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum DynamicCssParseErrorOwned {
    InvalidBraceContents(AzString),
    UnexpectedValue(CssParsingErrorOwned),
}

impl DynamicCssParseError<'_> {
    #[must_use] pub fn to_contained(&self) -> DynamicCssParseErrorOwned {
        match self {
            DynamicCssParseError::InvalidBraceContents(s) => {
                DynamicCssParseErrorOwned::InvalidBraceContents((*s).to_string().into())
            }
            DynamicCssParseError::UnexpectedValue(e) => {
                DynamicCssParseErrorOwned::UnexpectedValue(e.to_contained())
            }
        }
    }
}

impl DynamicCssParseErrorOwned {
    #[must_use] pub fn to_shared(&self) -> DynamicCssParseError<'_> {
        match self {
            Self::InvalidBraceContents(s) => {
                DynamicCssParseError::InvalidBraceContents(s)
            }
            Self::UnexpectedValue(e) => {
                DynamicCssParseError::UnexpectedValue(e.to_shared())
            }
        }
    }
}

/// "selector" contains the actual selector such as "nth-child" while "value" contains
/// an optional value - for example "nth-child(3)" would be: selector: "nth-child", value: "3".
/// # Errors
///
/// Returns an error if `selector` (with optional `value`) is not a recognized CSS pseudo-selector.
pub fn pseudo_selector_from_str<'a>(
    selector: &'a str,
    value: Option<&'a str>,
) -> Result<CssPathPseudoSelector, CssPseudoSelectorParseError<'a>> {
    match selector {
        "first" => Ok(CssPathPseudoSelector::First),
        "last" => Ok(CssPathPseudoSelector::Last),
        "hover" => Ok(CssPathPseudoSelector::Hover),
        "active" => Ok(CssPathPseudoSelector::Active),
        "focus" => Ok(CssPathPseudoSelector::Focus),
        "dragging" => Ok(CssPathPseudoSelector::Dragging),
        "drag-over" => Ok(CssPathPseudoSelector::DragOver),
        "root" => Ok(CssPathPseudoSelector::Root),
        "nth-child" => {
            let value = value.ok_or(CssPseudoSelectorParseError::EmptyNthChild)?;
            let parsed = parse_nth_child_selector(value)?;
            Ok(CssPathPseudoSelector::NthChild(parsed))
        }
        "lang" => {
            let lang_value = value.ok_or(CssPseudoSelectorParseError::UnknownSelector(
                selector, value,
            ))?;
            // Remove quotes if present
            let lang_value = lang_value
                .trim()
                .trim_start_matches('"')
                .trim_end_matches('"')
                .trim_start_matches('\'')
                .trim_end_matches('\'')
                .trim();
            Ok(CssPathPseudoSelector::Lang(AzString::from(
                lang_value.to_string(),
            )))
        }
        _ => Err(CssPseudoSelectorParseError::UnknownSelector(
            selector, value,
        )),
    }
}

/// Parses the inner content of an attribute selector token (the text between `[` and `]`).
///
/// Returns `None` if the input is malformed (empty name, unterminated quote, etc).
#[must_use] pub fn parse_attribute_selector(input: &str) -> Option<CssAttributeSelector> {
    let s = input.trim();
    if s.is_empty() {
        return None;
    }

    // Find the operator (the longest match wins): try the compound operators
    // first (in order), then the bare `=`, otherwise it is an existence check.
    let compound_ops: [(&str, AttributeMatchOp); 5] = [
        ("~=", AttributeMatchOp::Includes),
        ("|=", AttributeMatchOp::DashMatch),
        ("^=", AttributeMatchOp::Prefix),
        ("$=", AttributeMatchOp::Suffix),
        ("*=", AttributeMatchOp::Substring),
    ];
    let (op, op_pos): (AttributeMatchOp, Option<usize>) = compound_ops
        .iter()
        .find_map(|(pat, op)| s.find(pat).map(|i| (*op, Some(i))))
        .or_else(|| s.find('=').map(|i| (AttributeMatchOp::Eq, Some(i))))
        .unwrap_or((AttributeMatchOp::Exists, None));

    let (name, value) = match op_pos {
        None => (s, None),
        Some(i) => {
            let name = s[..i].trim();
            let op_len = if matches!(op, AttributeMatchOp::Eq) { 1 } else { 2 };
            let raw_value = s[i + op_len..].trim();
            let unquoted = strip_attribute_quotes(raw_value)?;
            (name, Some(unquoted))
        }
    };

    if name.is_empty() {
        return None;
    }
    // Reject names that contain whitespace or quotes.
    if name.chars().any(|c| c.is_whitespace() || c == '"' || c == '\'') {
        return None;
    }

    Some(CssAttributeSelector {
        name: name.to_string().into(),
        op,
        value: value
            .map_or_else(|| OptionString::None, |v| OptionString::Some(v.to_string().into())),
    })
}

/// Strips matching surrounding `"` or `'` from a value. If the value is unquoted,
/// returns it unchanged. Returns `None` if quoting is unbalanced.
fn strip_attribute_quotes(s: &str) -> Option<&str> {
    let bytes = s.as_bytes();
    if bytes.len() >= 2 {
        let first = bytes[0];
        let last = bytes[bytes.len() - 1];
        if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
            return Some(&s[1..s.len() - 1]);
        }
        if first == b'"' || first == b'\'' || last == b'"' || last == b'\'' {
            // Unbalanced quote.
            return None;
        }
    } else if bytes.len() == 1 && (bytes[0] == b'"' || bytes[0] == b'\'') {
        return None;
    }
    Some(s)
}

/// Parses the inner value of the `:nth-child` selector, including numbers and patterns.
///
/// I.e.: `"2n+3"` -> `Pattern { repeat: 2, offset: 3 }`
fn parse_nth_child_selector(
    value: &str,
) -> Result<CssNthChildSelector, CssPseudoSelectorParseError<'_>> {
    let value = value.trim();

    if value.is_empty() {
        return Err(CssPseudoSelectorParseError::EmptyNthChild);
    }

    if let Ok(number) = value.parse::<u32>() {
        return Ok(CssNthChildSelector::Number(number));
    }

    // If the value is not a number
    match value {
        "even" => Ok(CssNthChildSelector::Even),
        "odd" => Ok(CssNthChildSelector::Odd),
        _ => parse_nth_child_pattern(value),
    }
}

/// Parses the pattern between the braces of a "nth-child" (such as "2n+3").
fn parse_nth_child_pattern(
    value: &str,
) -> Result<CssNthChildSelector, CssPseudoSelectorParseError<'_>> {
    use crate::css::CssNthChildPattern;

    let value = value.trim();

    if value.is_empty() {
        return Err(CssPseudoSelectorParseError::EmptyNthChild);
    }

    // TODO: Test for "+"
    let repeat = value
        .split('n')
        .next()
        .ok_or(CssPseudoSelectorParseError::InvalidNthChildPattern(value))?
        .trim()
        .parse::<u32>()?;

    // In a "2n+3" form, the first .next() yields the "2n", the second .next() yields the "3"
    let mut offset_iterator = value.split('+');

    // has to succeed, since the string is verified to not be empty
    offset_iterator.next().unwrap();

    let offset = match offset_iterator.next() {
        Some(offset_string) => {
            let offset_string = offset_string.trim();
            if offset_string.is_empty() {
                return Err(CssPseudoSelectorParseError::InvalidNthChildPattern(value));
            }
            offset_string.parse::<u32>()?
        }
        None => 0,
    };

    Ok(CssNthChildSelector::Pattern(CssNthChildPattern {
        pattern_repeat: repeat,
        offset,
    }))
}

#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct ErrorLocation {
    pub original_pos: usize,
}

/// FFI-safe replacement for `(ErrorLocation, ErrorLocation)` tuple.
/// Represents a range (start..end) in the source text.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct ErrorLocationRange {
    pub start: ErrorLocation,
    pub end: ErrorLocation,
}

impl ErrorLocation {
    /// Given an error location, returns the (line, column)
    #[must_use] pub fn get_line_column_from_error(&self, css_string: &str) -> (usize, usize) {
        // `original_pos` is a pub field and, at Token::EndOfStream, `get_error_location`
        // records it as exactly `css_string.len()` -- so `- 1` lands INSIDE the final
        // character whenever the stylesheet ends in a multi-byte char, and an
        // out-of-range value is trivially constructible. Both used to panic here, i.e.
        // simply Display-ing a parse error on Unicode CSS would abort.
        let error_location =
            clamp_to_char_boundary(css_string, self.original_pos.saturating_sub(1));
        let (mut line_number, mut total_characters) = (0, 0);

        for line in css_string[0..error_location].lines() {
            line_number += 1;
            total_characters += line.chars().count();
        }

        // Rust doesn't count "\n" as a character, so we have to add the line number count on top
        let total_characters = total_characters + line_number;
        let column_pos = error_location - total_characters.saturating_sub(2);

        (line_number, column_pos)
    }
}

impl fmt::Display for CssParseError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let start_location = self.location.start.get_line_column_from_error(self.css_string);
        let end_location = self.location.end.get_line_column_from_error(self.css_string);
        write!(
            f,
            "    start: line {}:{}\r\n    end: line {}:{}\r\n    text: \"{}\"\r\n    reason: {}",
            start_location.0,
            start_location.1,
            end_location.0,
            end_location.1,
            self.get_error_string(),
            self.error,
        )
    }
}

/// Parses a CSS string into a [`Css`] value and a list of recoverable warnings.
///
/// Never panics. Syntax errors and unsupported properties are collected as
/// [`CssParseWarnMsg`] items rather than causing a hard failure, so the caller
/// always receives a (possibly empty) stylesheet.
#[must_use] pub fn new_from_str(css_string: &str) -> (Css, Vec<CssParseWarnMsg<'_>>) {
    let mut tokenizer = Tokenizer::new(css_string);
    let (rules, warnings) = new_from_str_inner(css_string, &mut tokenizer);

    (
        Css { rules: rules.into() },
        warnings,
    )
}

/// Returns the location of where the parser is currently in the document
fn get_error_location(tokenizer: &Tokenizer<'_>) -> ErrorLocation {
    ErrorLocation {
        original_pos: tokenizer.pos(),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CssPathParseError<'a> {
    EmptyPath,
    /// Invalid item encountered in string (for example a "{", "}")
    InvalidTokenEncountered(&'a str),
    UnexpectedEndOfStream(&'a str),
    SyntaxError(CssSyntaxError),
    /// The path has to be either `*`, `div`, `p` or something like that
    NodeTypeTag(NodeTypeTagParseError<'a>),
    /// Error while parsing a pseudo selector (like `:aldkfja`)
    PseudoSelectorParseError(CssPseudoSelectorParseError<'a>),
}

impl_from! { NodeTypeTagParseError<'a>, CssPathParseError::NodeTypeTag }
impl_from! { CssPseudoSelectorParseError<'a>, CssPathParseError::PseudoSelectorParseError }

impl From<CssSyntaxError> for CssPathParseError<'_> {
    fn from(e: CssSyntaxError) -> Self {
        CssPathParseError::SyntaxError(e)
    }
}

impl From<SimplecssError> for CssPathParseError<'_> {
    fn from(e: SimplecssError) -> Self {
        CssPathParseError::SyntaxError(CssSyntaxError::from(e))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CssPathParseErrorOwned {
    EmptyPath,
    InvalidTokenEncountered(AzString),
    UnexpectedEndOfStream(AzString),
    SyntaxError(CssSyntaxError),
    NodeTypeTag(NodeTypeTagParseErrorOwned),
    PseudoSelectorParseError(CssPseudoSelectorParseErrorOwned),
}

impl CssPathParseError<'_> {
    #[must_use] pub fn to_contained(&self) -> CssPathParseErrorOwned {
        match self {
            CssPathParseError::EmptyPath => CssPathParseErrorOwned::EmptyPath,
            CssPathParseError::InvalidTokenEncountered(s) => {
                CssPathParseErrorOwned::InvalidTokenEncountered((*s).to_string().into())
            }
            CssPathParseError::UnexpectedEndOfStream(s) => {
                CssPathParseErrorOwned::UnexpectedEndOfStream((*s).to_string().into())
            }
            CssPathParseError::SyntaxError(e) => CssPathParseErrorOwned::SyntaxError(*e),
            CssPathParseError::NodeTypeTag(e) => {
                CssPathParseErrorOwned::NodeTypeTag(e.to_contained())
            }
            CssPathParseError::PseudoSelectorParseError(e) => {
                CssPathParseErrorOwned::PseudoSelectorParseError(e.to_contained())
            }
        }
    }
}

impl CssPathParseErrorOwned {
    #[must_use] pub fn to_shared(&self) -> CssPathParseError<'_> {
        match self {
            Self::EmptyPath => CssPathParseError::EmptyPath,
            Self::InvalidTokenEncountered(s) => {
                CssPathParseError::InvalidTokenEncountered(s)
            }
            Self::UnexpectedEndOfStream(s) => {
                CssPathParseError::UnexpectedEndOfStream(s)
            }
            Self::SyntaxError(e) => CssPathParseError::SyntaxError(*e),
            Self::NodeTypeTag(e) => CssPathParseError::NodeTypeTag(e.to_shared()),
            Self::PseudoSelectorParseError(e) => {
                CssPathParseError::PseudoSelectorParseError(e.to_shared())
            }
        }
    }
}

/// Parses a CSS path from a string (only the path,.no commas allowed)
///
/// ```rust
/// # extern crate azul_css;
/// # use azul_css::parser2::parse_css_path;
/// # use azul_css::css::{
/// #     CssPathSelector::*, CssPathPseudoSelector::*, CssPath,
/// #     NodeTypeTag::*, CssNthChildSelector::*
/// # };
///
/// assert_eq!(
///     parse_css_path("* div #my_id > .class:nth-child(2)"),
///     Ok(CssPath {
///         selectors: vec![
///             Global,
///             Type(Div),
///             Children,
///             Id("my_id".to_string().into()),
///             DirectChildren,
///             Class("class".to_string().into()),
///             PseudoSelector(NthChild(Number(2))),
///         ]
///         .into()
///     })
/// );
/// ```
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `css-path` value.
pub fn parse_css_path(input: &str) -> Result<CssPath, CssPathParseError<'_>> {
    use azul_simplecss::{Combinator, Token};

    let input = input.trim();
    if input.is_empty() {
        return Err(CssPathParseError::EmptyPath);
    }

    let mut tokenizer = Tokenizer::new(input);
    let mut selectors = Vec::new();

    loop {
        let token = tokenizer.parse_next()?;
        match token {
            Token::UniversalSelector => {
                selectors.push(CssPathSelector::Global);
            }
            Token::TypeSelector(div_type) => match NodeTypeTag::from_str(div_type) {
                // An unknown type selector must invalidate the whole path (Selectors L4:
                // an invalid simple selector invalidates the selector), not be silently
                // dropped — dropping it left a dangling combinator that matched every
                // descendant of the previous selector.
                Ok(nt) => selectors.push(CssPathSelector::Type(nt)),
                Err(e) => return Err(CssPathParseError::NodeTypeTag(e)),
            },
            Token::IdSelector(id) => {
                selectors.push(CssPathSelector::Id(id.to_string().into()));
            }
            Token::ClassSelector(class) => {
                selectors.push(CssPathSelector::Class(class.to_string().into()));
            }
            Token::Combinator(Combinator::GreaterThan) => {
                selectors.push(CssPathSelector::DirectChildren);
            }
            Token::Combinator(Combinator::Space) => {
                selectors.push(CssPathSelector::Children);
            }
            Token::Combinator(Combinator::Plus) => {
                selectors.push(CssPathSelector::AdjacentSibling);
            }
            Token::Combinator(Combinator::Tilde) => {
                selectors.push(CssPathSelector::GeneralSibling);
            }
            Token::PseudoClass { selector, value } => {
                selectors.push(CssPathSelector::PseudoSelector(pseudo_selector_from_str(
                    selector, value,
                )?));
            }
            Token::EndOfStream => {
                break;
            }
            _ => {
                return Err(CssPathParseError::InvalidTokenEncountered(input));
            }
        }
    }

    if selectors.is_empty() {
        Err(CssPathParseError::EmptyPath)
    } else {
        Ok(CssPath {
            selectors: selectors.into(),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnparsedCssRuleBlock<'a> {
    /// The css path (full selector) of the style ruleset
    pub path: CssPath,
    /// `"justify-content" => "center"`
    pub declarations: BTreeMap<&'a str, (&'a str, ErrorLocationRange)>,
    /// Conditions from enclosing @-rules (@media, @lang, etc.)
    pub conditions: Vec<DynamicSelector>,
}

/// Owned version of `UnparsedCssRuleBlock`, with `BTreeMap` of Strings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnparsedCssRuleBlockOwned {
    pub path: CssPath,
    pub declarations: BTreeMap<String, (String, ErrorLocationRange)>,
    pub conditions: Vec<DynamicSelector>,
}

impl UnparsedCssRuleBlock<'_> {
    #[must_use] pub fn to_contained(&self) -> UnparsedCssRuleBlockOwned {
        UnparsedCssRuleBlockOwned {
            path: self.path.clone(),
            declarations: self
                .declarations
                .iter()
                .map(|(k, (v, loc))| ((*k).to_string(), ((*v).to_string(), *loc)))
                .collect(),
            conditions: self.conditions.clone(),
        }
    }
}

impl UnparsedCssRuleBlockOwned {
    #[must_use] pub fn to_shared(&self) -> UnparsedCssRuleBlock<'_> {
        UnparsedCssRuleBlock {
            path: self.path.clone(),
            declarations: self
                .declarations
                .iter()
                .map(|(k, (v, loc))| (k.as_str(), (v.as_str(), *loc)))
                .collect(),
            conditions: self.conditions.clone(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CssParseWarnMsg<'a> {
    pub warning: CssParseWarnMsgInner<'a>,
    pub location: ErrorLocationRange,
}

/// Owned version of `CssParseWarnMsg`, where warning is the owned type.
#[derive(Debug, Clone, PartialEq)]
pub struct CssParseWarnMsgOwned {
    pub warning: CssParseWarnMsgInnerOwned,
    pub location: ErrorLocationRange,
}

impl CssParseWarnMsg<'_> {
    #[must_use] pub fn to_contained(&self) -> CssParseWarnMsgOwned {
        CssParseWarnMsgOwned {
            warning: self.warning.to_contained(),
            location: self.location,
        }
    }
}

impl CssParseWarnMsgOwned {
    #[must_use] pub fn to_shared(&self) -> CssParseWarnMsg<'_> {
        CssParseWarnMsg {
            warning: self.warning.to_shared(),
            location: self.location,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum CssParseWarnMsgInner<'a> {
    /// Key "blah" isn't (yet) supported, so the parser didn't attempt to parse the value at all
    UnsupportedKeyValuePair { key: &'a str, value: &'a str },
    /// A CSS parse error that was encountered but recovered from
    ParseError(CssParseErrorInner<'a>),
    /// A rule was skipped due to an error
    SkippedRule {
        selector: Option<&'a str>,
        error: CssParseErrorInner<'a>,
    },
    /// A declaration was skipped due to an error
    SkippedDeclaration {
        key: &'a str,
        value: &'a str,
        error: CssParseErrorInner<'a>,
    },
    /// Malformed block structure (mismatched braces, etc.)
    MalformedStructure { message: &'a str },
}

#[derive(Debug, Clone, PartialEq)]
pub enum CssParseWarnMsgInnerOwned {
    UnsupportedKeyValuePair {
        key: String,
        value: String,
    },
    ParseError(CssParseErrorInnerOwned),
    SkippedRule {
        selector: Option<String>,
        error: CssParseErrorInnerOwned,
    },
    SkippedDeclaration {
        key: String,
        value: String,
        error: CssParseErrorInnerOwned,
    },
    MalformedStructure {
        message: String,
    },
}

impl CssParseWarnMsgInner<'_> {
    #[must_use] pub fn to_contained(&self) -> CssParseWarnMsgInnerOwned {
        match self {
            Self::UnsupportedKeyValuePair { key, value } => {
                CssParseWarnMsgInnerOwned::UnsupportedKeyValuePair {
                    key: (*key).to_string(),
                    value: (*value).to_string(),
                }
            }
            Self::ParseError(e) => CssParseWarnMsgInnerOwned::ParseError(e.to_contained()),
            Self::SkippedRule { selector, error } => CssParseWarnMsgInnerOwned::SkippedRule {
                selector: selector.map(std::string::ToString::to_string),
                error: error.to_contained(),
            },
            Self::SkippedDeclaration { key, value, error } => {
                CssParseWarnMsgInnerOwned::SkippedDeclaration {
                    key: (*key).to_string(),
                    value: (*value).to_string(),
                    error: error.to_contained(),
                }
            }
            Self::MalformedStructure { message } => CssParseWarnMsgInnerOwned::MalformedStructure {
                message: (*message).to_string(),
            },
        }
    }
}

impl CssParseWarnMsgInnerOwned {
    #[must_use] pub fn to_shared(&self) -> CssParseWarnMsgInner<'_> {
        match self {
            Self::UnsupportedKeyValuePair { key, value } => {
                CssParseWarnMsgInner::UnsupportedKeyValuePair { key, value }
            }
            Self::ParseError(e) => CssParseWarnMsgInner::ParseError(e.to_shared()),
            Self::SkippedRule { selector, error } => CssParseWarnMsgInner::SkippedRule {
                selector: selector.as_deref(),
                error: error.to_shared(),
            },
            Self::SkippedDeclaration { key, value, error } => {
                CssParseWarnMsgInner::SkippedDeclaration {
                    key,
                    value,
                    error: error.to_shared(),
                }
            }
            Self::MalformedStructure { message } => {
                CssParseWarnMsgInner::MalformedStructure { message }
            }
        }
    }
}

impl_display! { CssParseWarnMsgInner<'a>, {
    UnsupportedKeyValuePair { key, value } => format!("Unsupported CSS property: \"{}: {}\"", key, value),
    ParseError(e) => format!("Parse error (recoverable): {}", e),
    SkippedRule { selector, error } => {
        let sel = selector.unwrap_or("unknown");
        format!("Skipped rule for selector '{sel}': {error}")
    },
    SkippedDeclaration { key, value, error } => format!("Skipped declaration '{}:{}': {}", key, value, error),
    MalformedStructure { message } => format!("Malformed CSS structure: {}", message),
}}

/// Parses @media conditions from the content following "@media"
/// Returns a list of `DynamicSelectors` for the conditions
fn parse_media_conditions(content: &str) -> Vec<DynamicSelector> {
    let mut conditions = Vec::new();
    let content = content.trim();

    // Handle simple media types: "screen", "print", "all"
    if content.eq_ignore_ascii_case("screen") {
        conditions.push(DynamicSelector::Media(MediaType::Screen));
        return conditions;
    }
    if content.eq_ignore_ascii_case("print") {
        conditions.push(DynamicSelector::Media(MediaType::Print));
        return conditions;
    }
    if content.eq_ignore_ascii_case("all") {
        conditions.push(DynamicSelector::Media(MediaType::All));
        return conditions;
    }

    // Parse more complex media queries like "(min-width: 800px)" or "screen and (max-width: 600px)"
    // Split by "and" for compound queries
    for part in content.split(" and ") {
        let part = part.trim();

        // Skip media type keywords in compound queries
        if part.eq_ignore_ascii_case("screen")
            || part.eq_ignore_ascii_case("print")
            || part.eq_ignore_ascii_case("all")
        {
            if part.eq_ignore_ascii_case("screen") {
                conditions.push(DynamicSelector::Media(MediaType::Screen));
            } else if part.eq_ignore_ascii_case("print") {
                conditions.push(DynamicSelector::Media(MediaType::Print));
            } else if part.eq_ignore_ascii_case("all") {
                conditions.push(DynamicSelector::Media(MediaType::All));
            }
            continue;
        }

        // Parse parenthesized conditions like "(min-width: 800px)"
        if let Some(inner) = part.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
            if let Some(selector) = parse_media_feature(inner) {
                conditions.push(selector);
            }
        }
    }

    conditions
}

/// Parses a single media feature like "min-width: 800px"
fn parse_media_feature(feature: &str) -> Option<DynamicSelector> {
    let parts: Vec<&str> = feature.splitn(2, ':').collect();
    if parts.len() != 2 {
        // Handle features without values like "orientation: portrait"
        return None;
    }

    let key = parts[0].trim();
    let value = parts[1].trim();

    match key.to_lowercase().as_str() {
        "min-width" => {
            if let Some(px) = parse_px_value(value) {
                return Some(DynamicSelector::ViewportWidth(MinMaxRange::new(
                    Some(px),
                    None,
                )));
            }
        }
        "max-width" => {
            if let Some(px) = parse_px_value(value) {
                return Some(DynamicSelector::ViewportWidth(MinMaxRange::new(
                    None,
                    Some(px),
                )));
            }
        }
        "min-height" => {
            if let Some(px) = parse_px_value(value) {
                return Some(DynamicSelector::ViewportHeight(MinMaxRange::new(
                    Some(px),
                    None,
                )));
            }
        }
        "max-height" => {
            if let Some(px) = parse_px_value(value) {
                return Some(DynamicSelector::ViewportHeight(MinMaxRange::new(
                    None,
                    Some(px),
                )));
            }
        }
        "orientation" => {
            if value.eq_ignore_ascii_case("portrait") {
                return Some(DynamicSelector::Orientation(OrientationType::Portrait));
            } else if value.eq_ignore_ascii_case("landscape") {
                return Some(DynamicSelector::Orientation(OrientationType::Landscape));
            }
        }
        "prefers-color-scheme" => {
            if value.eq_ignore_ascii_case("dark") {
                return Some(DynamicSelector::Theme(ThemeCondition::Dark));
            } else if value.eq_ignore_ascii_case("light") {
                return Some(DynamicSelector::Theme(ThemeCondition::Light));
            }
        }
        "prefers-reduced-motion" => {
            if value.eq_ignore_ascii_case("reduce") {
                return Some(DynamicSelector::PrefersReducedMotion(BoolCondition::True));
            } else if value.eq_ignore_ascii_case("no-preference") {
                return Some(DynamicSelector::PrefersReducedMotion(BoolCondition::False));
            }
        }
        "prefers-contrast" | "prefers-high-contrast" => {
            if value.eq_ignore_ascii_case("more") || value.eq_ignore_ascii_case("high") || value.eq_ignore_ascii_case("active") {
                return Some(DynamicSelector::PrefersHighContrast(BoolCondition::True));
            } else if value.eq_ignore_ascii_case("no-preference") || value.eq_ignore_ascii_case("none") {
                return Some(DynamicSelector::PrefersHighContrast(BoolCondition::False));
            }
        }
        "aspect-ratio" => {
            if let Some(ratio) = parse_ratio_value(value) {
                return Some(DynamicSelector::AspectRatio(MinMaxRange::new(Some(ratio), Some(ratio))));
            }
        }
        "min-aspect-ratio" => {
            if let Some(ratio) = parse_ratio_value(value) {
                return Some(DynamicSelector::AspectRatio(MinMaxRange::new(Some(ratio), None)));
            }
        }
        "max-aspect-ratio" => {
            if let Some(ratio) = parse_ratio_value(value) {
                return Some(DynamicSelector::AspectRatio(MinMaxRange::new(None, Some(ratio))));
            }
        }
        _ => {}
    }

    None
}

/// Parses a pixel value like "800px" and returns the numeric value
fn parse_px_value(value: &str) -> Option<f32> {
    let value = value.trim();
    value
        .strip_suffix("px")
        .map_or_else(
            // Try parsing as a bare number
            || value.parse::<f32>().ok(),
            |num_str| num_str.trim().parse::<f32>().ok(),
        )
        // `str::parse::<f32>` accepts "NaN"/"inf"/"infinity"; the CSS <number-token>
        // grammar does not (CSS Syntax L3 §4.3.6 — digits, no keywords). Letting a NaN
        // through is not merely lax: `MinMaxRange` encodes "no bound" AS NaN, so
        // `@media (min-width: NaN)` would silently become an unconditional match
        // instead of an invalid feature. Reject non-finite at the source.
        .filter(|v| v.is_finite())
}

/// Parses a ratio value like "16/9" or "1.777" and returns it as f32
fn parse_ratio_value(value: &str) -> Option<f32> {
    let value = value.trim();
    if let Some((num, den)) = value.split_once('/') {
        let num: f32 = num.trim().parse().ok()?;
        let den: f32 = den.trim().parse().ok()?;
        if den == 0.0 { return None; }
        // Same NaN-sentinel hazard as parse_px_value: "inf/inf" and "1/NaN" both parse,
        // and a NaN ratio reads back out of MinMaxRange as "no bound".
        Some(num / den).filter(|r| r.is_finite())
    } else {
        value.parse::<f32>().ok().filter(|r| r.is_finite())
    }
}

/// Parses @container conditions from the content following "@container"
/// Format: @container (min-width: 400px) or @container sidebar (min-width: 400px)
fn parse_container_conditions(content: &str) -> Vec<DynamicSelector> {
    let mut conditions = Vec::new();
    let content = content.trim();

    // Check if there's a container name before the parenthesized condition
    // e.g., "sidebar (min-width: 400px)" or just "(min-width: 400px)"
    let (name_part, query_part) = if content.starts_with('(') {
        (None, content)
    } else if let Some(paren_idx) = content.find('(') {
        let name = content[..paren_idx].trim();
        if name.is_empty() {
            (None, content)
        } else {
            (Some(name), &content[paren_idx..])
        }
    } else {
        // No parentheses - might be just a container name
        if !content.is_empty() {
            conditions.push(DynamicSelector::ContainerName(AzString::from(content.to_string())));
        }
        return conditions;
    };

    if let Some(name) = name_part {
        conditions.push(DynamicSelector::ContainerName(AzString::from(name.to_string())));
    }

    // Parse the parenthesized query parts
    for part in query_part.split(" and ") {
        let part = part.trim();
        if let Some(inner) = part.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
            if let Some(selector) = parse_container_feature(inner) {
                conditions.push(selector);
            }
        }
    }

    conditions
}

/// Parses a single container query feature like "min-width: 400px"
fn parse_container_feature(feature: &str) -> Option<DynamicSelector> {
    let (key, value) = feature.split_once(':')?;
    let key = key.trim();
    let value = value.trim();

    match key.to_lowercase().as_str() {
        "min-width" => {
            parse_px_value(value).map(|px| DynamicSelector::ContainerWidth(MinMaxRange::new(Some(px), None)))
        }
        "max-width" => {
            parse_px_value(value).map(|px| DynamicSelector::ContainerWidth(MinMaxRange::new(None, Some(px))))
        }
        "min-height" => {
            parse_px_value(value).map(|px| DynamicSelector::ContainerHeight(MinMaxRange::new(Some(px), None)))
        }
        "max-height" => {
            parse_px_value(value).map(|px| DynamicSelector::ContainerHeight(MinMaxRange::new(None, Some(px))))
        }
        "aspect-ratio" => {
            parse_ratio_value(value).map(|r| DynamicSelector::AspectRatio(MinMaxRange::new(Some(r), Some(r))))
        }
        "min-aspect-ratio" => {
            parse_ratio_value(value).map(|r| DynamicSelector::AspectRatio(MinMaxRange::new(Some(r), None)))
        }
        "max-aspect-ratio" => {
            parse_ratio_value(value).map(|r| DynamicSelector::AspectRatio(MinMaxRange::new(None, Some(r))))
        }
        _ => None,
    }
}

/// Parses @theme condition from the content following "@theme"
/// Format: @theme(dark) or @theme dark
fn parse_theme_condition(content: &str) -> Option<DynamicSelector> {
    let content = content.trim();
    let inner = content
        .strip_prefix('(')
        .and_then(|s| s.strip_suffix(')'))
        .unwrap_or(content)
        .trim();
    let inner = inner
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| inner.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
        .unwrap_or(inner)
        .trim();

    match inner.to_lowercase().as_str() {
        "dark" => Some(DynamicSelector::Theme(ThemeCondition::Dark)),
        "light" => Some(DynamicSelector::Theme(ThemeCondition::Light)),
        _ => None,
    }
}

/// Parses @lang condition from the content following "@lang"
/// Format: @lang("de-DE") or @lang(de-DE)
fn parse_lang_condition(content: &str) -> Option<DynamicSelector> {
    let content = content.trim();

    // Remove parentheses and quotes
    let lang = content
        .strip_prefix('(')
        .and_then(|s| s.strip_suffix(')'))
        .unwrap_or(content)
        .trim();

    let lang = lang
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| lang.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
        .unwrap_or(lang)
        .trim();

    if lang.is_empty() {
        return None;
    }

    // Use Prefix matching by default (e.g., "de" matches "de-DE", "de-AT")
    Some(DynamicSelector::Language(LanguageCondition::Prefix(
        AzString::from(lang.to_string()),
    )))
}

/// Parses a CSS string (single-threaded) and returns the parsed rules in blocks
///
/// May return "warning" messages, i.e. messages that just serve as a warning,
/// instead of being actual errors. These warnings may be ignored by the caller,
/// but can be useful for debugging.
// Beyond this CSS nesting depth, get_parent_paths clones the ever-growing
// ancestor path every level (parse becomes O(depth^2) — a hang on adversarial
// input like `div{` x 10_000), so deeper rules keep only their own local
// selector. No realistic stylesheet nests this deep; this bounds parse time.
const MAX_NESTING_DEPTH: usize = 1024;

#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose CSS parser/formatter/dispatch table (one branch per property/variant)
fn new_from_str_inner<'a>(
    css_string: &'a str,
    tokenizer: &mut Tokenizer<'a>,
) -> (Vec<CssRuleBlock>, Vec<CssParseWarnMsg<'a>>) {
    use azul_simplecss::{Combinator, Token};

    // Stack entry for nested selectors: accumulated parent paths + the current
    // declarations at this nesting level.
    struct NestingLevel<'a> {
        paths: Vec<Vec<CssPathSelector>>,
        declarations: BTreeMap<&'a str, (&'a str, ErrorLocationRange)>,
        depth: usize,
    }

    // Helper: get parent paths from nesting stack (if any)
    fn get_parent_paths(nesting_stack: &[NestingLevel<'_>]) -> Vec<Vec<CssPathSelector>> {
        nesting_stack
            .last()
            .map_or_else(Vec::new, |parent| parent.paths.clone())
    }

    // Helper: combine parent path with child selector for nesting
    // For .button { :hover { } } -> .button:hover
    // For .outer { .inner { } } -> .outer .inner (with Children combinator)
    fn combine_paths(
        parent_paths: &[Vec<CssPathSelector>],
        child_path: &[CssPathSelector],
        is_pseudo_only: bool,
    ) -> Vec<Vec<CssPathSelector>> {
        if parent_paths.is_empty() {
            vec![child_path.to_vec()]
        } else {
            parent_paths
                .iter()
                .map(|parent| {
                    let mut combined = parent.clone();
                    if !is_pseudo_only && !child_path.is_empty() {
                        // Add implicit descendant combinator for non-pseudo selectors
                        combined.push(CssPathSelector::Children);
                    }
                    combined.extend(child_path.iter().cloned());
                    combined
                })
                .collect()
        }
    }

    let mut css_blocks = Vec::new();
    let mut warnings = Vec::new();

    let mut block_nesting = 0_usize;
    let mut last_path: Vec<CssPathSelector> = Vec::new();
    let mut last_error_location = ErrorLocation { original_pos: 0 };

    // Stack for tracking @-rule conditions (e.g., @media, @lang, @os)
    // Each entry contains the conditions and the nesting level where they were introduced
    let mut at_rule_stack: Vec<(Vec<DynamicSelector>, usize)> = Vec::new();
    // Pending @-rule that needs to be combined with AtStr tokens
    let mut pending_at_rule: Option<&str> = None;
    // Collect multiple AtStr tokens (e.g., "screen", "(min-width: 800px)" for compound media queries)
    let mut pending_at_str_parts: Vec<String> = Vec::new();

    // Stack for nested selectors
    // Each entry: (parent_paths, declarations, nesting_level)
    // parent_paths: all accumulated paths at this level (for comma-separated selectors)
    // declarations: current declarations at this level
    let mut nesting_stack: Vec<NestingLevel<'a>> = Vec::new();
    // Current accumulated paths before BlockStart
    let mut current_paths: Vec<Vec<CssPathSelector>> = Vec::new();
    // Current declarations at current level
    let mut current_declarations: BTreeMap<&str, (&str, ErrorLocationRange)> = BTreeMap::new();

    // Safety: limit maximum iterations to prevent infinite loops
    // A reasonable limit is 10x the input length (each char could produce at most a few tokens)
    let max_iterations = css_string.len().saturating_mul(10).max(1000);
    let mut iterations = 0_usize;
    let mut last_position = 0_usize;
    let mut stuck_count = 0_usize;

    loop {
        // Safety check 1: Maximum iterations
        iterations += 1;
        if iterations > max_iterations {
            warnings.push(CssParseWarnMsg {
                warning: CssParseWarnMsgInner::MalformedStructure {
                    message: "Parser iteration limit exceeded - possible infinite loop",
                },
                location: ErrorLocationRange { start: last_error_location, end: get_error_location(tokenizer) },
            });
            break;
        }

        // Safety check 2: Detect if parser is stuck (position not advancing)
        let current_position = tokenizer.pos();
        if current_position == last_position {
            stuck_count += 1;
            if stuck_count > 10 {
                warnings.push(CssParseWarnMsg {
                    warning: CssParseWarnMsgInner::MalformedStructure {
                        message: "Parser stuck - position not advancing",
                    },
                    location: ErrorLocationRange { start: last_error_location, end: get_error_location(tokenizer) },
                });
                break;
            }
        } else {
            stuck_count = 0;
            last_position = current_position;
        }

        let token = match tokenizer.parse_next() {
            Ok(token) => token,
            Err(e) => {
                let error_location = get_error_location(tokenizer);
                // An unclosed block that still contains a declaration makes the
                // tokenizer raise UnexpectedEndOfStream while scanning past the last `;`
                // for the missing `}`, BEFORE the loop ever reaches Token::EndOfStream.
                // Emit the same dedicated "unclosed blocks" diagnostic that arm would,
                // rather than a generic parse error, when we're still inside a block.
                let warning = if block_nesting != 0 {
                    CssParseWarnMsgInner::MalformedStructure {
                        message: "Unclosed blocks at end of file",
                    }
                } else {
                    CssParseWarnMsgInner::ParseError(e.into())
                };
                warnings.push(CssParseWarnMsg {
                    warning,
                    location: ErrorLocationRange { start: last_error_location, end: error_location },
                });
                // On error, break to avoid infinite loop - the tokenizer may be stuck
                break;
            }
        };

        macro_rules! warn_and_continue {
            ($warning:expr) => {{
                warnings.push(CssParseWarnMsg {
                    warning: $warning,
                    location: ErrorLocationRange { start: last_error_location, end: get_error_location(tokenizer) },
                });
                continue;
            }};
        }

        match token {
            Token::AtRule(rule_name) => {
                // Store the @-rule name to combine with the following AtStr tokens
                pending_at_rule = Some(rule_name);
                pending_at_str_parts.clear();
            }
            Token::AtStr(content) => {
                // Collect AtStr tokens until we see BlockStart
                if pending_at_rule.is_some() {
                    // Skip "and" keyword, it's just a separator
                    if !content.eq_ignore_ascii_case("and") {
                        pending_at_str_parts.push(content.to_string());
                    }
                }
            }
            Token::BlockStart => {
                // Process pending @-rule with all collected AtStr parts
                if let Some(rule_name) = pending_at_rule.take() {
                    let combined_content = pending_at_str_parts.join(" and ");
                    pending_at_str_parts.clear();
                    
                    let conditions = match rule_name.to_lowercase().as_str() {
                        "media" => parse_media_conditions(&combined_content),
                        "lang" => parse_lang_condition(&combined_content).into_iter().collect(),
                        "os" => crate::dynamic_selector::parse_os_at_rule_content(&combined_content).unwrap_or_default(),
                        "theme" => parse_theme_condition(&combined_content).into_iter().collect(),
                        "container" => parse_container_conditions(&combined_content),
                        _ => {
                            // Unknown @-rule, ignore
                            Vec::new()
                        }
                    };

                    if !conditions.is_empty() {
                        // Push conditions to stack, will be applied to nested rules
                        at_rule_stack.push((conditions, block_nesting + 1));
                    }
                }

                block_nesting += 1;

                // If we have a selector, push current state onto nesting stack
                if !current_paths.is_empty() || !last_path.is_empty() {
                    // Finalize current_paths with last_path
                    if !last_path.is_empty() {
                        current_paths.push(last_path.clone());
                        last_path.clear();
                    }

                    // Get parent paths and combine with current paths. Beyond
                    // MAX_NESTING_DEPTH, stop combining with the ancestor chain to
                    // bound the O(depth^2) path-cloning (see the const's doc above).
                    let combined_paths: Vec<Vec<CssPathSelector>> = if block_nesting > MAX_NESTING_DEPTH {
                        std::mem::take(&mut current_paths)
                    } else {
                        let parent_paths = get_parent_paths(&nesting_stack);
                        if parent_paths.is_empty() {
                            current_paths.clone()
                        } else {
                            // Combine each parent path with each current path
                            let mut result = Vec::new();
                            for parent in &parent_paths {
                                for child in &current_paths {
                                    // Check if child starts with pseudo-selector
                                    let is_pseudo_only = child.first().is_some_and(|s| matches!(s, CssPathSelector::PseudoSelector(_)));
                                    let mut combined = parent.clone();
                                    if !is_pseudo_only && !child.is_empty() {
                                        combined.push(CssPathSelector::Children);
                                    }
                                    combined.extend(child.iter().cloned());
                                    result.push(combined);
                                }
                            }
                            result
                        }
                    };

                    // Push to nesting stack
                    nesting_stack.push(NestingLevel {
                        paths: combined_paths,
                        declarations: std::mem::take(&mut current_declarations),
                        depth: block_nesting,
                    });
                    current_paths.clear();
                }
            }
            Token::Comma => {
                // Comma separates selectors
                if !last_path.is_empty() {
                    current_paths.push(last_path.clone());
                    last_path.clear();
                }
            }
            Token::BlockEnd => {
                if block_nesting == 0 {
                    warn_and_continue!(CssParseWarnMsgInner::MalformedStructure {
                        message: "Block end without matching block start"
                    });
                }

                // Collect all conditions from the current @-rule stack
                let current_conditions: Vec<DynamicSelector> = at_rule_stack
                    .iter()
                    .flat_map(|(conds, _)| conds.iter().cloned())
                    .collect();

                // Pop @-rule conditions that are at this nesting level
                while let Some((_, level)) = at_rule_stack.last() {
                    if *level >= block_nesting {
                        at_rule_stack.pop();
                    } else {
                        break;
                    }
                }

                block_nesting = block_nesting.saturating_sub(1);

                // Pop from nesting stack if we have one
                if let Some(level) = nesting_stack.pop() {
                    // Emit CSS blocks for all paths at this level
                    if !level.paths.is_empty() && !current_declarations.is_empty() {
                        css_blocks.extend(level.paths.iter().map(|path| UnparsedCssRuleBlock {
                            path: CssPath {
                                selectors: path.clone().into(),
                            },
                            declarations: current_declarations.clone(),
                            conditions: current_conditions.clone(),
                        }));
                    }
                    // Restore parent declarations
                    current_declarations = level.declarations;
                }

                last_path.clear();
                current_paths.clear();
            }
            Token::UniversalSelector => {
                last_path.push(CssPathSelector::Global);
            }
            Token::TypeSelector(div_type) => {
                match NodeTypeTag::from_str(div_type) {
                    Ok(nt) => last_path.push(CssPathSelector::Type(nt)),
                    Err(e) => {
                        warn_and_continue!(CssParseWarnMsgInner::SkippedRule {
                            selector: Some(div_type),
                            error: e.into(),
                        });
                    }
                }
            }
            Token::IdSelector(id) => {
                last_path.push(CssPathSelector::Id(id.to_string().into()));
            }
            Token::ClassSelector(class) => {
                last_path.push(CssPathSelector::Class(class.to_string().into()));
            }
            Token::Combinator(Combinator::GreaterThan) => {
                last_path.push(CssPathSelector::DirectChildren);
            }
            Token::Combinator(Combinator::Space) => {
                last_path.push(CssPathSelector::Children);
            }
            Token::Combinator(Combinator::Plus) => {
                last_path.push(CssPathSelector::AdjacentSibling);
            }
            Token::Combinator(Combinator::Tilde) => {
                last_path.push(CssPathSelector::GeneralSibling);
            }
            Token::PseudoClass { selector, value } | Token::DoublePseudoClass { selector, value } => {
                match pseudo_selector_from_str(selector, value) {
                    Ok(ps) => last_path.push(CssPathSelector::PseudoSelector(ps)),
                    Err(e) => {
                        warn_and_continue!(CssParseWarnMsgInner::SkippedRule {
                            selector: Some(selector),
                            error: e.into(),
                        });
                    }
                }
            }
            Token::AttributeSelector(attr) => {
                if let Some(sel) = parse_attribute_selector(attr) { last_path.push(CssPathSelector::Attribute(sel)) } else { warn_and_continue!(CssParseWarnMsgInner::MalformedStructure {
                    message: "Malformed attribute selector, rule skipped",
                }) }
            }
            Token::Declaration(key, val) => {
                current_declarations.insert(
                    key,
                    (val, ErrorLocationRange { start: last_error_location, end: get_error_location(tokenizer) }),
                );
            }
            Token::EndOfStream => {
                if block_nesting != 0 {
                    warnings.push(CssParseWarnMsg {
                        warning: CssParseWarnMsgInner::MalformedStructure {
                            message: "Unclosed blocks at end of file",
                        },
                        location: ErrorLocationRange { start: last_error_location, end: get_error_location(tokenizer) },
                    });
                }
                break;
            }
            _ => { /* Ignore unsupported tokens */ }
        }

        last_error_location = get_error_location(tokenizer);
    }

    // Process the collected CSS blocks and convert warnings
    let (stylesheet, mut block_warnings) = css_blocks_to_stylesheet(css_blocks, css_string);
    warnings.append(&mut block_warnings);

    (stylesheet, warnings)
}

/// Resolves a parsed `var(--name)` reference (a `CssDeclaration::Dynamic`) against the
/// document-wide custom-property map, producing a concrete `Static` declaration.
///
/// If the referenced custom property is defined, its raw value is parsed as the referenced
/// property's type (taken from the `var()`'s parsed fallback). Otherwise — undefined `var()`
/// or an unparseable value — the fallback (`default_value`) is used, matching the CSS
/// behaviour of an invalid/guaranteed-invalid substitution falling back to the declared
/// default. Non-`Dynamic` declarations pass through unchanged.
fn resolve_var_reference(
    decl: CssDeclaration,
    custom_props: &BTreeMap<String, String>,
) -> CssDeclaration {
    let CssDeclaration::Dynamic(dyn_prop) = decl else {
        return decl;
    };
    // `dynamic_id` is stored without the leading `--`; trim defensively either way.
    let name = dyn_prop.dynamic_id.as_str().trim_start_matches("--");
    if let Some(raw) = custom_props.get(name) {
        if let Ok(parsed) = parse_css_property(dyn_prop.default_value.get_type(), raw) {
            return CssDeclaration::Static(parsed);
        }
    }
    CssDeclaration::Static(dyn_prop.default_value)
}

fn css_blocks_to_stylesheet<'a>(
    css_blocks: Vec<UnparsedCssRuleBlock<'a>>,
    css_string: &'a str,
) -> (Vec<CssRuleBlock>, Vec<CssParseWarnMsg<'a>>) {
    let css_key_map = crate::props::property::get_css_key_map();
    let mut warnings = Vec::new();
    let mut parsed_css_blocks = Vec::new();

    // CSS custom properties (`--name: value`) + `var()` references. The parser already turns
    // `prop: var(--name, fallback)` into a `CssDeclaration::Dynamic`, but nothing consumed it
    // and `--name` definitions were dropped as unknown keys. Resolve them here at parse time:
    // collect every `--name` definition document-wide, then substitute each var() reference
    // with the referenced value (parsed as the target property's type) or its fallback. This
    // is a pragmatic subset of the full cascade — it covers the common `:root { --x: ... }`
    // pattern; element-scoped custom properties (redefined per subtree) are not modelled, which
    // would require cascade-level storage. Keys are stored without the leading `--`.
    let mut custom_props: BTreeMap<String, String> = BTreeMap::new();
    for block in &css_blocks {
        for (key, (value, _)) in &block.declarations {
            if let Some(name) = key.strip_prefix("--") {
                custom_props.insert(name.to_string(), value.trim().to_string());
            }
        }
    }

    for unparsed_css_block in css_blocks {
        let mut declarations = Vec::<CssDeclaration>::new();

        for (unparsed_css_key, (unparsed_css_value, location)) in &unparsed_css_block.declarations {
            // Custom-property DEFINITIONS were collected above; they emit no declaration
            // themselves (and must not warn as unknown keys).
            if unparsed_css_key.starts_with("--") {
                continue;
            }
            match parse_declaration_resilient(
                unparsed_css_key,
                unparsed_css_value,
                *location,
                &css_key_map,
            ) {
                Ok(decls) => {
                    declarations.extend(decls.into_iter().map(|d| resolve_var_reference(d, &custom_props)));
                }
                Err(e) => {
                    warnings.push(CssParseWarnMsg {
                        warning: CssParseWarnMsgInner::SkippedDeclaration {
                            key: unparsed_css_key,
                            value: unparsed_css_value,
                            error: e,
                        },
                        location: *location,
                    });
                }
            }
        }

        parsed_css_blocks.push(CssRuleBlock {
            path: unparsed_css_block.path,
            declarations: declarations.into(),
            conditions: unparsed_css_block.conditions.into(),
            priority: crate::css::rule_priority::AUTHOR,
        });
    }

    (parsed_css_blocks, warnings)
}

fn parse_declaration_resilient<'a>(
    unparsed_css_key: &'a str,
    unparsed_css_value: &'a str,
    location: ErrorLocationRange,
    css_key_map: &CssKeyMap,
) -> Result<Vec<CssDeclaration>, CssParseErrorInner<'a>> {
    let mut declarations = Vec::new();

    if let Some(combined_key) = CombinedCssPropertyType::from_str(unparsed_css_key, css_key_map) {
        if check_if_value_is_css_var(unparsed_css_value).is_some() {
            return Err(CssParseErrorInner::VarOnShorthandProperty {
                key: combined_key,
                value: unparsed_css_value,
            });
        }

        // Attempt to parse combined properties, continue with what succeeds
        match parse_combined_css_property(combined_key, unparsed_css_value) {
            Ok(parsed_props) => {
                declarations.extend(parsed_props.into_iter().map(CssDeclaration::Static));
            }
            Err(e) => return Err(CssParseErrorInner::DynamicCssParseError(e.into())),
        }
    } else if let Some(normal_key) = CssPropertyType::from_str(unparsed_css_key, css_key_map) {
        if let Some(css_var) = check_if_value_is_css_var(unparsed_css_value) {
            let (css_var_id, css_var_default) = css_var?;
            match parse_css_property(normal_key, css_var_default) {
                Ok(parsed_default) => {
                    declarations.push(CssDeclaration::Dynamic(DynamicCssProperty {
                        dynamic_id: css_var_id.to_string().into(),
                        default_value: parsed_default,
                    }));
                }
                Err(e) => return Err(CssParseErrorInner::DynamicCssParseError(e.into())),
            }
        } else {
            match parse_css_property(normal_key, unparsed_css_value) {
                Ok(parsed_value) => {
                    declarations.push(CssDeclaration::Static(parsed_value));
                }
                Err(e) => return Err(CssParseErrorInner::DynamicCssParseError(e.into())),
            }
        }
    } else {
        return Err(CssParseErrorInner::UnknownPropertyKey(
            unparsed_css_key,
            unparsed_css_value,
        ));
    }

    Ok(declarations)
}

/// Parses a single CSS key-value declaration, appending results to `declarations`.
///
/// Unknown property keys are downgraded to warnings (pushed into `warnings`)
/// rather than causing a hard error, so callers can continue processing the
/// remaining declarations in a rule block.
/// # Errors
///
/// Returns an error if `input` is not a valid CSS `css-declaration` value.
pub fn parse_css_declaration<'a>(
    unparsed_css_key: &'a str,
    unparsed_css_value: &'a str,
    location: ErrorLocationRange,
    css_key_map: &CssKeyMap,
    warnings: &mut Vec<CssParseWarnMsg<'a>>,
    declarations: &mut Vec<CssDeclaration>,
) -> Result<(), CssParseErrorInner<'a>> {
    match parse_declaration_resilient(unparsed_css_key, unparsed_css_value, location, css_key_map) {
        Ok(mut decls) => {
            declarations.append(&mut decls);
            Ok(())
        }
        Err(e) => {
            if let CssParseErrorInner::UnknownPropertyKey(key, val) = &e {
                warnings.push(CssParseWarnMsg {
                    warning: CssParseWarnMsgInner::UnsupportedKeyValuePair { key, value: val },
                    location,
                });
                Ok(()) // Continue processing despite unknown property
            } else {
                Err(e) // Propagate other errors
            }
        }
    }
}

fn check_if_value_is_css_var(
    unparsed_css_value: &str,
) -> Option<Result<(&str, &str), CssParseErrorInner<'_>>> {
    const DEFAULT_VARIABLE_DEFAULT: &str = "none";

    let (_, brace_contents) = parse_parentheses(unparsed_css_value, &["var"]).ok()?;

    // value is a CSS variable, i.e. var(--main-bg-color)
    Some(match parse_css_variable_brace_contents(brace_contents) {
        Some((variable_id, default_value)) => Ok((
            variable_id,
            default_value.unwrap_or(DEFAULT_VARIABLE_DEFAULT),
        )),
        None => Err(DynamicCssParseError::InvalidBraceContents(brace_contents).into()),
    })
}

/// Parses the brace contents of a css var, i.e.:
///
/// ```no_run,ignore
/// "--main-bg-col, blue" => (Some("main-bg-col"), Some("blue"))
/// "--main-bg-col"       => (Some("main-bg-col"), None)
/// ```
fn parse_css_variable_brace_contents(input: &str) -> Option<(&str, Option<&str>)> {
    let input = input.trim();

    let mut split_comma_iter = input.splitn(2, ',');
    let var_name = split_comma_iter.next()?;
    let var_name = var_name.trim();

    if !var_name.starts_with("--") {
        return None; // no proper CSS variable name
    }

    Some((&var_name[2..], split_comma_iter.next()))
}

#[cfg(test)]
#[allow(
    clippy::all,
    clippy::pedantic,
    clippy::nursery,
    unused_qualifications,
    single_use_lifetimes
)]
mod autotest_generated {
    use super::*;
    use crate::css::CssNthChildPattern;

    // ---------------------------------------------------------------------
    // helpers
    // ---------------------------------------------------------------------

    /// Runs `f`, converting a panic into `Err(message)` so that a *panicking*
    /// function under test produces a readable assertion failure instead of
    /// tearing down the test binary. `[profile.test] panic = "unwind"` is set
    /// in the workspace root `Cargo.toml`, so unwinding is available here.
    fn catch<R>(f: impl FnOnce() -> R) -> Result<R, String> {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|e| {
            e.downcast_ref::<String>().cloned().unwrap_or_else(|| {
                e.downcast_ref::<&str>()
                    .map_or_else(|| "<non-string panic payload>".to_string(), |s| (*s).to_string())
            })
        })
    }

    fn key_map() -> CssKeyMap {
        crate::props::property::get_css_key_map()
    }

    fn loc(start: usize, end: usize) -> ErrorLocationRange {
        ErrorLocationRange {
            start: ErrorLocation { original_pos: start },
            end: ErrorLocation { original_pos: end },
        }
    }

    /// A grab-bag of hostile inputs reused across the string parsers.
    const HOSTILE: &[&str] = &[
        "",
        " ",
        "   \t\n\r  ",
        "\0",
        "\u{1F600}",
        "e\u{301}\u{301}\u{301}",
        "-0",
        "0",
        "NaN",
        "inf",
        "-inf",
        "9223372036854775807",
        "-9223372036854775808",
        "18446744073709551616",
        "1e309",
        ";",
        "{}",
        "()",
        "((((",
        "))))",
        "\"",
        "'",
        "\\",
        "//",
        "/*",
        "valid;garbage",
        "  valid  ",
        "a=b=c",
        ":::",
        "--",
    ];

    // =====================================================================
    // parsers -> malformed / huge / boundary / unicode
    // =====================================================================

    // --- pseudo_selector_from_str ----------------------------------------

    #[test]
    fn pseudo_selector_from_str_valid_minimal() {
        assert_eq!(
            pseudo_selector_from_str("hover", None),
            Ok(CssPathPseudoSelector::Hover)
        );
        assert_eq!(
            pseudo_selector_from_str("first", None),
            Ok(CssPathPseudoSelector::First)
        );
        assert_eq!(
            pseudo_selector_from_str("last", None),
            Ok(CssPathPseudoSelector::Last)
        );
        assert_eq!(
            pseudo_selector_from_str("active", None),
            Ok(CssPathPseudoSelector::Active)
        );
        assert_eq!(
            pseudo_selector_from_str("focus", None),
            Ok(CssPathPseudoSelector::Focus)
        );
        assert_eq!(
            pseudo_selector_from_str("dragging", None),
            Ok(CssPathPseudoSelector::Dragging)
        );
        assert_eq!(
            pseudo_selector_from_str("drag-over", None),
            Ok(CssPathPseudoSelector::DragOver)
        );
        assert_eq!(
            pseudo_selector_from_str("root", None),
            Ok(CssPathPseudoSelector::Root)
        );
    }

    #[test]
    fn pseudo_selector_from_str_nth_child_needs_a_value() {
        assert_eq!(
            pseudo_selector_from_str("nth-child", None),
            Err(CssPseudoSelectorParseError::EmptyNthChild)
        );
        assert_eq!(
            pseudo_selector_from_str("nth-child", Some("2")),
            Ok(CssPathPseudoSelector::NthChild(CssNthChildSelector::Number(2)))
        );
    }

    #[test]
    fn pseudo_selector_from_str_lang_strips_quotes() {
        // Both quote styles are stripped, and the inner value is trimmed.
        for v in ["de-DE", "\"de-DE\"", "'de-DE'", "  \"de-DE\"  "] {
            assert_eq!(
                pseudo_selector_from_str("lang", Some(v)),
                Ok(CssPathPseudoSelector::Lang(AzString::from("de-DE".to_string()))),
                "lang value {v:?} did not normalise to de-DE"
            );
        }
        // A `:lang` with no value is rejected rather than defaulting to "".
        assert!(pseudo_selector_from_str("lang", None).is_err());
    }

    #[test]
    fn pseudo_selector_from_str_empty_and_whitespace_are_rejected() {
        assert!(pseudo_selector_from_str("", None).is_err());
        assert!(pseudo_selector_from_str("   ", None).is_err());
        assert!(pseudo_selector_from_str("\t\n", None).is_err());
        // The selector name is matched verbatim, so a padded name is *not* accepted.
        assert!(pseudo_selector_from_str(" hover ", None).is_err());
    }

    #[test]
    fn pseudo_selector_from_str_garbage_and_unicode_never_panic() {
        for s in HOSTILE {
            for v in [None, Some(*s), Some("2"), Some("\u{1F600}")] {
                let r = catch(|| pseudo_selector_from_str(s, v));
                assert!(
                    r.is_ok(),
                    "pseudo_selector_from_str({s:?}, {v:?}) panicked: {}",
                    r.unwrap_err()
                );
                // Nothing in HOSTILE is a real pseudo-selector name.
                assert!(
                    pseudo_selector_from_str(s, v).is_err(),
                    "pseudo_selector_from_str({s:?}, {v:?}) unexpectedly succeeded"
                );
            }
        }
    }

    #[test]
    fn pseudo_selector_from_str_extremely_long_input_terminates() {
        let long = "z".repeat(200_000);
        assert!(pseudo_selector_from_str(&long, None).is_err());
        // A huge *value* on a selector that ignores values must also terminate.
        assert_eq!(
            pseudo_selector_from_str("hover", Some(&long)),
            Ok(CssPathPseudoSelector::Hover)
        );
        // A huge nth-child value is rejected, not parsed into a bogus number.
        assert!(pseudo_selector_from_str("nth-child", Some(&long)).is_err());
    }

    #[test]
    fn pseudo_selector_from_str_deeply_nested_value_does_not_stack_overflow() {
        let nested = "(".repeat(10_000);
        let r = catch(|| pseudo_selector_from_str("nth-child", Some(&nested)).is_err());
        assert_eq!(r, Ok(true), "deeply nested nth-child value was not rejected safely");
    }

    // --- parse_attribute_selector ----------------------------------------

    #[test]
    fn parse_attribute_selector_valid_minimal() {
        let sel = parse_attribute_selector("href").expect("bare attribute name must parse");
        assert_eq!(sel.name.as_str(), "href");
        assert_eq!(sel.op, AttributeMatchOp::Exists);
        assert_eq!(sel.value.clone().into_option(), None);
    }

    #[test]
    fn parse_attribute_selector_all_operators() {
        let cases: [(&str, AttributeMatchOp); 6] = [
            ("a=b", AttributeMatchOp::Eq),
            ("a~=b", AttributeMatchOp::Includes),
            ("a|=b", AttributeMatchOp::DashMatch),
            ("a^=b", AttributeMatchOp::Prefix),
            ("a$=b", AttributeMatchOp::Suffix),
            ("a*=b", AttributeMatchOp::Substring),
        ];
        for (input, expected_op) in cases {
            let sel = parse_attribute_selector(input)
                .unwrap_or_else(|| panic!("{input:?} should parse"));
            assert_eq!(sel.name.as_str(), "a", "wrong name for {input:?}");
            assert_eq!(sel.op, expected_op, "wrong op for {input:?}");
            assert_eq!(
                sel.value.clone().into_option().map(|v| v.as_str().to_string()),
                Some("b".to_string()),
                "wrong value for {input:?}"
            );
        }
    }

    #[test]
    fn parse_attribute_selector_quotes_are_stripped_and_unbalanced_rejected() {
        for input in ["a=\"b\"", "a='b'", "a=b", "  a  =  \"b\"  "] {
            let sel = parse_attribute_selector(input)
                .unwrap_or_else(|| panic!("{input:?} should parse"));
            assert_eq!(
                sel.value.clone().into_option().map(|v| v.as_str().to_string()),
                Some("b".to_string()),
                "quotes not stripped for {input:?}"
            );
        }
        // Unbalanced quoting is a hard reject, not a silent half-strip.
        for input in ["a=\"b", "a=b\"", "a='b", "a=b'", "a=\"b'", "a=\"", "a='"] {
            assert!(
                parse_attribute_selector(input).is_none(),
                "unbalanced quote {input:?} should be rejected"
            );
        }
    }

    #[test]
    fn parse_attribute_selector_empty_and_malformed_are_rejected() {
        for input in ["", "   ", "\t\n", "=", "=b", "  =b", "\"a\"", "'a'"] {
            assert!(
                parse_attribute_selector(input).is_none(),
                "{input:?} should be rejected (empty/quoted name)"
            );
        }
        // Names may not contain whitespace.
        assert!(parse_attribute_selector("a b").is_none());
        assert!(parse_attribute_selector("a b=c").is_none());
    }

    #[test]
    fn parse_attribute_selector_unicode_name_is_accepted_and_does_not_panic() {
        let sel = parse_attribute_selector("data-\u{1F600}")
            .expect("a non-ASCII attribute name has no whitespace/quotes, so it is accepted");
        assert_eq!(sel.name.as_str(), "data-\u{1F600}");

        // Multi-byte values must not be sliced mid-char.
        let sel = parse_attribute_selector("lang=\"\u{4E2D}\u{6587}\"").expect("unicode value");
        assert_eq!(
            sel.value.clone().into_option().map(|v| v.as_str().to_string()),
            Some("\u{4E2D}\u{6587}".to_string())
        );
    }

    /// Invariant: whatever comes back, the name is never empty and never contains
    /// whitespace or quotes -- those are exactly the cases the parser promises to
    /// reject. This holds regardless of how the operator split is implemented.
    #[test]
    fn parse_attribute_selector_result_invariants_hold_for_hostile_input() {
        let long = format!("a={}", "x".repeat(100_000));
        let nested = format!("a={}", "[".repeat(10_000));
        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&long);
        inputs.push(&nested);
        inputs.push("title=\"a~=b\"");
        inputs.push("a=b=c");
        inputs.push("[[[[]]]]");

        for input in inputs {
            let parsed = match catch(|| parse_attribute_selector(input)) {
                Ok(p) => p,
                Err(msg) => panic!("parse_attribute_selector({input:?}) panicked: {msg}"),
            };
            if let Some(sel) = parsed {
                let name = sel.name.as_str();
                assert!(!name.is_empty(), "empty name accepted for {input:?}");
                assert!(
                    !name.chars().any(|c| c.is_whitespace() || c == '"' || c == '\''),
                    "name {name:?} contains whitespace/quotes for input {input:?}"
                );
            }
        }
    }

    // --- strip_attribute_quotes (private) --------------------------------

    #[test]
    fn strip_attribute_quotes_balanced_unquoted_and_unbalanced() {
        // Balanced -> stripped.
        assert_eq!(strip_attribute_quotes("\"abc\""), Some("abc"));
        assert_eq!(strip_attribute_quotes("'abc'"), Some("abc"));
        assert_eq!(strip_attribute_quotes("\"\""), Some(""));
        assert_eq!(strip_attribute_quotes("''"), Some(""));
        // Unquoted -> unchanged.
        assert_eq!(strip_attribute_quotes("abc"), Some("abc"));
        assert_eq!(strip_attribute_quotes(""), Some(""));
        assert_eq!(strip_attribute_quotes("a"), Some("a"));
        // Unbalanced -> None.
        assert_eq!(strip_attribute_quotes("\"abc"), None);
        assert_eq!(strip_attribute_quotes("abc\""), None);
        assert_eq!(strip_attribute_quotes("'abc"), None);
        assert_eq!(strip_attribute_quotes("abc'"), None);
        assert_eq!(strip_attribute_quotes("\"abc'"), None);
        assert_eq!(strip_attribute_quotes("\""), None);
        assert_eq!(strip_attribute_quotes("'"), None);
    }

    /// The function slices with raw byte indices (`&s[1..s.len() - 1]`), so a
    /// multi-byte first/last char is the interesting boundary case. No byte of a
    /// multi-byte UTF-8 sequence can equal `"` (0x22) or `'` (0x27), so the slice
    /// must always land on a char boundary.
    #[test]
    fn strip_attribute_quotes_multibyte_boundaries_never_panic() {
        let cases = [
            "\u{1F600}",
            "\"\u{1F600}\"",
            "'\u{4E2D}\u{6587}'",
            "\u{4E2D}\u{6587}",
            "\"\u{301}\"",
            "\u{301}",
        ];
        for s in cases {
            let r = catch(|| strip_attribute_quotes(s));
            assert!(r.is_ok(), "strip_attribute_quotes({s:?}) panicked: {}", r.unwrap_err());
        }
        assert_eq!(strip_attribute_quotes("\"\u{1F600}\""), Some("\u{1F600}"));
        assert_eq!(strip_attribute_quotes("\u{1F600}"), Some("\u{1F600}"));
    }

    #[test]
    fn strip_attribute_quotes_extremely_long_input_terminates() {
        let long = "x".repeat(500_000);
        assert_eq!(strip_attribute_quotes(&long), Some(long.as_str()));
        let quoted = format!("\"{long}\"");
        assert_eq!(strip_attribute_quotes(&quoted), Some(long.as_str()));
    }

    // --- parse_nth_child_selector / parse_nth_child_pattern (private) -----

    #[test]
    fn parse_nth_child_selector_valid_minimal() {
        assert_eq!(parse_nth_child_selector("2"), Ok(CssNthChildSelector::Number(2)));
        assert_eq!(parse_nth_child_selector("0"), Ok(CssNthChildSelector::Number(0)));
        assert_eq!(parse_nth_child_selector("even"), Ok(CssNthChildSelector::Even));
        assert_eq!(parse_nth_child_selector("odd"), Ok(CssNthChildSelector::Odd));
        assert_eq!(parse_nth_child_selector("  7  "), Ok(CssNthChildSelector::Number(7)));
        assert_eq!(
            parse_nth_child_selector("2n+3"),
            Ok(CssNthChildSelector::Pattern(CssNthChildPattern {
                pattern_repeat: 2,
                offset: 3
            }))
        );
        assert_eq!(
            parse_nth_child_selector("2n"),
            Ok(CssNthChildSelector::Pattern(CssNthChildPattern {
                pattern_repeat: 2,
                offset: 0
            }))
        );
    }

    #[test]
    fn parse_nth_child_selector_empty_is_empty_nth_child_error() {
        assert_eq!(
            parse_nth_child_selector(""),
            Err(CssPseudoSelectorParseError::EmptyNthChild)
        );
        assert_eq!(
            parse_nth_child_selector("   \t\n "),
            Err(CssPseudoSelectorParseError::EmptyNthChild)
        );
        assert_eq!(
            parse_nth_child_pattern(""),
            Err(CssPseudoSelectorParseError::EmptyNthChild)
        );
    }

    /// `u32` boundaries: MAX parses, MAX+1 and negatives are rejected via
    /// `ParseIntError` rather than wrapping or panicking.
    #[test]
    fn parse_nth_child_selector_numeric_limits_saturate_into_errors() {
        assert_eq!(
            parse_nth_child_selector("4294967295"),
            Ok(CssNthChildSelector::Number(u32::MAX))
        );
        for overflow in [
            "4294967296",
            "18446744073709551616",
            "99999999999999999999999999",
            "-1",
            "-0",
        ] {
            assert!(
                parse_nth_child_selector(overflow).is_err(),
                "{overflow:?} must not parse as an nth-child index"
            );
        }
        // Huge digit runs must be rejected, not truncated -- and must terminate.
        let huge = "9".repeat(100_000);
        assert!(parse_nth_child_selector(&huge).is_err());
        let huge_repeat = format!("{}n+1", "9".repeat(100_000));
        assert!(parse_nth_child_pattern(&huge_repeat).is_err());
    }

    #[test]
    fn parse_nth_child_selector_float_and_non_finite_strings_are_rejected() {
        for v in ["NaN", "inf", "-inf", "1.5", "1e5", "0x2", "+2", " 2 n "] {
            let r = catch(|| parse_nth_child_selector(v));
            assert!(r.is_ok(), "parse_nth_child_selector({v:?}) panicked: {}", r.unwrap_err());
        }
        assert!(parse_nth_child_selector("NaN").is_err());
        assert!(parse_nth_child_selector("inf").is_err());
        assert!(parse_nth_child_selector("1.5").is_err());
    }

    #[test]
    fn parse_nth_child_pattern_malformed_offsets_are_rejected() {
        // Trailing "+" with no offset.
        assert_eq!(
            parse_nth_child_pattern("2n+"),
            Err(CssPseudoSelectorParseError::InvalidNthChildPattern("2n+"))
        );
        assert!(parse_nth_child_pattern("2n+   ").is_err());
        assert!(parse_nth_child_pattern("2n+x").is_err());
        assert!(parse_nth_child_pattern("xn+1").is_err());
        // The `.split('n').next()` / `.split('+').next().unwrap()` pair must never
        // panic, no matter what the input looks like.
        for s in HOSTILE {
            let r = catch(|| parse_nth_child_pattern(s));
            assert!(r.is_ok(), "parse_nth_child_pattern({s:?}) panicked: {}", r.unwrap_err());
        }
    }

    #[test]
    fn parse_nth_child_selector_unicode_never_panics() {
        for v in ["\u{1F600}", "\u{FF12}", "2\u{301}", "e\u{301}ven", "\u{4E2D}n+\u{6587}"] {
            let r = catch(|| parse_nth_child_selector(v));
            assert!(r.is_ok(), "parse_nth_child_selector({v:?}) panicked: {}", r.unwrap_err());
            assert!(
                parse_nth_child_selector(v).is_err(),
                "{v:?} is not a valid nth-child value"
            );
        }
    }

    // --- parse_css_path ---------------------------------------------------

    #[test]
    fn parse_css_path_valid_minimal() {
        // Positive control, mirrors the doc example on `parse_css_path`.
        assert_eq!(
            parse_css_path("* div #my_id > .class:nth-child(2)"),
            Ok(CssPath {
                selectors: vec![
                    CssPathSelector::Global,
                    CssPathSelector::Type(NodeTypeTag::from_str("div").unwrap()),
                    CssPathSelector::Children,
                    CssPathSelector::Id("my_id".to_string().into()),
                    CssPathSelector::DirectChildren,
                    CssPathSelector::Class("class".to_string().into()),
                    CssPathSelector::PseudoSelector(CssPathPseudoSelector::NthChild(
                        CssNthChildSelector::Number(2)
                    )),
                ]
                .into()
            })
        );
        assert_eq!(
            parse_css_path("div"),
            Ok(CssPath {
                selectors: vec![CssPathSelector::Type(NodeTypeTag::from_str("div").unwrap())]
                    .into()
            })
        );
    }

    #[test]
    fn parse_css_path_empty_and_whitespace_are_empty_path_errors() {
        assert_eq!(parse_css_path(""), Err(CssPathParseError::EmptyPath));
        assert_eq!(parse_css_path("   "), Err(CssPathParseError::EmptyPath));
        assert_eq!(parse_css_path("\t\r\n "), Err(CssPathParseError::EmptyPath));
        // An unknown type tag is now a hard error (Selectors L4: an invalid simple
        // selector invalidates the selector) rather than being silently dropped into an
        // empty path. See parse_css_path_unknown_type_tag_is_not_silently_dropped.
        assert!(matches!(
            parse_css_path("definitelynotatag"),
            Err(CssPathParseError::NodeTypeTag(_))
        ));
    }

    #[test]
    fn parse_css_path_garbage_and_unicode_never_panic() {
        let long = "div ".repeat(50_000);
        let brackets = "[".repeat(10_000);
        let braces = "{".repeat(10_000);
        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&long);
        inputs.push(&brackets);
        inputs.push(&braces);
        inputs.push("div;garbage");
        inputs.push("div }");
        inputs.push(":::::");
        inputs.push("\u{1F600} > \u{4E2D}\u{6587}");

        for input in inputs {
            let r = catch(|| parse_css_path(input));
            assert!(r.is_ok(), "parse_css_path({:.40?}) panicked: {}", input, r.unwrap_err());
        }
    }

    #[test]
    fn parse_css_path_rejects_block_tokens() {
        // `{` / `}` are not path tokens; they must not silently produce a path.
        for input in ["div { }", "div {", "}"] {
            assert!(
                parse_css_path(input).is_err(),
                "{input:?} contains block tokens and must not parse as a path"
            );
        }
    }

    #[test]
    fn parse_css_path_unknown_pseudo_selector_is_an_error() {
        assert!(parse_css_path("div:definitelynotapseudo").is_err());
        assert!(parse_css_path(".x:nth-child(notanumber)").is_err());
    }

    /// BUG (red): `parse_css_path` swallows an unknown type selector
    /// (`if let Ok(nt) = NodeTypeTag::from_str(..)` with no `else`), so
    /// `"div definitelynotatag"` parses as `[Type(Div), Children]` -- a path that
    /// ends in a dangling descendant combinator and therefore matches *every*
    /// descendant of `div`, silently widening the selector. It should either be
    /// rejected (like `new_from_str_inner`, which emits a `SkippedRule` warning)
    /// or not leave a trailing combinator behind.
    #[test]
    fn parse_css_path_unknown_type_tag_is_not_silently_dropped() {
        let parsed = parse_css_path("div definitelynotatag");
        if let Ok(path) = &parsed {
            let selectors = path.selectors.as_slice();
            assert!(
                !matches!(
                    selectors.last(),
                    Some(
                        CssPathSelector::Children
                            | CssPathSelector::DirectChildren
                            | CssPathSelector::AdjacentSibling
                            | CssPathSelector::GeneralSibling
                    )
                ),
                "BUG: the unknown type tag was dropped, leaving a dangling combinator; \
                 `div definitelynotatag` now matches every descendant of div. \
                 selectors = {selectors:?}"
            );
        }
    }

    // --- parse_media_conditions / parse_media_feature ---------------------

    #[test]
    fn parse_media_conditions_valid_minimal() {
        assert_eq!(
            parse_media_conditions("screen"),
            vec![DynamicSelector::Media(MediaType::Screen)]
        );
        assert_eq!(
            parse_media_conditions("PRINT"),
            vec![DynamicSelector::Media(MediaType::Print)]
        );
        assert_eq!(
            parse_media_conditions("all"),
            vec![DynamicSelector::Media(MediaType::All)]
        );
    }

    #[test]
    fn parse_media_conditions_parenthesised_and_compound() {
        let conds = parse_media_conditions("(min-width: 800px)");
        assert_eq!(conds.len(), 1);
        match &conds[0] {
            DynamicSelector::ViewportWidth(r) => {
                assert_eq!(r.min(), Some(800.0));
                assert_eq!(r.max(), None);
            }
            other => panic!("expected ViewportWidth, got {other:?}"),
        }

        let conds = parse_media_conditions("screen and (max-width: 600px)");
        assert_eq!(conds.len(), 2, "compound query should yield both conditions");
        assert_eq!(conds[0], DynamicSelector::Media(MediaType::Screen));
        match &conds[1] {
            DynamicSelector::ViewportWidth(r) => {
                assert_eq!(r.min(), None);
                assert_eq!(r.max(), Some(600.0));
            }
            other => panic!("expected ViewportWidth, got {other:?}"),
        }
    }

    #[test]
    fn parse_media_conditions_empty_and_garbage_yield_no_conditions() {
        for input in ["", "   ", "((((", "))))", "\u{1F600}", "and", "(", ")", "()"] {
            let r = catch(|| parse_media_conditions(input));
            match r {
                Ok(conds) => assert!(
                    conds.is_empty(),
                    "{input:?} should not produce media conditions, got {conds:?}"
                ),
                Err(msg) => panic!("parse_media_conditions({input:?}) panicked: {msg}"),
            }
        }
    }

    #[test]
    fn parse_media_conditions_extremely_long_and_deeply_nested_terminate() {
        let nested = format!("({})", "(".repeat(10_000));
        let r = catch(|| parse_media_conditions(&nested));
        assert!(r.is_ok(), "deeply nested media query panicked: {}", r.unwrap_err());

        let long = "screen and ".repeat(20_000);
        let r = catch(|| parse_media_conditions(&long));
        assert!(r.is_ok(), "very long media query panicked: {}", r.unwrap_err());
    }

    #[test]
    fn parse_media_feature_known_features() {
        assert_eq!(
            parse_media_feature("orientation: portrait"),
            Some(DynamicSelector::Orientation(OrientationType::Portrait))
        );
        assert_eq!(
            parse_media_feature("orientation: LANDSCAPE"),
            Some(DynamicSelector::Orientation(OrientationType::Landscape))
        );
        assert_eq!(
            parse_media_feature("prefers-color-scheme: dark"),
            Some(DynamicSelector::Theme(ThemeCondition::Dark))
        );
        assert_eq!(
            parse_media_feature("prefers-reduced-motion: reduce"),
            Some(DynamicSelector::PrefersReducedMotion(BoolCondition::True))
        );
        assert_eq!(
            parse_media_feature("prefers-contrast: more"),
            Some(DynamicSelector::PrefersHighContrast(BoolCondition::True))
        );
        // Keys are matched case-insensitively.
        assert!(parse_media_feature("MIN-WIDTH: 800px").is_some());
    }

    #[test]
    fn parse_media_feature_malformed_returns_none() {
        for input in [
            "",
            "   ",
            "nocolon",
            "min-width:",
            "min-width: ",
            "min-width: abc",
            ": 800px",
            "unknown-feature: 800px",
            "orientation: sideways",
            "\u{1F600}: \u{1F600}",
        ] {
            let r = catch(|| parse_media_feature(input));
            match r {
                Ok(v) => assert!(v.is_none(), "{input:?} should be rejected, got {v:?}"),
                Err(msg) => panic!("parse_media_feature({input:?}) panicked: {msg}"),
            }
        }
    }

    /// BUG (red): `MinMaxRange` uses `f32::NAN` as its "no bound" sentinel, and
    /// `parse_px_value` happily parses `"NaN"` (Rust's `f32::from_str` accepts it).
    /// So `@media (min-width: NaN)` produces a `ViewportWidth` whose `min()` is
    /// `None` -- a viewport constraint that constrains nothing and therefore
    /// matches *every* viewport, instead of the media query being rejected.
    #[test]
    fn parse_media_feature_nan_width_does_not_erase_the_constraint() {
        for feature in ["min-width: NaN", "min-width: NaNpx", "max-width: nan"] {
            match parse_media_feature(feature) {
                None => {} // acceptable: the feature was rejected outright
                Some(DynamicSelector::ViewportWidth(r)) => {
                    assert!(
                        r.min().is_some() || r.max().is_some(),
                        "BUG: {feature:?} parsed into a ViewportWidth with no bounds at all \
                         (the NaN collided with MinMaxRange's `absent` sentinel), so the \
                         media query silently matches every viewport"
                    );
                }
                Some(other) => panic!("unexpected selector for {feature:?}: {other:?}"),
            }
        }
    }

    // --- parse_px_value ---------------------------------------------------

    #[test]
    fn parse_px_value_valid_minimal() {
        assert_eq!(parse_px_value("800px"), Some(800.0));
        assert_eq!(parse_px_value("800"), Some(800.0));
        assert_eq!(parse_px_value("  800px  "), Some(800.0));
        assert_eq!(parse_px_value("0"), Some(0.0));
        assert_eq!(parse_px_value("1.5px"), Some(1.5));
        assert_eq!(parse_px_value("-10px"), Some(-10.0));
    }

    #[test]
    fn parse_px_value_malformed_returns_none() {
        for input in ["", "   ", "px", "abc", "8 0 0", "800pxx", "\u{1F600}", "800%", "--"] {
            let r = catch(|| parse_px_value(input));
            match r {
                Ok(v) => assert!(v.is_none(), "{input:?} should be rejected, got {v:?}"),
                Err(msg) => panic!("parse_px_value({input:?}) panicked: {msg}"),
            }
        }
    }

    /// f32 range boundaries: overflow saturates to +/-inf and underflow to zero
    /// (that is `f32::from_str`'s documented behaviour) -- neither may panic.
    #[test]
    fn parse_px_value_overflow_and_underflow_saturate_without_panicking() {
        assert_eq!(parse_px_value("-0"), Some(-0.0));
        assert_eq!(parse_px_value("1e-50"), Some(0.0));
        assert_eq!(parse_px_value("3.4e38px"), Some(3.4e38));

        // FIXED: parse_px_value now rejects non-finite results (see
        // parse_px_value_rejects_non_finite_values). "1e39" is valid CSS number
        // *syntax* but overflows f32 to infinity, and an infinite length is exactly
        // the non-finite value that would collide with MinMaxRange's NaN "no bound"
        // sentinel — so it is rejected rather than saturated. (Was: Some(inf).)
        assert_eq!(parse_px_value("1e39px"), None);

        let huge_digits = "9".repeat(100_000);
        let r = catch(|| parse_px_value(&huge_digits));
        assert!(r.is_ok(), "a 100k-digit number panicked: {}", r.unwrap_err());
    }

    /// BUG (red): `f32::from_str` accepts `"NaN"`, `"inf"` and `"infinity"`, none of
    /// which are valid CSS `<length>` values. Because `MinMaxRange` encodes "no
    /// bound" as `NaN`, letting a NaN through silently turns a constraint into a
    /// wildcard (see `parse_media_feature_nan_width_does_not_erase_the_constraint`).
    /// `parse_px_value` should reject non-finite values at the source.
    #[test]
    fn parse_px_value_rejects_non_finite_values() {
        for input in ["NaN", "nan", "inf", "-inf", "infinity", "NaNpx", "infpx", "-infpx"] {
            if let Some(px) = parse_px_value(input) {
                assert!(
                    px.is_finite(),
                    "BUG: parse_px_value({input:?}) returned the non-finite value {px}; \
                     a non-finite length is not valid CSS and collides with MinMaxRange's \
                     NaN `absent` sentinel"
                );
            }
        }
    }

    // --- parse_ratio_value ------------------------------------------------

    #[test]
    fn parse_ratio_value_valid_minimal() {
        let r = parse_ratio_value("16/9").expect("16/9 should parse");
        assert!((r - (16.0 / 9.0)).abs() < 1e-6, "16/9 parsed as {r}");
        let r = parse_ratio_value("1.777").expect("bare float should parse");
        assert!((r - 1.777).abs() < 1e-6);
        let r = parse_ratio_value("  16 / 9  ").expect("whitespace should be trimmed");
        assert!((r - (16.0 / 9.0)).abs() < 1e-6);
    }

    #[test]
    fn parse_ratio_value_division_by_zero_is_rejected() {
        // Both +0.0 and -0.0 denominators must be caught by the `den == 0.0` guard.
        assert_eq!(parse_ratio_value("1/0"), None);
        assert_eq!(parse_ratio_value("1/-0"), None);
        assert_eq!(parse_ratio_value("0/0"), None);
        assert_eq!(parse_ratio_value("16/0.0"), None);
    }

    #[test]
    fn parse_ratio_value_malformed_returns_none() {
        for input in ["", "   ", "/", "16/", "/9", "a/b", "1/2/3", "\u{1F600}", "16:9"] {
            let r = catch(|| parse_ratio_value(input));
            match r {
                Ok(v) => assert!(v.is_none(), "{input:?} should be rejected, got {v:?}"),
                Err(msg) => panic!("parse_ratio_value({input:?}) panicked: {msg}"),
            }
        }
    }

    /// BUG (red): the `den == 0.0` guard catches division by zero but not the
    /// non-finite operands that produce NaN anyway -- `inf/inf` and `1/NaN` both
    /// yield NaN, which then becomes MinMaxRange's "no bound" sentinel and turns
    /// an `aspect-ratio` query into a wildcard.
    #[test]
    fn parse_ratio_value_never_returns_nan() {
        for input in ["NaN", "inf/inf", "NaN/1", "1/NaN", "-inf/inf", "inf/-inf"] {
            if let Some(r) = parse_ratio_value(input) {
                assert!(
                    !r.is_nan(),
                    "BUG: parse_ratio_value({input:?}) returned NaN, which MinMaxRange \
                     reads back as `no bound` -- the aspect-ratio query silently matches \
                     everything"
                );
            }
        }
    }

    #[test]
    fn parse_ratio_value_extremely_long_input_terminates() {
        let huge = format!("{}/{}", "9".repeat(50_000), "9".repeat(50_000));
        let r = catch(|| parse_ratio_value(&huge));
        assert!(r.is_ok(), "huge ratio panicked: {}", r.unwrap_err());
    }

    // --- parse_container_conditions / parse_container_feature -------------

    #[test]
    fn parse_container_conditions_valid_minimal() {
        // Bare name.
        assert_eq!(
            parse_container_conditions("sidebar"),
            vec![DynamicSelector::ContainerName(AzString::from(
                "sidebar".to_string()
            ))]
        );

        // Anonymous query.
        let conds = parse_container_conditions("(min-width: 400px)");
        assert_eq!(conds.len(), 1);
        match &conds[0] {
            DynamicSelector::ContainerWidth(r) => {
                assert_eq!(r.min(), Some(400.0));
                assert_eq!(r.max(), None);
            }
            other => panic!("expected ContainerWidth, got {other:?}"),
        }

        // Named query -> name + condition.
        let conds = parse_container_conditions("sidebar (min-width: 400px)");
        assert_eq!(conds.len(), 2);
        assert_eq!(
            conds[0],
            DynamicSelector::ContainerName(AzString::from("sidebar".to_string()))
        );
        assert!(matches!(conds[1], DynamicSelector::ContainerWidth(_)));
    }

    #[test]
    fn parse_container_conditions_empty_and_garbage_never_panic() {
        assert!(parse_container_conditions("").is_empty());
        assert!(parse_container_conditions("   ").is_empty());

        let nested = "(".repeat(10_000);
        let long = "a".repeat(200_000);
        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&nested);
        inputs.push(&long);

        for input in inputs {
            let r = catch(|| parse_container_conditions(input));
            assert!(
                r.is_ok(),
                "parse_container_conditions({:.40?}) panicked: {}",
                input,
                r.unwrap_err()
            );
        }
    }

    #[test]
    fn parse_container_feature_malformed_returns_none() {
        for input in ["", "   ", "nocolon", "min-width:", "min-width: abc", "unknown: 1px"] {
            let r = catch(|| parse_container_feature(input));
            match r {
                Ok(v) => assert!(v.is_none(), "{input:?} should be rejected, got {v:?}"),
                Err(msg) => panic!("parse_container_feature({input:?}) panicked: {msg}"),
            }
        }
        assert!(parse_container_feature("min-height: 400px").is_some());
        assert!(parse_container_feature("MAX-WIDTH: 400px").is_some());
    }

    // --- parse_theme_condition / parse_lang_condition ---------------------

    #[test]
    fn parse_theme_condition_valid_minimal() {
        for input in ["dark", "(dark)", "DARK", "\"dark\"", "'dark'", "(\"dark\")", "  dark  "] {
            assert_eq!(
                parse_theme_condition(input),
                Some(DynamicSelector::Theme(ThemeCondition::Dark)),
                "theme {input:?} should resolve to Dark"
            );
        }
        assert_eq!(
            parse_theme_condition("light"),
            Some(DynamicSelector::Theme(ThemeCondition::Light))
        );
    }

    #[test]
    fn parse_theme_condition_garbage_returns_none() {
        for input in ["", "   ", "(", ")", "()", "sepia", "\u{1F600}", "dark light", "\"dark"] {
            let r = catch(|| parse_theme_condition(input));
            match r {
                Ok(v) => assert!(v.is_none(), "theme {input:?} should be rejected, got {v:?}"),
                Err(msg) => panic!("parse_theme_condition({input:?}) panicked: {msg}"),
            }
        }
    }

    #[test]
    fn parse_lang_condition_valid_minimal() {
        for input in ["de-DE", "(de-DE)", "(\"de-DE\")", "('de-DE')", "  de-DE  "] {
            assert_eq!(
                parse_lang_condition(input),
                Some(DynamicSelector::Language(LanguageCondition::Prefix(
                    AzString::from("de-DE".to_string())
                ))),
                "lang {input:?} should resolve to Prefix(de-DE)"
            );
        }
    }

    #[test]
    fn parse_lang_condition_empty_returns_none() {
        for input in ["", "   ", "()", "(  )", "( )"] {
            assert_eq!(
                parse_lang_condition(input),
                None,
                "empty lang {input:?} must not produce a condition"
            );
        }
    }

    #[test]
    fn parse_lang_condition_unicode_and_long_input_never_panic() {
        let long = "a".repeat(200_000);
        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&long);
        for input in inputs {
            let r = catch(|| parse_lang_condition(input));
            assert!(
                r.is_ok(),
                "parse_lang_condition({:.40?}) panicked: {}",
                input,
                r.unwrap_err()
            );
        }
    }

    // --- css variables ----------------------------------------------------

    #[test]
    fn parse_css_variable_brace_contents_valid_minimal() {
        assert_eq!(
            parse_css_variable_brace_contents("--main-bg-col"),
            Some(("main-bg-col", None))
        );
        let (name, default) = parse_css_variable_brace_contents("--main-bg-col, blue")
            .expect("var with default should parse");
        assert_eq!(name, "main-bg-col");
        // NOTE: the default is returned *untrimmed* (" blue"); `parse_css_property`
        // trims it later, so assert on the trimmed form to stay fix-stable.
        assert_eq!(default.map(str::trim), Some("blue"));
    }

    #[test]
    fn parse_css_variable_brace_contents_rejects_non_variables() {
        for input in ["", "   ", "main-bg-col", "-main-bg-col", "blue", "\u{1F600}", ","] {
            assert_eq!(
                parse_css_variable_brace_contents(input),
                None,
                "{input:?} is not a `--` prefixed CSS variable"
            );
        }
    }

    /// The function slices `&var_name[2..]` after a `starts_with("--")` check.
    /// `--` is ASCII, so byte 2 is always a char boundary even when the variable
    /// name itself is multi-byte.
    #[test]
    fn parse_css_variable_brace_contents_multibyte_name_does_not_split_a_char() {
        assert_eq!(
            parse_css_variable_brace_contents("--\u{1F600}"),
            Some(("\u{1F600}", None))
        );
        // An empty name after `--` is currently accepted; assert only that it is safe.
        let r = catch(|| parse_css_variable_brace_contents("--"));
        assert!(r.is_ok(), "`--` panicked: {}", r.unwrap_err());
    }

    #[test]
    fn check_if_value_is_css_var_recognises_var_syntax() {
        // Not a var() at all.
        assert!(check_if_value_is_css_var("100px").is_none());
        assert!(check_if_value_is_css_var("").is_none());
        assert!(check_if_value_is_css_var("calc(1px + 2px)").is_none());

        // A var() without a default falls back to "none".
        match check_if_value_is_css_var("var(--main-bg-color)") {
            Some(Ok((id, default))) => {
                assert_eq!(id, "main-bg-color");
                assert_eq!(default, "none");
            }
            other => panic!("expected Some(Ok(..)), got {other:?}"),
        }

        // A var() with a default returns it.
        match check_if_value_is_css_var("var(--w, 100px)") {
            Some(Ok((id, default))) => {
                assert_eq!(id, "w");
                assert_eq!(default.trim(), "100px");
            }
            other => panic!("expected Some(Ok(..)), got {other:?}"),
        }

        // Malformed brace contents surface as an error, not a panic and not a None.
        assert!(matches!(
            check_if_value_is_css_var("var(nonsense)"),
            Some(Err(CssParseErrorInner::DynamicCssParseError(
                DynamicCssParseError::InvalidBraceContents(_)
            )))
        ));
        assert!(matches!(
            check_if_value_is_css_var("var()"),
            Some(Err(CssParseErrorInner::DynamicCssParseError(
                DynamicCssParseError::InvalidBraceContents(_)
            )))
        ));
    }

    #[test]
    fn check_if_value_is_css_var_hostile_input_never_panics() {
        let long = format!("var(--{})", "x".repeat(100_000));
        let nested = format!("var({})", "(".repeat(10_000));
        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&long);
        inputs.push(&nested);
        inputs.push("var(");
        inputs.push("var)");
        inputs.push("var((--x))");

        for input in inputs {
            let r = catch(|| check_if_value_is_css_var(input).is_some());
            assert!(
                r.is_ok(),
                "check_if_value_is_css_var({:.40?}) panicked: {}",
                input,
                r.unwrap_err()
            );
        }
    }

    // --- parse_declaration_resilient / parse_css_declaration --------------

    #[test]
    fn parse_css_declaration_valid_minimal() {
        let km = key_map();
        let mut warnings = Vec::new();
        let mut declarations = Vec::new();
        let r = parse_css_declaration(
            "width",
            "100px",
            loc(0, 0),
            &km,
            &mut warnings,
            &mut declarations,
        );
        assert_eq!(r, Ok(()));
        assert_eq!(declarations.len(), 1);
        assert!(matches!(declarations[0], CssDeclaration::Static(_)));
        assert!(warnings.is_empty());
    }

    #[test]
    fn parse_css_declaration_unknown_key_is_downgraded_to_a_warning() {
        let km = key_map();
        let mut warnings = Vec::new();
        let mut declarations = Vec::new();
        // Documented contract: an unknown key is a warning, not a hard error, so the
        // caller can keep processing the rest of the block.
        let r = parse_css_declaration(
            "definitely-not-a-property",
            "1",
            loc(0, 0),
            &km,
            &mut warnings,
            &mut declarations,
        );
        assert_eq!(r, Ok(()));
        assert!(declarations.is_empty());
        assert_eq!(warnings.len(), 1);
        assert!(matches!(
            warnings[0].warning,
            CssParseWarnMsgInner::UnsupportedKeyValuePair { .. }
        ));
    }

    #[test]
    fn parse_css_declaration_bad_value_is_a_hard_error() {
        let km = key_map();
        let mut warnings = Vec::new();
        let mut declarations = Vec::new();
        let r = parse_css_declaration(
            "width",
            "definitely-not-a-length",
            loc(0, 0),
            &km,
            &mut warnings,
            &mut declarations,
        );
        assert!(r.is_err(), "a known key with an unparseable value must error");
        assert!(declarations.is_empty());
    }

    #[test]
    fn parse_declaration_resilient_var_on_shorthand_is_rejected() {
        let km = key_map();
        // `margin` is a shorthand; `var()` on it is ambiguous and must be refused.
        let r = parse_declaration_resilient("margin", "var(--m)", loc(0, 0), &km);
        assert!(
            matches!(r, Err(CssParseErrorInner::VarOnShorthandProperty { .. })),
            "expected VarOnShorthandProperty, got {r:?}"
        );
    }

    #[test]
    fn parse_declaration_resilient_var_on_normal_property_becomes_dynamic() {
        let km = key_map();
        let decls = parse_declaration_resilient("width", "var(--w, 100px)", loc(0, 0), &km)
            .expect("var() on a non-shorthand property should parse");
        assert_eq!(decls.len(), 1);
        match &decls[0] {
            CssDeclaration::Dynamic(DynamicCssProperty { dynamic_id, .. }) => {
                assert_eq!(dynamic_id.as_str(), "w");
            }
            other => panic!("expected a Dynamic declaration, got {other:?}"),
        }
    }

    #[test]
    fn parse_declaration_resilient_hostile_key_value_pairs_never_panic() {
        let km = key_map();
        let long = "x".repeat(100_000);
        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&long);

        for key in &inputs {
            for value in &inputs {
                let r = catch(|| parse_declaration_resilient(key, value, loc(0, 0), &km).is_ok());
                assert!(
                    r.is_ok(),
                    "parse_declaration_resilient({:.30?}, {:.30?}) panicked: {}",
                    key,
                    value,
                    r.unwrap_err()
                );
            }
        }
    }

    #[test]
    fn parse_declaration_resilient_empty_key_is_an_unknown_property() {
        let km = key_map();
        assert!(matches!(
            parse_declaration_resilient("", "", loc(0, 0), &km),
            Err(CssParseErrorInner::UnknownPropertyKey("", ""))
        ));
    }

    // =====================================================================
    // numeric -> overflow / NaN / saturation / limits
    // =====================================================================

    #[test]
    fn get_line_column_from_error_representative_values() {
        let css = "div {\n    width: 100px;\n}";
        // Position 0 and 1 both clamp to offset 0 via `saturating_sub(1)`.
        assert_eq!(
            ErrorLocation { original_pos: 0 }.get_line_column_from_error(css),
            (0, 0)
        );
        let (line, _col) = ErrorLocation { original_pos: 12 }.get_line_column_from_error(css);
        assert_eq!(line, 2, "byte 11 is on the second line");
    }

    #[test]
    fn get_line_column_from_error_empty_css_does_not_panic() {
        let r = catch(|| ErrorLocation { original_pos: 0 }.get_line_column_from_error(""));
        assert_eq!(r, Ok((0, 0)));
    }

    /// The column arithmetic (`error_location - total_characters.saturating_sub(2)`)
    /// is an unchecked subtraction; newline-heavy inputs are the worst case for it.
    #[test]
    fn get_line_column_from_error_newline_heavy_input_does_not_underflow() {
        let newlines = "\n".repeat(1_000);
        let crlf = "\r\n".repeat(1_000);
        for css in [newlines.as_str(), crlf.as_str()] {
            for pos in [1_usize, 2, 3, 500, css.len()] {
                let r = catch(|| ErrorLocation { original_pos: pos }.get_line_column_from_error(css));
                assert!(
                    r.is_ok(),
                    "get_line_column_from_error(pos={pos}) underflowed/panicked: {}",
                    r.unwrap_err()
                );
            }
        }
    }

    /// BUG (red): `css_string[0..error_location]` is an unchecked slice. An
    /// `original_pos` past the end of the string -- trivially reachable, since
    /// `ErrorLocation` is a `pub` struct with a `pub` field and the method takes an
    /// arbitrary `&str` -- panics with "byte index out of bounds" instead of
    /// clamping.
    #[test]
    fn get_line_column_from_error_out_of_range_pos_does_not_panic() {
        let css = "div {}";
        for pos in [css.len() + 2, 999, usize::MAX] {
            if let Err(msg) =
                catch(|| ErrorLocation { original_pos: pos }.get_line_column_from_error(css))
            {
                panic!(
                    "BUG: get_line_column_from_error panicked for original_pos={pos} on a \
                     {}-byte string (unchecked `css_string[0..error_location]` slice); it \
                     should clamp instead: {msg}",
                    css.len()
                );
            }
        }
    }

    /// BUG (red): the same unchecked slice also ignores UTF-8 char boundaries.
    /// `original_pos = css.len()` is exactly what `get_error_location` records at
    /// `Token::EndOfStream`, so a stylesheet whose last character is multi-byte
    /// makes `original_pos - 1` land *inside* that character and the slice panics
    /// with "byte index is not a char boundary".
    #[test]
    fn get_line_column_from_error_at_end_of_unicode_css_does_not_panic() {
        // "a\u{1F600}" is 5 bytes; the only char boundaries are 0, 1 and 5.
        let css = "a\u{1F600}";
        assert_eq!(css.len(), 5);
        let pos = css.len(); // -> error_location == 4, which is mid-emoji
        if let Err(msg) =
            catch(|| ErrorLocation { original_pos: pos }.get_line_column_from_error(css))
        {
            panic!(
                "BUG: get_line_column_from_error panicked at end-of-stream (original_pos={pos}) \
                 because the CSS ends with a multi-byte char and `original_pos - 1` splits it: \
                 {msg}"
            );
        }
    }

    // =====================================================================
    // getters / predicates -> invariants
    // =====================================================================

    #[test]
    fn get_error_string_returns_the_trimmed_slice_between_start_and_end() {
        let css = "div { width: 100px; }";
        let err = CssParseError {
            css_string: css,
            error: CssParseErrorInner::MalformedCss,
            location: loc(6, 18),
        };
        assert_eq!(err.get_error_string(), "width: 100px");

        // An empty range yields an empty string rather than panicking.
        let err = CssParseError {
            css_string: css,
            error: CssParseErrorInner::MalformedCss,
            location: loc(0, 0),
        };
        assert_eq!(err.get_error_string(), "");
    }

    /// BUG (red): `get_error_string` slices `&self.css_string[start..end]` with no
    /// validation. A location that is out of range, reversed, or lands inside a
    /// multi-byte char panics. `CssParseError` is `pub` with `pub` fields (and is
    /// rebuilt from an owned value by `CssParseErrorOwned::to_shared`, where nothing
    /// re-checks the location against the string), so this is reachable.
    #[test]
    fn get_error_string_invalid_location_does_not_panic() {
        let cases: [(&str, ErrorLocationRange, &str); 3] = [
            ("div", loc(0, 99), "end past the end of the string"),
            ("div", loc(2, 1), "reversed range (start > end)"),
            ("a\u{1F600}", loc(0, 4), "end inside a multi-byte char"),
        ];
        for (css, location, why) in cases {
            let err = CssParseError {
                css_string: css,
                error: CssParseErrorInner::MalformedCss,
                location,
            };
            if let Err(msg) = catch(|| err.get_error_string().to_string()) {
                panic!(
                    "BUG: get_error_string panicked on an invalid location ({why}) instead of \
                     returning an empty/clamped slice: {msg}"
                );
            }
        }
    }

    // --- serializer: Display for CssParseError ----------------------------

    #[test]
    fn display_of_css_parse_error_is_non_empty_and_well_formed() {
        let css = "div { width: 100px; }";
        let err = CssParseError {
            css_string: css,
            error: CssParseErrorInner::MalformedCss,
            location: loc(6, 18),
        };
        let s = format!("{err}");
        assert!(!s.is_empty());
        assert!(s.contains("start: line"), "missing start location: {s}");
        assert!(s.contains("end: line"), "missing end location: {s}");
        assert!(s.contains("width: 100px"), "missing offending text: {s}");
        assert!(s.contains("Malformed Css"), "missing reason: {s}");
    }

    #[test]
    fn display_of_css_parse_error_on_zero_value_does_not_panic() {
        let err = CssParseError {
            css_string: "",
            error: CssParseErrorInner::UnclosedBlock,
            location: ErrorLocationRange::default(),
        };
        let r = catch(|| format!("{err}"));
        match r {
            Ok(s) => assert!(!s.is_empty(), "Display produced an empty string"),
            Err(msg) => panic!("Display panicked on a zero-valued CssParseError: {msg}"),
        }
    }

    /// BUG (red): `Display for CssParseError` calls both `get_line_column_from_error`
    /// and `get_error_string`, so it inherits their unchecked slicing. Formatting the
    /// error for a stylesheet that ends in a multi-byte character panics -- i.e. the
    /// *error reporting path* itself crashes on non-ASCII CSS.
    #[test]
    fn display_of_css_parse_error_with_unicode_css_does_not_panic() {
        let css = "p{}\u{1F600}"; // 7 bytes; boundaries at 0..=3 and 7
        let err = CssParseError {
            css_string: css,
            error: CssParseErrorInner::MalformedCss,
            location: loc(0, css.len()),
        };
        if let Err(msg) = catch(|| format!("{err}")) {
            panic!(
                "BUG: Display for CssParseError panicked while formatting an error whose CSS \
                 ends in a multi-byte char (unchecked slicing in get_line_column_from_error / \
                 get_error_string): {msg}"
            );
        }
    }

    #[test]
    fn display_of_error_and_warning_inners_is_never_empty() {
        let km = key_map();
        let margin = CombinedCssPropertyType::from_str("margin", &km).expect("margin is a shorthand");

        let inners: Vec<CssParseErrorInner<'_>> = vec![
            CssParseErrorInner::ParseError(CssSyntaxError::UnknownToken(CssSyntaxErrorPos {
                row: usize::MAX,
                col: usize::MAX,
            })),
            CssParseErrorInner::UnclosedBlock,
            CssParseErrorInner::MalformedCss,
            CssParseErrorInner::DynamicCssParseError(DynamicCssParseError::InvalidBraceContents(
                "",
            )),
            CssParseErrorInner::PseudoSelectorParseError(
                CssPseudoSelectorParseError::EmptyNthChild,
            ),
            CssParseErrorInner::NodeTypeTag(NodeTypeTagParseError::Invalid("")),
            CssParseErrorInner::UnknownPropertyKey("", ""),
            CssParseErrorInner::VarOnShorthandProperty {
                key: margin,
                value: "",
            },
        ];

        for inner in &inners {
            let s = format!("{inner}");
            assert!(!s.is_empty(), "empty Display for {inner:?}");
        }

        let warnings = vec![
            CssParseWarnMsgInner::UnsupportedKeyValuePair { key: "", value: "" },
            CssParseWarnMsgInner::ParseError(CssParseErrorInner::MalformedCss),
            CssParseWarnMsgInner::SkippedRule {
                selector: None,
                error: CssParseErrorInner::UnclosedBlock,
            },
            CssParseWarnMsgInner::SkippedDeclaration {
                key: "",
                value: "",
                error: CssParseErrorInner::MalformedCss,
            },
            CssParseWarnMsgInner::MalformedStructure { message: "" },
        ];
        for w in &warnings {
            assert!(!format!("{w}").is_empty(), "empty Display for {w:?}");
        }
    }

    // =====================================================================
    // round-trip -> to_contained() == to_shared()
    // =====================================================================

    #[test]
    fn css_pseudo_selector_parse_error_round_trips() {
        let cases = vec![
            CssPseudoSelectorParseError::EmptyNthChild,
            CssPseudoSelectorParseError::UnknownSelector("blah", None),
            CssPseudoSelectorParseError::UnknownSelector("blah", Some("3")),
            CssPseudoSelectorParseError::InvalidNthChildPattern("2x+1"),
            CssPseudoSelectorParseError::InvalidNthChild(
                "x".parse::<u32>().unwrap_err(),
            ),
            CssPseudoSelectorParseError::InvalidNthChild(
                "99999999999999999999".parse::<u32>().unwrap_err(),
            ),
            // Empty / extreme payloads.
            CssPseudoSelectorParseError::UnknownSelector("", Some("")),
        ];
        for case in &cases {
            assert_eq!(
                &case.to_contained().to_shared(),
                case,
                "round-trip changed the value"
            );
        }
    }

    #[test]
    fn dynamic_css_parse_error_round_trips() {
        let simple = DynamicCssParseError::InvalidBraceContents("--x, blue");
        assert_eq!(&simple.to_contained().to_shared(), &simple);

        let empty = DynamicCssParseError::InvalidBraceContents("");
        assert_eq!(&empty.to_contained().to_shared(), &empty);

        // A real `CssParsingError` from the property parser. The nested error has its
        // own owned/shared pair, so compare via `Display` (semantics) plus the variant.
        let km = key_map();
        let width = CssPropertyType::from_str("width", &km).expect("width is a property");
        let inner = parse_css_property(width, "definitely-not-a-length")
            .expect_err("an invalid length must fail to parse");
        let wrapped = DynamicCssParseError::UnexpectedValue(inner);
        let round_tripped = wrapped.to_contained();
        let back = round_tripped.to_shared();
        assert!(matches!(back, DynamicCssParseError::UnexpectedValue(_)));
        assert_eq!(
            format!("{back}"),
            format!("{wrapped}"),
            "round-trip lost information from the nested CssParsingError"
        );
    }

    #[test]
    fn css_parse_error_inner_round_trips_for_every_variant() {
        let km = key_map();
        let margin =
            CombinedCssPropertyType::from_str("margin", &km).expect("margin is a shorthand");

        let cases = vec![
            CssParseErrorInner::ParseError(CssSyntaxError::UnexpectedEndOfStream(
                CssSyntaxErrorPos { row: 0, col: 0 },
            )),
            // Extreme numeric payloads must survive the FFI hop unchanged.
            CssParseErrorInner::ParseError(CssSyntaxError::InvalidAdvance(
                CssSyntaxInvalidAdvance {
                    expected: isize::MIN,
                    total: usize::MAX,
                    pos: CssSyntaxErrorPos {
                        row: usize::MAX,
                        col: usize::MAX,
                    },
                },
            )),
            CssParseErrorInner::ParseError(CssSyntaxError::UnsupportedToken(CssSyntaxErrorPos {
                row: 3,
                col: 7,
            })),
            CssParseErrorInner::UnclosedBlock,
            CssParseErrorInner::MalformedCss,
            CssParseErrorInner::DynamicCssParseError(DynamicCssParseError::InvalidBraceContents(
                "--x",
            )),
            CssParseErrorInner::PseudoSelectorParseError(
                CssPseudoSelectorParseError::EmptyNthChild,
            ),
            CssParseErrorInner::NodeTypeTag(NodeTypeTagParseError::Invalid("notatag")),
            CssParseErrorInner::UnknownPropertyKey("key", "value"),
            CssParseErrorInner::UnknownPropertyKey("", ""),
            CssParseErrorInner::VarOnShorthandProperty {
                key: margin,
                value: "var(--m)",
            },
        ];

        for case in &cases {
            assert_eq!(
                &case.to_contained().to_shared(),
                case,
                "round-trip changed the value for {case:?}"
            );
        }
    }

    #[test]
    fn css_parse_error_round_trips_including_unicode_payloads() {
        let css = "div { width: \u{1F600}; }";
        let err = CssParseError {
            css_string: css,
            error: CssParseErrorInner::UnknownPropertyKey("k\u{1F600}", "v\u{4E2D}"),
            location: loc(1, 2),
        };
        assert_eq!(err.to_contained().to_shared(), err);

        // Zero value.
        let err = CssParseError {
            css_string: "",
            error: CssParseErrorInner::MalformedCss,
            location: ErrorLocationRange::default(),
        };
        assert_eq!(err.to_contained().to_shared(), err);
    }

    #[test]
    fn css_path_parse_error_round_trips_for_every_variant() {
        let cases = vec![
            CssPathParseError::EmptyPath,
            CssPathParseError::InvalidTokenEncountered("{"),
            CssPathParseError::InvalidTokenEncountered(""),
            CssPathParseError::UnexpectedEndOfStream("div"),
            CssPathParseError::SyntaxError(CssSyntaxError::UnknownToken(CssSyntaxErrorPos {
                row: usize::MAX,
                col: 0,
            })),
            CssPathParseError::NodeTypeTag(NodeTypeTagParseError::Invalid("notatag")),
            CssPathParseError::PseudoSelectorParseError(
                CssPseudoSelectorParseError::InvalidNthChildPattern("2x"),
            ),
        ];
        for case in &cases {
            assert_eq!(
                &case.to_contained().to_shared(),
                case,
                "round-trip changed the value for {case:?}"
            );
        }
    }

    #[test]
    fn css_parse_warn_msg_round_trips_for_every_variant() {
        let inners = vec![
            CssParseWarnMsgInner::UnsupportedKeyValuePair {
                key: "foo",
                value: "bar",
            },
            CssParseWarnMsgInner::UnsupportedKeyValuePair { key: "", value: "" },
            CssParseWarnMsgInner::ParseError(CssParseErrorInner::MalformedCss),
            CssParseWarnMsgInner::SkippedRule {
                selector: None,
                error: CssParseErrorInner::UnclosedBlock,
            },
            CssParseWarnMsgInner::SkippedRule {
                selector: Some("div"),
                error: CssParseErrorInner::MalformedCss,
            },
            CssParseWarnMsgInner::SkippedDeclaration {
                key: "width",
                value: "\u{1F600}",
                error: CssParseErrorInner::MalformedCss,
            },
            CssParseWarnMsgInner::MalformedStructure {
                message: "unclosed",
            },
        ];

        for inner in &inners {
            assert_eq!(
                &inner.to_contained().to_shared(),
                inner,
                "round-trip changed the value for {inner:?}"
            );

            let msg = CssParseWarnMsg {
                warning: inner.clone(),
                location: loc(7, 42),
            };
            let back = msg.to_contained();
            let back = back.to_shared();
            assert_eq!(back, msg, "CssParseWarnMsg round-trip changed the value");
            assert_eq!(back.location, loc(7, 42), "location was not preserved");
        }
    }

    #[test]
    fn unparsed_css_rule_block_round_trips() {
        let mut declarations = BTreeMap::new();
        declarations.insert("width", ("100px", loc(1, 2)));
        declarations.insert("color", ("\u{1F600}", loc(3, 4)));

        let block = UnparsedCssRuleBlock {
            path: CssPath {
                selectors: vec![
                    CssPathSelector::Global,
                    CssPathSelector::Class("btn".to_string().into()),
                ]
                .into(),
            },
            declarations,
            // NB: deliberately no MinMaxRange condition here -- those store `f32::NAN`
            // as the "absent bound" sentinel, so they are not equal to themselves under
            // the derived `PartialEq` (see dynamic_selector.rs).
            conditions: vec![DynamicSelector::Media(MediaType::Screen)],
        };

        assert_eq!(block.to_contained().to_shared(), block);

        // Empty instance.
        let empty = UnparsedCssRuleBlock {
            path: CssPath {
                selectors: Vec::new().into(),
            },
            declarations: BTreeMap::new(),
            conditions: Vec::new(),
        };
        assert_eq!(empty.to_contained().to_shared(), empty);
    }

    // =====================================================================
    // other -> new_from_str / new_from_str_inner / css_blocks_to_stylesheet
    // =====================================================================

    #[test]
    fn new_from_str_valid_minimal() {
        let (css, warnings) = new_from_str("div { width: 100px; }");
        assert_eq!(css.rules.len(), 1);
        assert_eq!(css.rules.as_slice()[0].declarations.len(), 1);
        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
    }

    #[test]
    fn new_from_str_empty_input_yields_an_empty_stylesheet() {
        let (css, warnings) = new_from_str("");
        assert_eq!(css.rules.len(), 0);
        assert!(warnings.is_empty());

        let (css, _warnings) = new_from_str("   \n\t  ");
        assert_eq!(css.rules.len(), 0);
    }

    #[test]
    fn new_from_str_unclosed_block_warns_instead_of_failing() {
        let (css, warnings) = new_from_str("div { width: 100px;");
        assert_eq!(css.rules.len(), 0, "an unclosed block emits no rules");
        assert!(
            warnings.iter().any(|w| matches!(
                w.warning,
                CssParseWarnMsgInner::MalformedStructure { .. }
            )),
            "expected a MalformedStructure warning, got {warnings:?}"
        );
    }

    #[test]
    fn new_from_str_unknown_property_is_a_warning_not_a_dropped_rule() {
        let (css, warnings) = new_from_str("div { definitely-not-a-property: 1; width: 10px; }");
        assert_eq!(css.rules.len(), 1);
        // The unknown key is skipped but the valid declaration survives.
        assert_eq!(css.rules.as_slice()[0].declarations.len(), 1);
        assert!(!warnings.is_empty(), "the unknown key should have warned");
    }

    #[test]
    fn var_reference_resolves_against_a_root_custom_property() {
        let (css, _) = new_from_str(":root{--boxw:150px} .v{width:var(--boxw)}");
        // The `--boxw` DEFINITION emits no declaration; the `var(--boxw)` REFERENCE is
        // resolved to a concrete Static value, so exactly one declaration survives overall.
        let decls: Vec<_> = css
            .rules
            .as_slice()
            .iter()
            .flat_map(|r| r.declarations.as_slice().iter())
            .collect();
        assert_eq!(decls.len(), 1, "custom-prop def emits nothing, var() resolves: {decls:?}");
        // The resolved declaration is identical to a direct `width:150px`.
        let (direct, _) = new_from_str(".v{width:150px}");
        assert_eq!(decls[0], &direct.rules.as_slice()[0].declarations.as_slice()[0]);
    }

    #[test]
    fn undefined_var_reference_falls_back_to_its_default() {
        let (css, _) = new_from_str(".v{width:var(--nope, 42px)}");
        let (direct, _) = new_from_str(".v{width:42px}");
        assert_eq!(
            css.rules.as_slice()[0].declarations.as_slice()[0],
            direct.rules.as_slice()[0].declarations.as_slice()[0],
        );
    }

    /// `new_from_str` documents "Never panics" -- hold it to that.
    #[test]
    fn new_from_str_hostile_input_never_panics() {
        let long_rule = "div { width: 100px; }".repeat(2_000);
        let deep_nesting = format!("{}{}", "div {".repeat(500), "}".repeat(500));
        let unbalanced_open = "{".repeat(5_000);
        let unbalanced_close = "}".repeat(5_000);
        let long_selector = format!("{} {{ width: 1px; }}", "div ".repeat(10_000));

        let mut inputs: Vec<&str> = HOSTILE.to_vec();
        inputs.push(&long_rule);
        inputs.push(&deep_nesting);
        inputs.push(&unbalanced_open);
        inputs.push(&unbalanced_close);
        inputs.push(&long_selector);
        inputs.push("div { width: \u{1F600}; }");
        inputs.push("\u{1F600} { \u{4E2D}: \u{6587}; }");
        inputs.push("div { width: 100px; /* unterminated");
        inputs.push("@media (min-width: 800px) { div { width: 1px; } }");
        inputs.push("@theme(dark) { div { width: 1px; } }");
        inputs.push("@lang(\"de-DE\") { div { width: 1px; } }");
        inputs.push("@container sidebar (min-width: 400px) { div { width: 1px; } }");
        inputs.push("@definitely-not-an-at-rule x { div { width: 1px; } }");
        inputs.push(".a { .b { :hover { width: 1px; } } }");
        inputs.push("div[data-x=\"y\"] { width: 1px; }");
        inputs.push("div[ { width: 1px; }");
        inputs.push("a, b, , c { width: 1px; }");
        inputs.push("div:nth-child(999999999999) { width: 1px; }");

        for input in inputs {
            let r = catch(|| {
                let (css, warnings) = new_from_str(input);
                (css.rules.len(), warnings.len())
            });
            assert!(
                r.is_ok(),
                "new_from_str({:.60?}) panicked despite the `Never panics` contract: {}",
                input,
                r.unwrap_err()
            );
        }
    }

    #[test]
    fn new_from_str_at_rules_attach_conditions_to_nested_rules() {
        let (css, _warnings) = new_from_str("@media screen { div { width: 1px; } }");
        assert_eq!(css.rules.len(), 1);
        let rule = &css.rules.as_slice()[0];
        assert!(
            rule.conditions
                .as_slice()
                .contains(&DynamicSelector::Media(MediaType::Screen)),
            "the @media condition was not attached: {:?}",
            rule.conditions.as_slice()
        );
    }

    #[test]
    fn new_from_str_comma_separated_selectors_emit_one_rule_each() {
        let (css, _warnings) = new_from_str("div, p { width: 1px; }");
        assert_eq!(css.rules.len(), 2, "each selector in the list gets its own rule");
    }

    #[test]
    fn new_from_str_inner_matches_new_from_str() {
        let css_string = "div { width: 100px; }";
        let mut tokenizer = Tokenizer::new(css_string);
        let (rules, warnings) = new_from_str_inner(css_string, &mut tokenizer);
        assert_eq!(rules.len(), 1);
        assert!(warnings.is_empty());
    }

    #[test]
    fn get_error_location_tracks_the_tokenizer_position() {
        let css_string = "div { width: 100px; }";
        let mut tokenizer = Tokenizer::new(css_string);
        assert_eq!(get_error_location(&tokenizer).original_pos, 0);

        let _ = tokenizer.parse_next();
        let after = get_error_location(&tokenizer).original_pos;
        assert!(after > 0, "the tokenizer position did not advance");
        assert!(
            after <= css_string.len(),
            "the tokenizer position ran past the end of the input"
        );

        // Position on an empty document is 0 and must not panic.
        let empty = Tokenizer::new("");
        assert_eq!(get_error_location(&empty).original_pos, 0);
    }

    #[test]
    fn css_blocks_to_stylesheet_parses_known_keys_and_warns_on_unknown_ones() {
        let css_string = "div { width: 100px; }";

        let mut declarations = BTreeMap::new();
        declarations.insert("width", ("100px", loc(6, 18)));
        let good = UnparsedCssRuleBlock {
            path: CssPath {
                selectors: vec![CssPathSelector::Global].into(),
            },
            declarations,
            conditions: Vec::new(),
        };

        let mut declarations = BTreeMap::new();
        declarations.insert("definitely-not-a-property", ("1", loc(0, 1)));
        let bad = UnparsedCssRuleBlock {
            path: CssPath {
                selectors: vec![CssPathSelector::Global].into(),
            },
            declarations,
            conditions: Vec::new(),
        };

        let (rules, warnings) = css_blocks_to_stylesheet(vec![good, bad], css_string);
        assert_eq!(rules.len(), 2, "both blocks are emitted");
        assert_eq!(rules[0].declarations.len(), 1);
        assert_eq!(rules[1].declarations.len(), 0, "the unknown key is dropped");
        assert_eq!(warnings.len(), 1, "the unknown key produced exactly one warning");
        assert!(matches!(
            warnings[0].warning,
            CssParseWarnMsgInner::SkippedDeclaration { .. }
        ));
    }

    #[test]
    fn css_blocks_to_stylesheet_empty_input_is_empty_output() {
        let (rules, warnings) = css_blocks_to_stylesheet(Vec::new(), "");
        assert!(rules.is_empty());
        assert!(warnings.is_empty());
    }
}