makeover-webview 0.125.0

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser. With the build feature, writes a consumer's generated frontend files and checks the hand-written ones against them.
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
//! Every class this crate is responsible for, as a set rather than one name at
//! a time.
//!
//! The naming functions ([`crate::class`], [`crate::option_class`],
//! [`crate::list::part_class`], [`crate::list::cell_part_class`]) answer "what
//! is this one thing called". That is half the agreement. The other half is
//! the set: a checker cannot ask "is this app rule
//! re-specifying something makeover already defines" without the list, and this
//! crate is the only place that knows it, because this crate writes the sheet.
//!
//! # Two sets, because there are two questions
//!
//! [`vocabulary`] is the classes the generated stylesheet writes a rule for.
//! That is the set a drift check wants: an app rule for one of these is a
//! restatement of a rule the app already gets, and unlayered app CSS beats
//! `@layer makeover`, so the restatement silently wins.
//!
//! [`names`] is every class this crate can put in markup, written down module by
//! module beside the emitters. The two sets are equal, and a test holds them
//! equal: a class an emitter can write and the sheet does not rule is an
//! element that draws as default flow, which is how MNW's five ssh-keys classes
//! went four months unstyled and how a described form on MNW drew its error as
//! a plain sentence. wiki `look-restoration`, "zero generated classes left
//! unstyled". They stay two functions because they are two sources, the sheet
//! scraped and the emitters listed, and the gate is that they agree.
//!
//! # Why the first set is scraped and not listed
//!
//! A hand-maintained copy of the sheet's contents is the defect being fixed,
//! one level up: it can disagree with the sheet, and the day it does, the
//! checker reads the list and the browser reads the sheet. So [`vocabulary`]
//! parses the CSS this crate generates. There is no second source to drift
//! from, and a class added to an emitter enters the vocabulary in the same
//! commit that adds it.

use crate::chart::CHART_CLASSES;
use crate::css_lex::{Lang, Role, is_ident, lex, matching_close, top_level};
use crate::facet::FACET_CLASSES;
use crate::figure::FIGURE_CLASSES;
use crate::form::{FIELD_CLASSES, FIELD_STATE_CLASSES};
use crate::list::{
    CELL_DROP_CLASSES, CELL_PART_CLASSES, CELL_WIDTH_CLASSES, FLOW_CLASSES, NESTING_CLASSES,
    ROW_PART_CLASSES,
};
use crate::meter::METER_CLASSES;
use crate::placeholder::PLACEHOLDER_CLASSES;
use crate::{Emit, option_class};
use makeover_layout::Selector;
use std::collections::{BTreeMap, BTreeSet};

/// Every class name the generated stylesheet defines a rule for, prefixed the
/// way `opts` prefixes them.
///
/// Includes the state classes a caller never spells alone (`chosen`,
/// `latched`). Those are deliberately unprefixed: they qualify a prefixed
/// component (`.mo-tab.chosen`) rather than standing on their own, so a prefix
/// moves the thing and not its state.
#[must_use]
pub fn vocabulary(opts: &Emit) -> BTreeSet<String> {
    classes_in_css(&crate::stylesheet(opts))
}

/// Every class a renderer's markup may carry, or a rule here names.
///
/// [`vocabulary`] plus every class the class lists below say markup can carry,
/// which is to say [`vocabulary`] exactly: the test below fails on any
/// difference. This is the
/// set to check a renderer's emitted markup against: a class outside it is a
/// name that renderer invented, which is how quasi-webview came to spell
/// `tabs`, `segmented` and `option` and render every described selector flat.
///
/// # The markup's half is written down, module by module
///
/// One list per module whose classes reach markup, each beside its rules, and
/// this is their union with the scrape. Keeping the lists beside the rules is
/// what stops the set drifting from what actually comes out in a document. A
/// name this function omits is a name an app reads as dead and deletes live
/// rules for, and a name the sheet does not rule is an element drawn as
/// default flow.
///
/// The emitters live in the quasi hosts, and `quasi-webview`'s corpus test
/// is what keeps the union honest: it renders rather than reading the source,
/// because a width class, a drop class and a state appended to an open
/// attribute are literals nowhere.
#[must_use]
pub fn names(opts: &Emit) -> BTreeSet<String> {
    let mut all = vocabulary(opts);
    all.extend(
        ROW_PART_CLASSES
            .iter()
            .chain(CELL_PART_CLASSES)
            .chain(CELL_WIDTH_CLASSES)
            .chain(CELL_DROP_CLASSES)
            .chain(FLOW_CLASSES)
            .chain(NESTING_CLASSES)
            .chain(crate::RUN_CLASSES)
            .chain(FACET_CLASSES)
            .chain(FIELD_CLASSES)
            .chain(FIGURE_CLASSES)
            .chain(METER_CLASSES)
            .chain(CHART_CLASSES)
            .chain(PLACEHOLDER_CLASSES)
            .map(|name| crate::class(name, opts)),
    );
    all.extend(
        [Selector::Tabs, Selector::Segmented, Selector::Toggle]
            .into_iter()
            .map(|s| crate::class(option_class(s), opts)),
    );
    // Unprefixed, deliberately, exactly as the `chosen` and `latched` the
    // scraped half brings in: a state qualifies a prefixed component rather
    // than standing on its own.
    all.extend(FIELD_STATE_CLASSES.iter().map(|name| (*name).to_owned()));
    all
}

/// Which properties a stylesheet sets on each class it names.
///
/// The grain a drift check actually wants. A class name in common is not by
/// itself a divergence: goingson's `.badge` sets shape and the generated
/// `.badge` sets fill and edge, and the app's own comment says "do not add
/// background, border or box-shadow here". That arrangement is settled and
/// correct, so a check that flagged the shared name would demand deleting it.
/// A shared *property* is the thing that goes wrong, because app CSS is
/// unlayered and takes the property from the design system silently.
///
/// A property appearing under more than one selector arm collapses into one
/// entry. That loses a real distinction, the sort caret's reserved gap is
/// `content` on the unsorted arm and the generated caret is `content` on the
/// sorted one, which is a deliberate pairing rather than a clash, so a
/// consumer of this needs a way to say a pair was reviewed. Deciding that here
/// would need a selector matcher, and a check that guesses wrong about
/// specificity fails correct builds.
///
/// A declaration whose value is exactly `revert-layer` is not one of them. It
/// takes nothing by construction: it is a later layer handing the property back
/// to the one below, which is the opposite of the thing this reader is looking
/// for. Counting it made every handoff in a consumer's sheet look like an
/// override, and the allowlist entry written to silence one went on permitting
/// a real override on the same pair afterwards. [`deferrals_by_class`] is where
/// those declarations go instead.
#[must_use]
pub fn declarations_by_class(css: &str) -> BTreeMap<String, BTreeSet<String>> {
    by_class(css, |value| !is_handoff(value))
}

/// Which properties a stylesheet hands back to the layer below, per class.
///
/// The other half of [`declarations_by_class`]. A `revert-layer` says "whatever
/// the design system set here, keep it", so a checker reading a consumer's
/// sheet wants it as evidence that a clash was already remedied rather than as
/// a clash of its own.
#[must_use]
pub fn deferrals_by_class(css: &str) -> BTreeMap<String, BTreeSet<String>> {
    by_class(css, is_handoff)
}

/// [`declarations_by_class`] and [`deferrals_by_class`], which differ only in
/// which declarations they keep.
fn by_class(css: &str, keep: impl Fn(&str) -> bool) -> BTreeMap<String, BTreeSet<String>> {
    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    walk_arms(css, keep, |arm, properties| {
        for class in classes_matched_by(arm) {
            out.entry(class)
                .or_default()
                .extend(properties.iter().cloned());
        }
    });
    out
}

/// Every arm of every rule that sets a property `keep` admits, with the
/// properties its rule sets.
fn walk_arms(
    css: &str,
    keep: impl Fn(&str) -> bool,
    mut each: impl FnMut(&str, &BTreeSet<String>),
) {
    for (selector, body) in rules(css) {
        let properties = properties_in_body(&body, &keep);
        if properties.is_empty() {
            continue;
        }
        for arm in selector_arms(&selector) {
            each(arm, &properties);
        }
    }
}

/// Raise each property's entry to at least `rank`.
fn strengthen(
    entry: &mut BTreeMap<String, Specificity>,
    properties: &BTreeSet<String>,
    rank: Specificity,
) {
    for property in properties {
        let strongest = entry.entry(property.clone()).or_default();
        *strongest = (*strongest).max(rank);
    }
}

/// Which properties a stylesheet sets on each bare element it names.
///
/// The blind spot [`declarations_by_class`] has by construction: it keys rules
/// by the classes in their selectors, so a rule carrying no class at all is
/// invisible to it. `button { color: var(--content) }` is exactly that, and it
/// sets the same property the generated `.button` does on every described act
/// in the app, including the tone of a destructive one, so a delete comes to
/// look like an ordinary button with the check reporting nothing.
///
/// Only a selector arm that is one bare compound counts: `button`,
/// `button:hover`, `input[type="text"]`. A scoped arm (`.page button`) reaches
/// the elements inside one region rather than every one of them, so whether it
/// lands on a described act depends on where that act is rendered, and a check
/// that guessed would fail correct builds. The certain case is the one this
/// reads.
///
/// Pair the result against [`classes_for_element`] to ask the question a
/// checker wants: does this element rule take a property the design system sets
/// on a class that element can carry.
///
/// The answer carries the strongest arm each property was set on, because the
/// app's own remedy has to outrank the rule it remedies. `.field` does not beat
/// `input[type="text"]`: both are the app's, both are in the same layer, and
/// the attribute makes the element rule the more specific of the two. A check
/// reading only "the app mentions this pair somewhere" waves that straight
/// through, which is the shape of every handoff that looked written and was
/// not.
#[must_use]
pub fn declarations_by_element(css: &str) -> BTreeMap<String, BTreeMap<String, Specificity>> {
    let mut out: BTreeMap<String, BTreeMap<String, Specificity>> = BTreeMap::new();
    walk_arms(
        css,
        |value| !is_handoff(value),
        |arm, properties| {
            if let Some(element) = bare_element(arm) {
                strengthen(
                    out.entry(element).or_default(),
                    properties,
                    specificity(arm),
                );
            }
        },
    );
    out
}

/// The arms of a selector list: its commas at the top level, and no others.
///
/// A comma inside `:is(a, button)` or `[title="a,b"]` separates arguments, not
/// arms. Splitting on it reads `.card:is(a, button)` as a bare `button` rule,
/// which is a class-qualified rule reported as an element rule clobbering the
/// design system.
///
/// Public beside [`rules`] so a consumer can read the same selector the reader
/// inside this module read, rather than re-implement the split and drift from
/// it.
pub fn selector_arms(selector: &str) -> Vec<&str> {
    let mut arms = Vec::new();
    let mut start = 0;
    for (i, _) in top_level(selector).filter(|&(_, c)| c == ',') {
        arms.push(&selector[start..i]);
        start = i + 1;
    }
    arms.push(&selector[start..]);
    arms
}

/// What a stylesheet says about each class, and how strongly.
///
/// Every property the sheet names on a class, whether it takes it or hands it
/// back, keyed by the strongest arm that names it. The question it answers is
/// not "does this collide", [`declarations_by_class`] is that, but "has the
/// app spoken for this pair, in a rule that wins where it has to".
#[must_use]
pub fn mentions_by_class(css: &str) -> BTreeMap<String, BTreeMap<String, Specificity>> {
    let mut out: BTreeMap<String, BTreeMap<String, Specificity>> = BTreeMap::new();
    walk_arms(
        css,
        |_| true,
        |arm, properties| {
            let rank = specificity(arm);
            for class in classes_matched_by(arm) {
                strengthen(out.entry(class).or_default(), properties, rank);
            }
        },
    );
    out
}

/// Which properties a stylesheet sets on each class from the bare arm `.class`,
/// the rule that reaches every element carrying it whatever its state.
///
/// The arm a later layer cancels variants from. `.button { color }` in an app
/// sheet reaches every `.button`, so it beats `.button[data-tone="danger"]`
/// in `@layer makeover` however much more specific that is: layers resolve
/// before specificity. A scoped arm (`.page .button`), a qualified one
/// (`.button.primary`, `button.button`) or a state arm reaches fewer elements
/// than the variants it might cancel, and whether it lands on one depends on
/// markup this cannot read. The certain case is the one this reads, the same
/// line [`declarations_by_element`] draws.
#[must_use]
pub fn bare_declarations(css: &str) -> BTreeMap<String, BTreeSet<String>> {
    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    walk_arms(
        css,
        |value| !is_handoff(value),
        |arm, properties| {
            if let Some(class) = bare_class(arm) {
                out.entry(class)
                    .or_default()
                    .extend(properties.iter().cloned());
            }
        },
    );
    out
}

/// The class an arm names when the arm is that class and nothing else.
fn bare_class(arm: &str) -> Option<String> {
    let name = arm.trim().strip_prefix('.')?;
    let whole =
        name.starts_with(|c: char| c.is_alphabetic() || c == '_') && name.chars().all(is_ident);
    whole.then(|| name.to_string())
}

/// Every arm on which a stylesheet styles a class in some state, variant or
/// context rather than everywhere, with the properties that arm sets.
///
/// Keyed by class, then by the arm as [`normalize_arm`] spells it.
/// `.button[data-tone="danger"]`, `.button:disabled` and `.run .link` are all
/// variants; `.button` is not. What makes an arm a variant is only that it is
/// not the bare class, so the reader needs no theory of which qualifiers
/// matter: anything narrower than everywhere is something a rule on the bare
/// class in a later layer silently undoes.
///
/// An arm ending in a pseudo-element is skipped, for the reason
/// `classes_matched_by` gives: it styles a box the element draws, not the
/// element.
#[must_use]
pub fn variants_by_class(css: &str) -> BTreeMap<String, BTreeMap<String, BTreeSet<String>>> {
    let mut out: BTreeMap<String, BTreeMap<String, BTreeSet<String>>> = BTreeMap::new();
    walk_arms(
        css,
        |value| !is_handoff(value),
        |arm, properties| {
            if arm.contains("::") || bare_class(arm).is_some() {
                return;
            }
            let spelled = expand_is(&normalize_arm(arm));
            for class in classes_matched_by(arm) {
                let arms = out.entry(class).or_default();
                for alternative in &spelled {
                    arms.entry(alternative.clone())
                        .or_default()
                        .extend(properties.iter().cloned());
                }
            }
        },
    );
    out
}

/// Every property a stylesheet names on each arm, taken or handed back, keyed
/// by the arm as [`normalize_arm`] spells it.
///
/// The evidence that a cancelled variant was restated. A restatement has to be
/// on the variant's own arm: one on a weaker arm sits in the same app layer as
/// the bare rule and loses or ties with it on specificity, and one on another
/// variant restates a different state.
#[must_use]
pub fn mentions_by_arm(css: &str) -> BTreeMap<String, BTreeSet<String>> {
    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    walk_arms(
        css,
        |_| true,
        |arm, properties| {
            for alternative in expand_is(&normalize_arm(arm)) {
                out.entry(alternative)
                    .or_default()
                    .extend(properties.iter().cloned());
            }
        },
    );
    out
}

/// A normalized arm with every `:is(...)` outside a negation or a `:has()`
/// multiplied out into the arms it stands for.
///
/// `.tab:is(:disabled,[aria-disabled="true"])` is the two arms
/// `.tab:disabled` and `.tab[aria-disabled="true"]`, and one sheet writing
/// the grouped form while the other writes the pair is the same claim. Only
/// `:is`: `:where` has no specificity, so a restatement written with it is
/// not the same rule. Specificity of the expanded arm can differ from the
/// grouped one by the group's strongest argument, which errs toward reading a
/// restatement as weaker, the safe side for a checker.
#[must_use]
pub fn expand_is(original: &str) -> Vec<String> {
    const LIMIT: usize = 64;
    let mut done = Vec::new();
    let mut pending = vec![original.to_string()];
    while let Some(arm) = pending.pop() {
        let Some((start, end)) = top_level_is(&arm) else {
            done.push(arm);
            continue;
        };
        let inner = &arm[start + ":is(".len()..end];
        for alternative in selector_arms(inner) {
            pending.push(format!(
                "{}{}{}",
                &arm[..start],
                alternative,
                &arm[end + 1..]
            ));
        }
        if done.len() + pending.len() > LIMIT {
            return vec![original.to_string()];
        }
    }
    done.sort();
    done.dedup();
    done
}

/// Where the first `:is(` sits that is not inside another parenthesis, with
/// the offset of its closing parenthesis.
fn top_level_is(arm: &str) -> Option<(usize, usize)> {
    let bytes = arm.as_bytes();
    let mut depth = 0usize;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'(' => depth += 1,
            b')' => depth = depth.saturating_sub(1),
            b':' if depth == 0 && arm[i..].starts_with(":is(") => {
                return matching_close(bytes, i + ":is".len(), b'(', b')').map(|k| (i, k));
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// One selector arm spelled one way, so two sheets' arms compare as text.
///
/// Runs of whitespace become one space, whitespace beside a combinator or a
/// comma and inside a pseudo-class's parentheses goes, and single quotes
/// become double: the spellings a
/// hand-written sheet and the generated one can differ by without selecting
/// anything different.
#[must_use]
pub fn normalize_arm(arm: &str) -> String {
    let mut words = String::new();
    for word in arm.split_whitespace() {
        if !words.is_empty() {
            words.push(' ');
        }
        words.push_str(word);
    }
    let words = words.replace('\'', "\"");
    // Not a bracket's outside: `.a [x]` and `.a :is(.b)` are descendant
    // combinators, and dropping that space would select a different element.
    let before = ['>', '+', '~', ',', ')'];
    let after = ['>', '+', '~', ',', '('];
    let chars: Vec<char> = words.chars().collect();
    let mut out = String::with_capacity(words.len());
    for (i, &c) in chars.iter().enumerate() {
        if c == ' '
            && (chars.get(i + 1).is_some_and(|n| before.contains(n))
                || i.checked_sub(1)
                    .and_then(|p| chars.get(p))
                    .is_some_and(|p| after.contains(p)))
        {
            continue;
        }
        out.push(c);
    }
    out
}

/// How CSS ranks one selector: ids, then classes, then elements.
///
/// Ordered the way the cascade orders it, so the tuple comparison is the
/// cascade's comparison. It settles a contest between two rules in the same
/// layer, which is the only contest it is used for here: a layer beats
/// specificity outright, so nothing in the app's sheet has to be compared
/// against the generated one this way.
pub type Specificity = (usize, usize, usize);

/// The specificity of one selector arm.
///
/// A functional pseudo-class counts as one class and its argument is not read.
/// CSS says `:not(.a.b)` takes the specificity of its strongest argument, so
/// this undercounts a compound inside one, which puts the error on the side
/// of reporting a remedy as too weak rather than accepting one that is.
#[must_use]
pub fn specificity(selector: &str) -> Specificity {
    let chars: Vec<char> = selector.chars().collect();
    let (mut ids, mut classes, mut elements) = (0, 0, 0);
    let mut i = 0;
    while i < chars.len() {
        match chars[i] {
            '#' => {
                ids += 1;
                i = skip_name(&chars, i + 1);
            }
            '.' => {
                classes += 1;
                i = skip_name(&chars, i + 1);
            }
            ':' => {
                // `::before` is an element, `:hover` is a class.
                if chars.get(i + 1) == Some(&':') {
                    elements += 1;
                    i = skip_name(&chars, i + 2);
                } else {
                    classes += 1;
                    i = skip_name(&chars, i + 1);
                }
                if chars.get(i) == Some(&'(') {
                    i = skip_group(&chars, i);
                }
            }
            '[' => {
                classes += 1;
                i = skip_group(&chars, i);
            }
            c if c.is_ascii_alphabetic() => {
                elements += 1;
                i = skip_name(&chars, i);
            }
            // A combinator, whitespace, or the universal selector, none of
            // which count for anything.
            _ => i += 1,
        }
    }
    (ids, classes, elements)
}

/// Past the identifier starting at `from`.
fn skip_name(chars: &[char], from: usize) -> usize {
    let mut i = from;
    while i < chars.len() && is_ident(chars[i]) {
        i += 1;
    }
    i
}

/// Past the bracketed or parenthesised group opening at `from`, nesting and
/// all.
fn skip_group(chars: &[char], from: usize) -> usize {
    let close = if chars[from] == '[' { ']' } else { ')' };
    matching_close(chars, from, chars[from], close).map_or(chars.len(), |k| k + 1)
}

/// A value that hands the property back rather than taking it.
///
/// Bare only. `revert-layer !important` in a later layer inverts layer order
/// and takes the property from every layer below, which is the opposite
/// declaration wearing the same word.
fn is_handoff(value: &str) -> bool {
    value.trim() == "revert-layer"
}

/// The property names a declaration block sets, keeping the ones `keep` admits.
fn properties_in_body(body: &str, keep: impl Fn(&str) -> bool) -> BTreeSet<String> {
    body.split(';')
        .filter_map(|decl| decl.split_once(':'))
        .filter(|(_, value)| keep(value))
        .map(|(name, _)| {
            let name = name.trim();
            // A standard property name is case-insensitive, so `BOX-SHADOW` is
            // `box-shadow` and must fold; a custom property (`--x`) is
            // case-sensitive and must not.
            if name.starts_with("--") {
                name.to_string()
            } else {
                name.to_ascii_lowercase()
            }
        })
        .filter(|name| !name.is_empty() && !name.contains(['{', '}']))
        .collect()
}

#[must_use]
pub fn classes_in_css(css: &str) -> BTreeSet<String> {
    rules(css)
        .into_iter()
        .flat_map(|(selector, _)| classes_in_selector(&selector))
        .collect()
}

/// The attributes a stylesheet selects on, as `name` and `name=value` both.
///
/// [`classes_in_css`] answers "which classes" and this answers "which
/// attributes", the third question the module's readers leave open. A value a
/// selector pins is carried beside the bare name: `[data-tone="danger"]`
/// contributes `data-tone` and `data-tone=danger`, so a reader can ask "does
/// any rule select on this attribute" and "does any rule pin this value" with
/// one set.
///
/// The value is normalised the way two spellings compare: surrounding quotes
/// stripped and a trailing case-insensitivity flag (`i` or `s`) dropped, so
/// `[aria-sort="ascending" i]` reads as `aria-sort=ascending`. The name is
/// lowercased, the value is not.
///
/// Only attributes in a selector count. An attribute name appearing in a
/// declaration (`content`, say) is not something a rule selects on.
#[must_use]
pub fn attributes_in_css(css: &str) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    for (selector, _) in rules(css) {
        for arm in selector_arms(&selector) {
            for (name, value) in attributes_in_selector(arm) {
                out.insert(name.clone());
                if let Some(value) = value {
                    out.insert(format!("{name}={value}"));
                }
            }
        }
    }
    out
}

/// The `[name]` selectors one arm carries, as `(name, value)` pairs.
///
/// A value is `None` when the arm names the attribute without pinning one
/// (`[hidden]`), and `Some` otherwise. Quoted values keep the quoting as the
/// sheet wrote it; [`attributes_in_css`] normalises.
fn attributes_in_selector(selector: &str) -> Vec<(String, Option<String>)> {
    let chars: Vec<char> = selector.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '[' {
            let end = skip_group(&chars, i);
            let inner: String = chars[i + 1..end.saturating_sub(1)].iter().collect();
            out.push(scan_attribute(&inner));
            i = end;
        } else {
            i += 1;
        }
    }
    out
}

/// The inside of one `[...]`, read as `(name, value)`.
fn scan_attribute(inner: &str) -> (String, Option<String>) {
    let inner = inner.trim();
    let name_end = inner
        .find(|c: char| !(is_ident(c) || c == ':'))
        .unwrap_or(inner.len());
    let name = inner[..name_end].to_ascii_lowercase();
    let value = inner
        .split_once('=')
        .map(|(_, value)| {
            value
                .trim()
                .trim_end_matches(|c: char| c == 'i' || c == 's' || c.is_whitespace())
                .trim()
                .trim_matches(['"', '\''])
                .to_owned()
        })
        .filter(|value| !value.is_empty());
    (name, value)
}

/// `(selector, declaration block)` for every rule in a stylesheet.
///
/// One reader for both sides. Comparing what makeover defines against what an
/// app defines is only meaningful if the two were read the same way, which is
/// why this is the only place either question is answered from.
///
/// A comment is skipped whole: the banner at the top of the generated sheet is
/// prose about the cascade layer and would otherwise contribute words that look
/// like selectors. A string is opaque, because `content: "\25B2"` is the sort
/// caret rather than a selector and a brace inside one would desync the stack.
/// An at-rule block (`@layer`, `@media`, `@supports`) holds rules rather than
/// declarations, so a depth counter alone is not enough and the stack records
/// what kind of block each brace opened.
///
/// The drift checks blank comments and strings with the same lexer, so the two
/// never disagree about where one ends.
pub fn rules(css: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    // One entry per open brace: true when that block holds declarations rather
    // than nested rules.
    let mut blocks: Vec<bool> = Vec::new();
    // Text since the last `{`, `}` or `;`. What precedes a `{` is that block's
    // prelude, and a prelude starting with `@` opens an at-rule. A string's
    // whole span stays here, because a prelude can be a selector and
    // `[data-tone="danger"]` read as `[data-tone=]` is an attribute check
    // nothing can be built on.
    let mut prelude = String::new();
    // The declaration so far: the part of `prelude` that belongs in a block's
    // body. It differs only in holding a string as its two quotes alone, so a
    // `;` or `:` inside one cannot split a declaration, and it is discarded
    // when the prelude turns out to be a nested rule rather than a statement.
    let mut stmt = String::new();
    // The selector of each open declaration block, and the body so far.
    let mut open: Vec<(String, String)> = Vec::new();

    for (c, role) in lex(css, Lang::Css) {
        match (role, c) {
            (Role::Comment, _) => {}
            (Role::Text, _) => prelude.push(c),
            (_, '{') => {
                if prelude.trim_start().starts_with('@') {
                    blocks.push(false);
                } else {
                    // A nested rule is a rule of its own. Its prelude resolves
                    // against the block it sits in, which is what keeps
                    // `.page { .button { } }` from reading as a bare `.button`
                    // rule that reaches every button in the app.
                    let selector = match open.last() {
                        Some((parent, _)) => nest(parent, prelude.trim()),
                        None => prelude.clone(),
                    };
                    open.push((selector, String::new()));
                    blocks.push(true);
                }
                prelude.clear();
                stmt.clear();
            }
            (_, '}') => {
                if blocks.pop().unwrap_or(false) {
                    if let Some((_, body)) = open.last_mut() {
                        body.push_str(&stmt);
                    }
                    if let Some(rule) = open.pop() {
                        out.push(rule);
                    }
                }
                prelude.clear();
                stmt.clear();
            }
            _ => {
                if blocks.last().copied().unwrap_or(false) {
                    if c == ';' {
                        if let Some((_, body)) = open.last_mut() {
                            body.push_str(&stmt);
                            body.push(';');
                        }
                        prelude.clear();
                        stmt.clear();
                    } else {
                        prelude.push(c);
                        stmt.push(c);
                    }
                } else if c == ';' {
                    prelude.clear();
                } else {
                    prelude.push(c);
                }
            }
        }
    }
    out
}

/// The selector a nested rule resolves to inside the block it sits in.
///
/// A prelude beginning with `&` splices the parent in where the `&` stands; one
/// without is a descendant of it. The parent's commas are an arm list, and each
/// arm takes its own copy, so `.a, .b { .c { } }` resolves to `.a .c, .b .c`
/// and never to `.a, .b .c`. Carrying the parent in matters: a nested `.button`
/// inside `.page` is `.page .button`, which reaches fewer elements than the
/// bare class, so it must not read as a rule on the class itself.
fn nest(parent: &str, nested: &str) -> String {
    let mut arms = Vec::new();
    for outer in selector_arms(parent) {
        let outer = outer.trim();
        for inner in selector_arms(nested) {
            let inner = inner.trim();
            if let Some(rest) = inner.strip_prefix('&') {
                arms.push(format!("{outer}{rest}"));
            } else if inner.is_empty() {
                arms.push(outer.to_string());
            } else {
                arms.push(format!("{outer} {inner}"));
            }
        }
    }
    arms.join(", ")
}

/// Which generated classes each element can plausibly carry.
///
/// The half of the element check that CSS cannot answer. A stylesheet says
/// `button { color: ... }` and `.chip { color: ... }` and nothing in either
/// text says a chip is rendered as a `<button>`; the renderer knows that, and
/// this crate is the renderer. So the pairing is declared here rather than
/// inferred, and [`declarations_by_element`] supplies the other half.
///
/// Read it as "may carry", not "does carry". A pairing that never occurs in a
/// given app costs a check that finds nothing; a pairing left out is a defect
/// that ships, which is the trade this list is written on the generous side
/// of.
///
/// `div` and `span` are deliberately absent. Nearly every container class in
/// the vocabulary sits on one of them, so the pairing would be the whole
/// vocabulary against one rule and would say nothing about which class was
/// meant. An app writing a bare `div { }` rule has a wider problem than this
/// check, and the classes it would clobber are containers rather than the
/// controls whose tone and bevel carry meaning.
pub const ELEMENT_CLASSES: &[(&str, &[&str])] = &[
    // The controls. `a` and `button` are interchangeable in markup for most of
    // these, a link that posts is a button, an act that navigates is an
    // anchor, which is why the two lists overlap as much as they do.
    (
        "a",
        &[
            "link",
            "button",
            "tab",
            "chip",
            "badge",
            "card",
            "row-activate",
            "figure-act",
            "chrome-place",
            "facet-take",
            "facet-prune",
            "facet-join-word",
        ],
    ),
    (
        "button",
        &[
            "button",
            "chip",
            "segment",
            "toggle",
            "tab",
            "link",
            "badge",
            "card",
            "facet-take",
            "facet-prune",
            "facet-join-word",
            "chip-remove",
            "row-activate",
        ],
    ),
    // A disclosure. quasi-webview renders an ask as `<details>` with a
    // `<summary>` that is styled as an act.
    ("details", &["ask"]),
    ("summary", &["button", "ask-open", "ask-body"]),
    // The form controls. `.field` is the well every one of them sits in.
    ("input", &["field", "toggle", "row-select"]),
    ("select", &["field"]),
    ("textarea", &["field"]),
    (
        "label",
        &[
            "form-label",
            "form-checkbox-label",
            "form-radio-label",
            "toggle",
            // A card wrapping a choice, which is how a tier picker is pressed.
            "card",
        ],
    ),
    ("form", &["form"]),
    ("progress", &["progress"]),
    // Text and lists.
    ("p", &["text", "facet-name", "placeholder-text"]),
    ("ul", &["list", "facet-values"]),
    ("ol", &["list"]),
    ("li", &["facet-value"]),
    // A table written in HTML rather than described. quasi-webview renders a
    // described table as divs carrying the same classes, so both spellings of
    // the same table answer to the same rules and both are worth checking.
    ("table", &["table"]),
    ("thead", &["table-head"]),
    ("tr", &["table-row"]),
    ("td", &["cell", "cell-value", "cell-content"]),
    ("th", &["table-heading"]),
    // A figure, likewise: the described picture is divs, the hand-written one
    // is the HTML element that means the same thing.
    ("figure", &["picture", "figure"]),
    ("img", &["picture-img"]),
    ("figcaption", &["picture-caption", "figure-caption"]),
    ("nav", &["chrome-nav"]),
];

/// The generated classes `element` can carry, prefixed the way `opts` prefixes
/// them.
///
/// Empty for an element the design system never renders onto, which is the
/// answer for most of them: a rule on one of those cannot collide with a
/// generated class because no generated class is ever on it.
#[must_use]
pub fn classes_for_element(element: &str, opts: &Emit) -> BTreeSet<String> {
    if element == UNIVERSAL {
        return vocabulary(opts);
    }
    ELEMENT_CLASSES
        .iter()
        .find(|(name, _)| *name == element)
        .map(|(_, classes)| classes.iter().map(|c| crate::class(c, opts)).collect())
        .unwrap_or_default()
}

/// The element key [`declarations_by_element`] files a bare `*` rule under.
///
/// A universal rule reaches every element, so [`classes_for_element`] answers
/// it with the whole vocabulary: `* { padding: 0 }` in a layer after
/// `makeover` zeroes every generated padding, and has to be read as doing so.
pub const UNIVERSAL: &str = "*";

/// The element name of one bare compound arm, if that is what it is.
fn bare_element(arm: &str) -> Option<String> {
    // An attribute value or a `:not()` argument can hold anything, including
    // the spaces and dots this then rejects on. Neither changes which element
    // the arm styles, so both go before the test rather than into it.
    let mut flat = String::with_capacity(arm.len());
    let mut depth = 0usize;
    for c in arm.chars() {
        match c {
            '[' | '(' => depth += 1,
            ']' | ')' => depth = depth.saturating_sub(1),
            _ if depth == 0 => flat.push(c),
            _ => {}
        }
    }
    let flat = flat.trim();
    // A lone universal, bare or under a state (`*`, `*:hover`), reaches every
    // element, so it reaches every described one. `*::before` styles a
    // generated box rather than an element, and `* button` is scoped.
    if let Some(rest) = flat.strip_prefix('*') {
        let bare = !rest.contains(['.', '#', '>', '+', '~', '*'])
            && !rest.chars().any(char::is_whitespace)
            && !rest.contains("::");
        return bare.then(|| UNIVERSAL.to_string());
    }
    // A descendant, a child, a class, an id or a scoped universal: not this.
    if flat.is_empty() || flat.contains(['.', '#', '>', '+', '~', '*']) {
        return None;
    }
    if flat.chars().any(char::is_whitespace) {
        return None;
    }
    let name: String = flat
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '-')
        .collect();
    // A pseudo-element on nothing (`::selection`) or a pseudo-class on nothing
    // (`:root`) names no element.
    if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
        return None;
    }
    Some(name.to_ascii_lowercase())
}

/// The class names one selector matches on.
fn classes_in_selector(selector: &str) -> Vec<String> {
    let chars: Vec<char> = selector.chars().collect();
    let mut names = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        // A leading digit is a length (`.5rem`), never a class: CSS forbids an
        // identifier starting with one.
        if chars[i] == '.'
            && chars
                .get(i + 1)
                .is_some_and(|c| c.is_alphabetic() || *c == '_')
        {
            let start = i + 1;
            let mut end = start;
            while end < chars.len() && is_ident(chars[end]) {
                end += 1;
            }
            names.push(chars[start..end].iter().collect());
            i = end;
        } else {
            i += 1;
        }
    }
    names
}

/// The class names a rule styles an element *by*: every class in the subject
/// of each selector arm, outside a `:not()` or a `:has()`.
///
/// Not [`classes_in_selector`], which is the right answer to "which classes
/// does this sheet mention" and the wrong one to "which classes does this rule
/// set a property on". A rule sets its properties on the element its selector
/// ends at, so only that compound counts:
///
/// - An ancestor is context. `.table-row > .kind-actions { min-inline-size }`
///   styles the cell and never the row, so reading it as a `.table-row`
///   declaration reported a clash with the generated `.table-row` that no
///   element can show. quasi-webview's act-column fold is that selector, and
///   it failed goingson's build with three such clashes.
/// - A `:has()` is a condition on what the element holds. `.row:has(.button)`
///   styles the row, so a class inside it is not one the rule reaches.
/// - A negation's argument is the one place a class stands for the elements a
///   rule refuses: `.group:not(.raised) { box-shadow }` never reaches a raised
///   element. quasi-webview's group box is that selector, and it failed
///   goingson's build with two such clashes.
///
/// `:is()` and `:where()` in the subject match by their arguments, so a class
/// inside one stays counted.
///
/// An arm ending in a pseudo-element reaches no element at all. A pseudo-element
/// comes last in its compound, so `.field::file-selector-button` styles the
/// button box a file input draws and not the input carrying `.field`; filing its
/// border and padding under `field` made every app rule on a bare `input` read
/// as taking a property the generated `.field` sets, and failed goingson's build
/// with clashes no element could show. Such an arm contributes no class, and the
/// other arms of the same list still do. Only the `::` spelling is read, which is
/// the one the generated sheets write.
fn classes_matched_by(selector: &str) -> Vec<String> {
    let subjects: Vec<String> = selector_arms(selector)
        .into_iter()
        .filter(|arm| !arm.contains("::"))
        .map(|arm| without_pseudo(&without_pseudo(subject_of(arm), ":not("), ":has("))
        .collect();
    classes_in_selector(&subjects.join(","))
}

/// The last compound of one selector arm: what follows the final combinator
/// outside any parentheses, brackets or quotes.
fn subject_of(arm: &str) -> &str {
    let arm = arm.trim();
    let start = top_level(arm)
        .filter(|&(_, c)| c.is_whitespace() || matches!(c, '>' | '+' | '~'))
        .last()
        .map_or(0, |(i, c)| i + c.len_utf8());
    &arm[start..]
}

/// `compound` with every `<pseudo>(...)` group taken out, balanced.
fn without_pseudo(compound: &str, pseudo: &str) -> String {
    let mut kept = String::with_capacity(compound.len());
    let mut rest = compound;
    while let Some(at) = rest.find(pseudo) {
        kept.push_str(&rest[..at]);
        let end = matching_close(rest.as_bytes(), at + pseudo.len() - 1, b'(', b')')
            .map_or(rest.len(), |k| k + 1);
        rest = &rest[end..];
    }
    kept.push_str(rest);
    kept
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::list::{cell_part_class, part_class};

    #[test]
    fn a_comment_inside_a_selector_keeps_the_text_around_it() {
        // `.a /* note */ .b` is `.b` inside `.a`, so it is no bare `.b` rule.
        let css = ".a /* note */ .b { color: red }";
        assert!(bare_declarations(css).is_empty());
        assert!(declarations_by_class(css)["b"].contains("color"));
    }

    #[test]
    fn an_arm_is_spelled_one_way_without_changing_what_it_selects() {
        assert_eq!(
            normalize_arm("  .button:is( :disabled ,  [aria-disabled='true'] ) "),
            ".button:is(:disabled,[aria-disabled=\"true\"])"
        );
        assert_eq!(normalize_arm(".table-row  >  .cell"), ".table-row>.cell");
        // A space before a bracket or after a parenthesis is a descendant
        // combinator, and keeping it is the difference between two elements.
        assert_eq!(normalize_arm(".a [data-x]"), ".a [data-x]");
        assert_eq!(normalize_arm(".a:is(.b) .c"), ".a:is(.b) .c");
    }

    #[test]
    fn a_grouped_arm_is_the_arms_it_groups() {
        assert_eq!(
            expand_is(".tab:is(:disabled,[aria-disabled=\"true\"])"),
            vec![".tab:disabled", ".tab[aria-disabled=\"true\"]"]
        );
        // Inside a negation the group is what the arm refuses, not two arms.
        assert_eq!(expand_is(".b:not(:is(.x,.y))"), vec![".b:not(:is(.x,.y))"]);
        assert_eq!(
            expand_is(".card:is(a,button):is(:active,:disabled)").len(),
            4
        );
    }

    #[test]
    fn a_variant_is_any_arm_but_the_bare_class() {
        let css = ".button { color: red; }\n\
                   .button[data-tone=\"danger\"], .run .button { color: blue; }\n\
                   .button::after { content: \"x\"; }\n";
        let variants = variants_by_class(css);
        let arms: Vec<&str> = variants["button"].keys().map(String::as_str).collect();
        assert_eq!(arms, vec![".button[data-tone=\"danger\"]", ".run .button"]);
        let bare = bare_declarations(css);
        assert!(bare["button"].contains("color"));
        assert!(bare_class("button.button").is_none());
        assert!(bare_class(".button.quiet").is_none());
    }

    #[test]
    fn a_quoted_attribute_value_survives_into_the_selector() {
        // Read as `.badge[data-tone=]` before, so no check could tell the
        // danger badge's rule from the success one's.
        let read = rules(".badge[data-tone=\"danger\"] { color: red; }");
        assert_eq!(read.len(), 1, "{read:?}");
        assert!(read[0].0.contains(r#"[data-tone="danger"]"#), "{read:?}");
        // And a quoted value in a declaration still cannot split it.
        let body = rules(r#".a { background: url("a;b:c"); color: red; }"#);
        assert!(body[0].1.contains("color"), "{body:?}");
    }

    #[test]
    fn a_pseudo_element_arm_styles_no_element_carrying_its_class() {
        // The file field's button: its declarations style the chooser box, not
        // the input, so none of them is a `.field` declaration.
        let by_class =
            declarations_by_class(".field::file-selector-button { border: none; padding: 1px; }");
        assert!(!by_class.contains_key("field"), "{by_class:?}");

        // The other arms of a list still reach their elements.
        let mixed = declarations_by_class(".a::before, .b { color: red; }");
        assert!(!mixed.contains_key("a"), "{mixed:?}");
        assert!(
            mixed.get("b").is_some_and(|p| p.contains("color")),
            "{mixed:?}"
        );
    }
    use makeover_layout::{CellPart, Prominence};

    #[test]
    fn the_scrape_finds_the_components_the_sheet_is_built_from() {
        let v = vocabulary(&Emit::default());
        assert!(
            v.len() > 20,
            "scraped {} classes, which reads as a parser failure rather than a small sheet",
            v.len()
        );
        for name in ["card", "tab", "table-heading", "cell-value", "chosen"] {
            assert!(
                v.contains(name),
                "the sheet defines .{name} and the scan missed it"
            );
        }
    }

    #[test]
    fn every_class_this_crate_can_emit_has_a_rule() {
        // wiki `look-restoration`: zero generated classes left unstyled. Before
        // 0.82.0 twenty names in `names` had no rule, on the reading that a
        // wrapper or a state was the app's to style. Nine of them were styled
        // by nothing at all in MNW, including the message a reader sees when a
        // described field refuses their answer. No exception list: a name that
        // truly needs no look is a name this crate should not emit.
        let opts = Emit::default();
        let unruled: Vec<String> = names(&opts)
            .difference(&vocabulary(&opts))
            .cloned()
            .collect();
        assert!(
            unruled.is_empty(),
            "{} class(es) this crate can emit and its sheet never rules: {unruled:?}. \
             Write the rule beside the emitter, or stop emitting the class.",
            unruled.len()
        );
    }

    #[test]
    fn every_name_a_caller_can_ask_for_is_one_this_crate_admits_to() {
        // The two halves of the agreement, checked against each other. A naming
        // function returning a class outside `names` would put a class in the
        // markup that nothing downstream can recognise, which is the failure
        // quasi-webview shipped and phase 1 exists to make impossible.
        let opts = Emit::default();
        let all = names(&opts);

        for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
            let name = option_class(selector);
            assert!(
                all.contains(name),
                "option_class({selector:?}) is .{name}, which nothing admits to"
            );
        }
        for part in [Prominence::Lead, Prominence::Support, Prominence::Quiet] {
            let name = part_class(part);
            assert!(
                all.contains(name),
                "part_class({part:?}) is .{name}, which nothing admits to"
            );
        }
        for part in [
            CellPart::Value,
            CellPart::Tokens,
            CellPart::Actions,
            CellPart::Link,
        ] {
            let name = cell_part_class(part);
            assert!(
                all.contains(name),
                "cell_part_class({part:?}) is .{name}, which nothing admits to"
            );
        }
    }

    #[test]
    fn the_part_lists_hold_every_arm_of_the_match_beside_them() {
        // ROW_PART_CLASSES and CELL_PART_CLASSES are written out because a
        // `#[non_exhaustive]` enum cannot be enumerated. This is the test that
        // stops them drifting from the matches they sit next to.
        for part in [Prominence::Lead, Prominence::Support, Prominence::Quiet] {
            assert!(
                ROW_PART_CLASSES.contains(&part_class(part)),
                "{part:?} is missing from ROW_PART_CLASSES"
            );
        }
        for part in [
            CellPart::Value,
            CellPart::Tokens,
            CellPart::Actions,
            CellPart::Link,
        ] {
            assert!(
                CELL_PART_CLASSES.contains(&cell_part_class(part)),
                "{part:?} is missing from CELL_PART_CLASSES"
            );
        }
        // The fallbacks, which are what an upstream addition lands on.
        assert!(ROW_PART_CLASSES.contains(&"row-part"));
        assert!(CELL_PART_CLASSES.contains(&"cell-part"));
    }

    #[test]
    fn a_prefix_moves_the_component_classes_and_leaves_the_states_qualifying_them() {
        let plain = vocabulary(&Emit::default());
        let prefixed = vocabulary(&Emit {
            class_prefix: "mo-",
            ..Emit::default()
        });
        assert_eq!(
            plain.len(),
            prefixed.len(),
            "a prefix changed how many classes exist"
        );
        // `chosen` and `latched` never stand alone: the sheet writes
        // `.mo-tab.chosen`, so the state stays bare while the thing moves.
        // `current` is the third, and it is the same shape: which child of a
        // region showing one at a time is the one showing.
        // A field's two, `has-error` and `visible`, are the same shape, and
        // reach the scrape once the sheet rules them.
        let states = ["chosen", "latched", "current"];
        for name in &plain {
            let expected = if states.contains(&name.as_str())
                || FIELD_STATE_CLASSES.contains(&name.as_str())
            {
                name.clone()
            } else {
                format!("mo-{name}")
            };
            assert!(
                prefixed.contains(&expected),
                ".{name} did not move to .{expected} under the prefix"
            );
        }
    }

    #[test]
    fn a_handoff_is_not_an_override() {
        // The defect this split fixes. `revert-layer` in a later layer gives
        // the property back to the design system, so counting it as a taking
        // made every remedy in a consumer's sheet read as the thing it
        // remedied, and the allowlist entry written to silence one went on
        // permitting a real override on the same pair for good.
        let css = ".button { background: revert-layer; color: red; }";
        let taken = declarations_by_class(css);
        let given = deferrals_by_class(css);
        assert_eq!(
            taken.get("button"),
            Some(&["color".to_string()].into_iter().collect())
        );
        assert_eq!(
            given.get("button"),
            Some(&["background".to_string()].into_iter().collect())
        );
    }

    #[test]
    fn an_important_handoff_is_an_override() {
        // `revert-layer !important` in a later layer inverts layer order and
        // takes the property from every layer below it. Same word, opposite
        // declaration, and the one shape of it this reader must not wave
        // through.
        let css = ".button { background: revert-layer !important; }";
        assert_eq!(
            declarations_by_class(css).get("button"),
            Some(&["background".to_string()].into_iter().collect())
        );
        assert!(!deferrals_by_class(css).contains_key("button"));
    }

    #[test]
    fn a_class_that_only_hands_properties_back_is_not_in_the_taking_set() {
        // An empty entry would read as "this class collides on nothing", which
        // is true, and as "this class is in the map", which is what a caller
        // iterating the map would act on.
        let by_class = declarations_by_class(".field { background: revert-layer; }");
        assert!(!by_class.contains_key("field"), "got {by_class:?}");
    }

    #[test]
    fn an_element_rule_is_read_where_a_class_reader_sees_nothing() {
        let css = "button { color: red; background: blue; }";
        assert!(declarations_by_class(css).is_empty());
        let by_element = declarations_by_element(css);
        let button = by_element.get("button").expect("button is named");
        assert_eq!(
            button.keys().cloned().collect::<Vec<_>>(),
            ["background", "color"]
        );
        // One element, nothing else: (0, 0, 1).
        assert_eq!(button["color"], (0, 0, 1));
    }

    #[test]
    fn the_strongest_arm_is_the_one_reported() {
        // A remedy has to outrank the rule it remedies, so a reader that kept
        // the weakest arm would call a losing handoff sufficient.
        let css = "input { color: red; }\ninput[type=\"text\"]:focus { color: blue; }\n";
        assert_eq!(declarations_by_element(css)["input"]["color"], (0, 2, 1));
    }

    #[test]
    fn a_selector_is_ranked_the_way_the_cascade_ranks_it() {
        for (selector, expected) in [
            ("button", (0, 0, 1)),
            ("*", (0, 0, 0)),
            (".field", (0, 1, 0)),
            ("input.field", (0, 1, 1)),
            ("input[type=\"text\"]", (0, 1, 1)),
            ("button:hover", (0, 1, 1)),
            ("button::before", (0, 0, 2)),
            ("#main .card > button:focus-visible", (1, 2, 1)),
            (".chip.latched[aria-pressed=\"true\"]", (0, 3, 0)),
            ("button:not(.link)", (0, 1, 1)),
        ] {
            assert_eq!(specificity(selector), expected, "{selector}");
        }
    }

    #[test]
    fn what_a_class_is_spoken_for_by_counts_a_handoff_as_speech() {
        // A handoff takes nothing, so `declarations_by_class` is right to drop
        // it, and it is still the app saying what happens to that property on
        // that class, which is what this reader is for.
        let css = ".field { background: revert-layer; }\ninput.field:focus { color: red; }\n";
        let mentions = mentions_by_class(css);
        assert_eq!(mentions["field"]["background"], (0, 1, 0));
        assert_eq!(mentions["field"]["color"], (0, 2, 1));
    }

    #[test]
    fn only_a_bare_compound_counts_as_an_element_rule() {
        // Each of these styles a `button` and none of them is the certain
        // case. A scoped arm reaches one region, and an arm carrying a class
        // is the class reader's business, not this one's.
        for selector in [
            ".page button",
            "button.link",
            ".card > button",
            "button + button",
            "* button",
        ] {
            let css = format!("{selector} {{ color: red; }}");
            assert!(
                declarations_by_element(&css).is_empty(),
                "{selector} was read as a bare element rule"
            );
        }
    }

    #[test]
    fn a_state_or_an_attribute_does_not_stop_an_arm_being_bare() {
        // All of these reach every button in the document, which is what makes
        // them certain to reach a described one.
        for selector in [
            "button:hover",
            "button:focus-visible",
            "button:disabled",
            "button[aria-disabled=\"true\"]",
            "button:not(.link)",
            "button[data-tone=\"danger\"]:hover",
        ] {
            let css = format!("{selector} {{ color: red; }}");
            assert!(
                declarations_by_element(&css).contains_key("button"),
                "{selector} was not read as a bare element rule"
            );
        }
    }

    #[test]
    fn a_universal_rule_reaches_every_generated_class() {
        for selector in ["*", "*:hover", "*:not(svg)"] {
            let css = format!("{selector} {{ padding: 0; }}");
            assert!(
                declarations_by_element(&css).contains_key(UNIVERSAL),
                "{selector} was not read as reaching every element"
            );
        }
        for selector in ["*::before", "* button", ".page *", "*.card"] {
            let css = format!("{selector} {{ padding: 0; }}");
            assert!(
                !declarations_by_element(&css).contains_key(UNIVERSAL),
                "{selector} was read as reaching every element"
            );
        }
        let opts = Emit::default();
        assert_eq!(classes_for_element(UNIVERSAL, &opts), vocabulary(&opts));
    }

    #[test]
    fn a_pseudo_element_on_nothing_names_no_element() {
        for selector in [":root", "::selection", "::backdrop", ":root:not(.x)"] {
            let css = format!("{selector} {{ color: red; }}");
            assert!(
                declarations_by_element(&css).is_empty(),
                "{selector} named an element"
            );
        }
    }

    #[test]
    fn every_arm_of_a_list_is_read_on_its_own() {
        let css = "input, select, .field, .page textarea { color: red; }";
        let by_element = declarations_by_element(css);
        assert!(by_element.contains_key("input"));
        assert!(by_element.contains_key("select"));
        assert!(!by_element.contains_key("textarea"), "that arm is scoped");
        assert_eq!(by_element.len(), 2);
    }

    #[test]
    fn a_comma_inside_a_group_does_not_split_the_list() {
        // `.card:is(a, button)` is a class-qualified rule. Split on every comma
        // it reads as a bare `button` rule, and a consumer scoping the pointer
        // cursor to a pressable card fails its build for doing it right.
        let css = ".card:is(a, button, label, [data-act]) { cursor: pointer; }\n\
                   a[title=\"x, y\"], button { color: red; }";
        let by_element = declarations_by_element(css);
        assert!(!by_element.contains_key("label"), "{by_element:?}");
        assert!(
            !by_element["button"].contains_key("cursor"),
            "{by_element:?}"
        );
        assert!(by_element["a"].contains_key("color"), "{by_element:?}");
        assert!(by_element["button"].contains_key("color"), "{by_element:?}");
        assert_eq!(
            mentions_by_class(css)["card"]["cursor"],
            specificity(".card:is(a, button, label, [data-act])")
        );
    }

    #[test]
    fn an_element_handing_a_property_back_is_not_taking_it() {
        let css = "button { background: revert-layer; }";
        assert!(declarations_by_element(css).is_empty());
    }

    #[test]
    fn the_pairing_map_carries_the_elements_this_crate_renders_onto() {
        // The map is hand-written and the emitters are not, so this is what
        // stops the two drifting. Every `<tag class="...">` in this crate's own
        // source, for a tag the map claims to cover, has to be a pairing the
        // map declares, or the check reads a smaller world than the renderer
        // writes and the gap is silent.
        let mut checked = 0;
        for (tag, class) in emitted_pairs() {
            if !ELEMENT_CLASSES.iter().any(|(name, _)| *name == tag) {
                continue;
            }
            checked += 1;
            assert!(
                classes_for_element(&tag, &Emit::default()).contains(&class),
                "this crate emits <{tag} class=\"{class}\"> and ELEMENT_CLASSES \
                 does not pair them"
            );
        }
        // A facet's controls are a tag its caller picks, so they are declared
        // by hand under both `a` and `button` and are not literals here.
        assert!(
            checked > 3,
            "scraped {checked} pairings off the emitters, which reads as the scan \
             having stopped matching rather than the renderer having shrunk"
        );
    }

    /// `(element, class)` for every literal `<tag class="...">` this crate's
    /// own source emits.
    ///
    /// Source rather than rendered markup, because an emitter no test happens
    /// to call is exactly the one whose pairing nobody wrote down. A class
    /// built at runtime (an option class, a row part) is not a literal and is
    /// not seen here; those are declared in the map by hand.
    fn emitted_pairs() -> Vec<(String, String)> {
        const OPEN: &str = "class=\\\"";
        let mut out = Vec::new();
        for file in std::fs::read_dir("src").expect("read src") {
            let path = file.expect("dir entry").path();
            if path.extension().is_none_or(|e| e != "rs") {
                continue;
            }
            let src = std::fs::read_to_string(&path).expect("read source");
            for (at, _) in src.match_indices(OPEN) {
                // The tag is the last `<name` before the attribute.
                let Some(open) = src[..at].rfind('<') else {
                    continue;
                };
                let tag: String = src[open + 1..]
                    .chars()
                    .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
                    .collect();
                if tag.is_empty() {
                    continue;
                }
                // What is pushed next: `push_class(out, "name", opts)`.
                let tail = &src[at..(at + 300).min(src.len())];
                let Some(call) = tail.find("push_class(out, \"") else {
                    continue;
                };
                let name: String = tail[call + "push_class(out, \"".len()..]
                    .chars()
                    .take_while(|c| *c != '"')
                    .collect();
                if !name.is_empty() {
                    out.push((tag, name));
                }
            }
        }
        out
    }

    #[test]
    fn the_properties_a_class_carries_are_read_per_class() {
        let css = ".badge { padding: 1px; font-weight: 600; }\n                   .badge[data-color] { border: 1px solid red; }\n                   @media (min-width: 40rem) { .badge { padding: 2px; } }\n";
        let by_class = declarations_by_class(css);
        let badge = by_class.get("badge").expect("badge is named");
        // Every arm collapses into one entry, including the one inside the
        // media block: they are all the same class carrying the same property.
        assert!(badge.contains("padding"));
        assert!(badge.contains("font-weight"));
        assert!(badge.contains("border"));
        assert_eq!(badge.len(), 3);
    }

    #[test]
    fn a_value_holding_a_colon_or_a_semicolon_is_not_read_as_a_property() {
        let css = ".x { background: url(\"a;b:c\"); color: red; }";
        let by_class = declarations_by_class(css);
        let x = by_class.get("x").expect("x is named");
        assert_eq!(
            *x,
            ["background".to_string(), "color".to_string()]
                .into_iter()
                .collect::<BTreeSet<_>>()
        );
    }

    #[test]
    fn the_generated_sheet_draws_a_badge_as_a_chip() {
        // wiki `table-model`: a badge is a chip, fill and edge and ink, drawn by
        // the renderer, so an app stylesheet has nothing of it left to state.
        // A property-grain reader is what turns that into a check.
        let by_class = declarations_by_class(&crate::stylesheet(&Emit::default()));
        let badge = by_class.get("badge").expect("the sheet defines .badge");
        for property in ["color", "background", "border", "padding"] {
            assert!(badge.contains(property), "no {property}, got {badge:?}");
        }
    }

    #[test]
    fn a_declaration_value_holding_a_dot_is_not_read_as_a_class() {
        let found = classes_in_css(".real { transition: .2s ease; margin: 0.5rem; }");
        assert_eq!(found, ["real".to_string()].into_iter().collect());
    }

    #[test]
    fn an_at_rule_does_not_hide_the_selectors_inside_it() {
        let found = classes_in_css(
            "@layer makeover { @media (min-width: 40rem) { .wide { color: red; } } }",
        );
        assert_eq!(found, ["wide".to_string()].into_iter().collect());
    }

    #[test]
    fn an_attribute_is_read_with_and_without_its_pinned_value() {
        // `data-tone` answers "does any rule select on it" and
        // `data-tone=danger` answers "does any rule pin this value"; both are
        // what a reverse check asks.
        let found = attributes_in_css(
            ".badge[data-tone=\"danger\"] { color: red; }\n[hidden] { display: none; }\n\
             .row[aria-sort=\"ascending\" i] { color: blue; }",
        );
        let expected: BTreeSet<String> = [
            "data-tone",
            "data-tone=danger",
            "hidden",
            "aria-sort",
            "aria-sort=ascending",
        ]
        .into_iter()
        .map(String::from)
        .collect();
        assert_eq!(found, expected);
    }

    #[test]
    fn a_declaration_value_is_not_read_as_a_selected_attribute() {
        // `content` appears only inside a declaration body, never in a
        // selector, so it is not something the sheet selects on.
        let found = attributes_in_css(".caret::after { content: \"\u{25B2}\"; }");
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn a_nested_rule_is_a_rule_of_its_own() {
        // Inside a declaration block a `{` opens a nested rule, not a second
        // declaration, so its declarations land on the class it names rather
        // than slipping past the drift check.
        let by_class = declarations_by_class(".page { color: red; .button { background: blue; } }");
        assert!(by_class["page"].contains("color"), "{by_class:?}");
        assert!(by_class["button"].contains("background"), "{by_class:?}");
    }

    #[test]
    fn a_nested_rule_with_an_ampersand_is_read() {
        let descendant = declarations_by_class(".page { & .button { background: blue; } }");
        assert!(
            descendant["button"].contains("background"),
            "{descendant:?}"
        );
        // `&.button` is the parent element that also carries the class, and
        // `&:disabled` the parent in a state: both reach the class.
        let compound = declarations_by_class(".page { &.button { color: red; } }");
        assert!(compound["button"].contains("color"), "{compound:?}");
        let state = declarations_by_class(".page { &:disabled { color: red; } }");
        assert!(state["page"].contains("color"), "{state:?}");
    }

    #[test]
    fn a_nested_rule_stays_scoped_to_its_parent() {
        // `.page .button` reaches fewer buttons than a bare `.button`, so it
        // must not read as the bare-class rule that beats every variant.
        let css = ".page { .button { background: blue; } }";
        assert!(
            !bare_declarations(css).contains_key("button"),
            "a scoped rule is not a bare one: {:?}",
            bare_declarations(css)
        );
        assert_eq!(
            variants_by_class(css)["button"].keys().collect::<Vec<_>>(),
            vec![".page .button"]
        );
    }

    #[test]
    fn a_property_name_is_read_without_regard_to_case() {
        let by_class = declarations_by_class(".card { BOX-SHADOW: none; }");
        assert!(by_class["card"].contains("box-shadow"), "{by_class:?}");
        // A custom property is case-sensitive and keeps its spelling.
        let custom = declarations_by_class(".card { --Gap: 1px; }");
        assert!(custom["card"].contains("--Gap"), "{custom:?}");
    }

    #[test]
    fn a_string_is_opaque_and_a_comment_contributes_nothing() {
        let found = classes_in_css("/* .notaclass */ .caret::after { content: \"} .alsonot\"; }");
        assert_eq!(found, ["caret".to_string()].into_iter().collect());
    }

    #[test]
    fn a_compound_selector_yields_every_class_it_names() {
        let found = classes_in_css(
            ".tab.chosen[aria-sort=\"ascending\"] > .label:not(.muted) { color: red; }",
        );
        let expected: BTreeSet<String> = ["tab", "chosen", "label", "muted"]
            .into_iter()
            .map(String::from)
            .collect();
        assert_eq!(found, expected);
    }

    #[test]
    fn a_class_a_rule_refuses_is_not_a_class_it_styles() {
        let css = ".region:not(.group) > .region.group:not(.raised):not(.tiles) > \
                   .heading:first-child { background: var(--surface-raised); }\n\
                   .row:is(.chosen):has(.badge) { color: red; }";
        let declared = declarations_by_class(css);
        for refused in ["raised", "tiles"] {
            assert!(!declared.contains_key(refused), "{refused} is only negated");
            assert!(!mentions_by_class(css).contains_key(refused));
        }
        for reached in ["heading", "row", "chosen"] {
            assert!(declared.contains_key(reached), "{reached} is matched on");
        }
        // An ancestor is context and a `:has()` is a condition: neither is the
        // element the declarations land on.
        for context in ["region", "group", "badge"] {
            assert!(!declared.contains_key(context), "{context} is not styled");
        }
        // Still a mention of the sheet's vocabulary, which is the other question.
        assert!(classes_in_css(css).contains("raised"));
    }

    /// quasi-webview's act-column fold, which failed goingson's build with
    /// three clashes no element could show: every declaration lands on the
    /// cell or the menu, never on the row or the actions strip it names.
    #[test]
    fn a_rule_styles_its_subject_and_not_its_context() {
        let css = ".table-row:has(> .table-menu .table-row-menu[open]) > \
                   .kind-actions:not(.table-menu) { min-inline-size: 10rem; }\n\
                   .table-row:has(> .kind-actions .cell-actions > *) > .table-menu \
                   .table-row-menu:not(:has(> .row-menu-items > *)) { display: block; }";
        let declared = declarations_by_class(css);
        assert_eq!(
            declared.keys().map(String::as_str).collect::<Vec<_>>(),
            ["kind-actions", "table-row-menu"],
            "{declared:?}"
        );
    }

    #[test]
    fn a_nested_negation_is_skipped_whole() {
        assert_eq!(
            classes_matched_by(".a:not(:is(.b, .c)) .d"),
            ["d".to_string()]
        );
    }
}