noxid-css-ir 0.2.0

The css-ir component of the Noxid compiler
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
//! CSS accuracy: the view is the oracle.
//!
//! A component `style` block is checked against the compiler-visible view
//! tree of the same component. Everything this module refuses is provable
//! from the block plus the view — nothing is inferred from runtime layout,
//! and nothing that the compiler cannot resolve (a `var()`, a `token()`, a
//! bound `class`) is ever guessed at. A wrong-but-silent stylesheet is the
//! CSS half of the wrong-but-silent compile.

use crate::{Keyframe, StyleAtRuleBlock, StyleDeclaration, StyleRule};
use noxid_css_syntax::properties::{PropertyLookup, table};
use noxid_ir::{ComponentDefinition, SemanticAttribute, SemanticId, SemanticViewNode};
use noxid_source::{Diagnostic, Span};
use std::collections::{BTreeMap, BTreeSet};

/// One element the component's view can render, in some branch.
#[derive(Clone, Debug)]
struct ViewElement {
    tag: String,
    classes: BTreeSet<String>,
    id: Option<String>,
    attributes: BTreeSet<String>,
    /// A bound `class`/`id` makes the element's identity unknown at compile
    /// time; unknown never refuses.
    opaque_class: bool,
    opaque_id: bool,
    parent: Option<usize>,
}

#[derive(Default)]
struct ViewModel {
    elements: Vec<ViewElement>,
}

impl ViewModel {
    fn collect(nodes: &[SemanticViewNode]) -> Self {
        let mut model = Self::default();
        model.walk(nodes, None);
        model
    }

    // Exhaustive on SemanticViewNode: a new variant with element children
    // that is dropped here would silently stop the view being the oracle.
    fn walk(&mut self, nodes: &[SemanticViewNode], parent: Option<usize>) {
        for node in nodes {
            match node {
                SemanticViewNode::Element {
                    tag,
                    attributes,
                    children,
                    ..
                } => {
                    let index = self.elements.len();
                    let mut element = ViewElement {
                        tag: tag.to_ascii_lowercase(),
                        classes: BTreeSet::new(),
                        id: None,
                        attributes: BTreeSet::new(),
                        opaque_class: false,
                        opaque_id: false,
                        parent,
                    };
                    for attribute in attributes {
                        match attribute {
                            SemanticAttribute::Static { name, value, .. } => {
                                let lowered = name.to_ascii_lowercase();
                                element.attributes.insert(lowered.clone());
                                match lowered.as_str() {
                                    "class" => element
                                        .classes
                                        .extend(value.split_whitespace().map(str::to_string)),
                                    "id" => element.id = Some(value.trim().to_string()),
                                    _ => {}
                                }
                            }
                            SemanticAttribute::Binding { name, .. }
                            | SemanticAttribute::TwoWayBinding { name, .. }
                            | SemanticAttribute::Event { name, .. } => {
                                let lowered = name.to_ascii_lowercase();
                                element.attributes.insert(lowered.clone());
                                match lowered.as_str() {
                                    "class" => element.opaque_class = true,
                                    "id" => element.opaque_id = true,
                                    _ => {}
                                }
                            }
                        }
                    }
                    self.elements.push(element);
                    self.walk(children, Some(index));
                }
                SemanticViewNode::ComponentInvocation { children, .. } => {
                    // Invocation children render in this component's scope,
                    // so they are ours; the invoked component's own elements
                    // carry its scope and are checked against its own block.
                    self.walk(children, parent);
                }
                SemanticViewNode::Conditional { children, .. }
                | SemanticViewNode::For { children, .. } => self.walk(children, parent),
                SemanticViewNode::Match { cases, .. } | SemanticViewNode::Stream { cases, .. } => {
                    for case in cases {
                        self.walk(&case.children, parent);
                    }
                }
                SemanticViewNode::Text { .. }
                | SemanticViewNode::Binding { .. }
                | SemanticViewNode::Slot { .. } => {}
            }
        }
    }

    fn siblings(&self, index: usize) -> Vec<usize> {
        let parent = self.elements[index].parent;
        (0..self.elements.len())
            .filter(|candidate| *candidate != index && self.elements[*candidate].parent == parent)
            .collect()
    }

    fn ancestors(&self, index: usize) -> Vec<usize> {
        let mut output = Vec::new();
        let mut cursor = self.elements[index].parent;
        while let Some(current) = cursor {
            output.push(current);
            cursor = self.elements[current].parent;
        }
        output
    }

    /// Every way a reader could name an element this view renders, for the
    /// teaching half of `CSS_UNUSED_SELECTOR`.
    fn descriptors(&self) -> Vec<String> {
        let mut output = BTreeSet::new();
        for element in &self.elements {
            output.insert(element.tag.clone());
            for class in &element.classes {
                output.insert(format!(".{class}"));
            }
            if let Some(id) = &element.id {
                output.insert(format!("#{id}"));
            }
        }
        output.into_iter().collect()
    }
}

// ---------------------------------------------------------------------
// Selector model
// ---------------------------------------------------------------------

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Combinator {
    Descendant,
    Child,
    NextSibling,
    LaterSibling,
}

#[derive(Clone, Debug, Default)]
struct Compound {
    tag: Option<String>,
    classes: Vec<String>,
    ids: Vec<String>,
    attributes: Vec<String>,
    pseudo_classes: usize,
    pseudo_elements: usize,
    universal: bool,
}

#[derive(Clone, Debug)]
struct Complex {
    /// Right-most compound first, each paired with the combinator that
    /// joins it to the compound that follows in this list.
    steps: Vec<(Compound, Option<Combinator>)>,
    global: bool,
}

/// `(ids, classes and attributes and pseudo-classes, tags and pseudo-elements)`
type Specificity = (usize, usize, usize);

impl Complex {
    fn specificity(&self) -> Specificity {
        self.steps.iter().fold((0, 0, 0), |total, (compound, _)| {
            (
                total.0 + compound.ids.len(),
                total.1
                    + compound.classes.len()
                    + compound.attributes.len()
                    + compound.pseudo_classes,
                total.2 + usize::from(compound.tag.is_some()) + compound.pseudo_elements,
            )
        })
    }

    fn has_pseudo(&self) -> bool {
        self.steps
            .iter()
            .any(|(compound, _)| compound.pseudo_classes + compound.pseudo_elements > 0)
    }
}

fn parse_selector_list(selector: &str) -> Vec<(String, Complex)> {
    split_top_level(selector, ',')
        .into_iter()
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .map(|part| (part.to_string(), parse_complex(part)))
        .collect()
}

fn parse_complex(selector: &str) -> Complex {
    let global = selector.contains(":global(");
    let mut steps: Vec<(Compound, Option<Combinator>)> = Vec::new();
    let mut buffer = String::new();
    let mut pending: Option<Combinator> = None;
    let mut paren = 0usize;
    let mut bracket = 0usize;
    let mut quote: Option<char> = None;
    let mut chars = selector.chars().peekable();
    let flush = |buffer: &mut String,
                 steps: &mut Vec<(Compound, Option<Combinator>)>,
                 combinator: Option<Combinator>| {
        let trimmed = buffer.trim().to_string();
        buffer.clear();
        if trimmed.is_empty() {
            return;
        }
        steps.push((parse_compound(&trimmed), combinator));
    };
    while let Some(ch) = chars.next() {
        if let Some(active) = quote {
            buffer.push(ch);
            if ch == active {
                quote = None;
            }
            continue;
        }
        match ch {
            '\'' | '"' => {
                quote = Some(ch);
                buffer.push(ch);
            }
            '(' => {
                paren += 1;
                buffer.push(ch);
            }
            ')' => {
                paren = paren.saturating_sub(1);
                buffer.push(ch);
            }
            '[' => {
                bracket += 1;
                buffer.push(ch);
            }
            ']' => {
                bracket = bracket.saturating_sub(1);
                buffer.push(ch);
            }
            '>' | '+' | '~' if paren == 0 && bracket == 0 => {
                flush(&mut buffer, &mut steps, pending.take());
                pending = Some(match ch {
                    '>' => Combinator::Child,
                    '+' => Combinator::NextSibling,
                    _ => Combinator::LaterSibling,
                });
            }
            _ if ch.is_whitespace() && paren == 0 && bracket == 0 => {
                if !buffer.trim().is_empty() {
                    // A combinator may still follow; look ahead past spaces.
                    let mut lookahead = chars.clone();
                    let mut next = lookahead.next();
                    while matches!(next, Some(candidate) if candidate.is_whitespace()) {
                        next = lookahead.next();
                    }
                    if matches!(next, Some('>') | Some('+') | Some('~')) {
                        continue;
                    }
                    flush(&mut buffer, &mut steps, pending.take());
                    pending = Some(Combinator::Descendant);
                }
            }
            _ => buffer.push(ch),
        }
    }
    flush(&mut buffer, &mut steps, pending.take());
    // Reverse into right-most-first order, moving each combinator onto the
    // compound it binds to its left neighbour.
    let mut ordered: Vec<(Compound, Option<Combinator>)> = Vec::new();
    for index in (0..steps.len()).rev() {
        let combinator = steps[index].1;
        ordered.push((steps[index].0.clone(), combinator));
    }
    Complex {
        steps: ordered,
        global,
    }
}

fn parse_compound(text: &str) -> Compound {
    let mut compound = Compound::default();
    let chars = text.chars().collect::<Vec<_>>();
    let mut index = 0usize;
    let mut tag = String::new();
    while index < chars.len() {
        match chars[index] {
            '*' => {
                compound.universal = true;
                index += 1;
            }
            '.' => {
                index += 1;
                compound.classes.push(read_identifier(&chars, &mut index));
            }
            '#' => {
                index += 1;
                compound.ids.push(read_identifier(&chars, &mut index));
            }
            '[' => {
                let start = index + 1;
                let mut depth = 1usize;
                index += 1;
                while index < chars.len() && depth > 0 {
                    match chars[index] {
                        '[' => depth += 1,
                        ']' => depth -= 1,
                        _ => {}
                    }
                    index += 1;
                }
                let inner = chars[start..index.saturating_sub(1)]
                    .iter()
                    .collect::<String>();
                let name = inner
                    .split(['=', '~', '|', '^', '$', '*'])
                    .next()
                    .unwrap_or("")
                    .trim()
                    .to_ascii_lowercase();
                compound.attributes.push(name);
            }
            ':' => {
                let double = chars.get(index + 1) == Some(&':');
                index += if double { 2 } else { 1 };
                let _name = read_identifier(&chars, &mut index);
                if chars.get(index) == Some(&'(') {
                    let mut depth = 1usize;
                    index += 1;
                    while index < chars.len() && depth > 0 {
                        match chars[index] {
                            '(' => depth += 1,
                            ')' => depth -= 1,
                            _ => {}
                        }
                        index += 1;
                    }
                }
                if double {
                    compound.pseudo_elements += 1;
                } else {
                    compound.pseudo_classes += 1;
                }
            }
            ch if ch.is_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() => {
                tag.push(ch);
                index += 1;
            }
            _ => index += 1,
        }
    }
    if !tag.is_empty() {
        compound.tag = Some(tag.to_ascii_lowercase());
    }
    compound
}

fn read_identifier(chars: &[char], index: &mut usize) -> String {
    let start = *index;
    while *index < chars.len() {
        let ch = chars[*index];
        if ch.is_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() {
            *index += 1;
        } else if ch == '\\' && *index + 1 < chars.len() {
            *index += 2;
        } else {
            break;
        }
    }
    chars[start..*index].iter().collect()
}

/// `Possible` treats a bound `class`/`id` as "could be anything", so the
/// unused-selector check never refuses a selector a runtime value might
/// satisfy. `Certain` treats it as "not this", so the shadowing and nesting
/// checks only reason about elements the compiler can actually see.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MatchMode {
    Possible,
    Certain,
}

fn compound_matches(compound: &Compound, element: &ViewElement, mode: MatchMode) -> bool {
    if let Some(tag) = &compound.tag
        && tag != &element.tag
    {
        return false;
    }
    let opaque_class = element.opaque_class && mode == MatchMode::Possible;
    let opaque_id = element.opaque_id && mode == MatchMode::Possible;
    for class in &compound.classes {
        if !opaque_class && !element.classes.contains(class) {
            return false;
        }
    }
    for id in &compound.ids {
        if opaque_id {
            continue;
        }
        if element.id.as_deref() != Some(id.as_str()) {
            return false;
        }
    }
    for attribute in &compound.attributes {
        if attribute.is_empty() || attribute.starts_with("data-noxid-") {
            continue;
        }
        if !element.attributes.contains(attribute) {
            return false;
        }
    }
    true
}

fn matches_from(
    model: &ViewModel,
    complex: &Complex,
    step: usize,
    index: usize,
    mode: MatchMode,
) -> bool {
    let Some((compound, combinator)) = complex.steps.get(step) else {
        return true;
    };
    if !compound_matches(compound, &model.elements[index], mode) {
        return false;
    }
    let Some(combinator) = combinator else {
        return complex.steps.len() == step + 1
            || matches_from(model, complex, step + 1, index, mode);
    };
    let candidates = match combinator {
        Combinator::Descendant => model.ancestors(index),
        Combinator::Child => model.elements[index].parent.into_iter().collect(),
        Combinator::NextSibling | Combinator::LaterSibling => model.siblings(index),
    };
    candidates
        .into_iter()
        .any(|candidate| matches_from(model, complex, step + 1, candidate, mode))
}

fn matched_elements(model: &ViewModel, complex: &Complex, mode: MatchMode) -> BTreeSet<usize> {
    (0..model.elements.len())
        .filter(|index| matches_from(model, complex, 0, *index, mode))
        .collect()
}

// ---------------------------------------------------------------------
// The checks
// ---------------------------------------------------------------------

/// A flattened qualified rule with the context it lives in.
struct FlatRule {
    id: SemanticId,
    selector: String,
    selector_span: Span,
    context: String,
    /// Elements this rule could match, bound `class`/`id` included.
    matched: BTreeSet<usize>,
    /// Elements this rule provably matches.
    certain: BTreeSet<usize>,
    specificity: Specificity,
    has_pseudo: bool,
    declarations: Vec<StyleDeclaration>,
}

pub(crate) fn check(
    component: &ComponentDefinition,
    rules: &[StyleRule],
    vocabulary: &Vocabulary,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let model = ViewModel::collect(&component.view);
    let style_id = SemanticId::style(&component.name);
    let mut flat = Vec::new();
    visit_rules(
        &model,
        rules,
        "",
        &mut flat,
        diagnostics,
        &style_id,
        vocabulary,
    );
    check_unused(&model, &flat, diagnostics);
    check_shadowing(&flat, diagnostics);
    check_nesting(&model, &flat, diagnostics);
}

#[allow(clippy::too_many_arguments)]
fn visit_rules(
    model: &ViewModel,
    rules: &[StyleRule],
    context: &str,
    flat: &mut Vec<FlatRule>,
    diagnostics: &mut Vec<Diagnostic>,
    style_id: &SemanticId,
    vocabulary: &Vocabulary,
) {
    for rule in rules {
        match rule {
            StyleRule::Qualified {
                id,
                selector,
                declarations,
                span,
                ..
            } => {
                check_declarations(declarations, id, diagnostics);
                check_strict_declarations(vocabulary, declarations, diagnostics);
                check_contrast(vocabulary, selector, declarations, diagnostics);
                let parsed = parse_selector_list(selector);
                let global = parsed.iter().any(|(_, complex)| complex.global);
                let mut matched = BTreeSet::new();
                let mut certain = BTreeSet::new();
                let mut specificity = (0, 0, 0);
                let mut has_pseudo = false;
                for (_, complex) in &parsed {
                    matched.extend(matched_elements(model, complex, MatchMode::Possible));
                    certain.extend(matched_elements(model, complex, MatchMode::Certain));
                    specificity = specificity.max(complex.specificity());
                    has_pseudo |= complex.has_pseudo();
                }
                flat.push(FlatRule {
                    id: id.clone(),
                    selector: selector.clone(),
                    selector_span: *span,
                    context: context.to_string(),
                    matched: if global { BTreeSet::new() } else { matched },
                    certain: if global { BTreeSet::new() } else { certain },
                    specificity,
                    has_pseudo: has_pseudo || global,
                    declarations: declarations.clone(),
                });
            }
            StyleRule::AtRule {
                name,
                prelude,
                block,
                ..
            } => {
                // The strict width-query check runs during lowering, against
                // the prelude the author wrote, before `token(md)` resolves.
                let nested = format!("{context}@{name} {}|", prelude.trim());
                match block {
                    Some(StyleAtRuleBlock::Rules(rules)) => visit_rules(
                        model,
                        rules,
                        &nested,
                        flat,
                        diagnostics,
                        style_id,
                        vocabulary,
                    ),
                    Some(StyleAtRuleBlock::Declarations(declarations)) => {
                        check_declarations(declarations, style_id, diagnostics);
                        check_strict_declarations(vocabulary, declarations, diagnostics);
                    }
                    None => {}
                }
            }
            StyleRule::Keyframes { id, frames, .. } => {
                for Keyframe { declarations, .. } in frames {
                    check_declarations(declarations, id, diagnostics);
                    check_strict_declarations(vocabulary, declarations, diagnostics);
                }
            }
        }
    }
}

fn check_declarations(
    declarations: &[StyleDeclaration],
    owner: &SemanticId,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let table = table();
    for declaration in declarations {
        if declaration.important {
            diagnostics.push(
                Diagnostic::error(
                    "CSS_IMPORTANT_FORBIDDEN",
                    format!(
                        "`!important` is not allowed on `{}` in a component style block; scoping already isolates this component's rules, so `!important` can only hide a specificity mistake. Delete `!important`, and if the rule really must win, give its selector the specificity it needs.",
                        declaration.name
                    ),
                    declaration.span,
                )
                .with_symbol(declaration.id.to_string()),
            );
        }
        match table.lookup(&declaration.name) {
            PropertyLookup::Known(def) => {
                if let Err(rejection) = table.check_value(def, &declaration.value) {
                    diagnostics.push(
                        Diagnostic::error(
                            "CSS_INVALID_VALUE",
                            format!(
                                "{}; `{}` accepts {}.",
                                rejection.describe(&declaration.name),
                                declaration.name,
                                def.legal_values()
                            ),
                            declaration.span,
                        )
                        .with_symbol(declaration.id.to_string())
                        .with_field("property", declaration.name.clone()),
                    );
                }
            }
            PropertyLookup::Custom | PropertyLookup::Vendor => {}
            PropertyLookup::Unknown => {
                let suggestion = table
                    .nearest(&declaration.name)
                    .map(|nearest| format!(" Write `{nearest}` instead."))
                    .unwrap_or_default();
                diagnostics.push(
                    Diagnostic::error(
                        "CSS_UNKNOWN_PROPERTY",
                        format!(
                            "unknown CSS property `{}`.{suggestion} Custom properties (`--name`) and vendor-prefixed properties are always legal; every other property must be one the compiler's property table knows.",
                            declaration.name
                        ),
                        declaration.span,
                    )
                    .with_symbol(declaration.id.to_string())
                    .with_field("property", declaration.name.clone()),
                );
            }
        }
        let _ = owner;
    }
}

fn check_unused(model: &ViewModel, flat: &[FlatRule], diagnostics: &mut Vec<Diagnostic>) {
    let descriptors = model.descriptors();
    for rule in flat {
        let parsed = parse_selector_list(&rule.selector);
        for (text, complex) in &parsed {
            if complex.global {
                continue;
            }
            if !matched_elements(model, complex, MatchMode::Possible).is_empty() {
                continue;
            }
            let nearest = nearest_descriptor(text, &descriptors);
            let advice = match nearest {
                Some(candidate) => {
                    format!("the nearest element this view renders is `{candidate}`")
                }
                None => "this view renders no elements".to_string(),
            };
            diagnostics.push(
                Diagnostic::error(
                    "CSS_UNUSED_SELECTOR",
                    format!(
                        "selector `{text}` matches no element this component's view can render, across every `#if`, `#match`, and `#for` branch; {advice}. Rewrite the selector to name an element the view renders, wrap it in `:global(...)`, or move the rule to a global stylesheet if it targets markup this component does not own."
                    ),
                    rule.selector_span,
                )
                .with_symbol(rule.id.to_string())
                .with_field("selector", text.clone()),
            );
        }
    }
}

fn nearest_descriptor(selector: &str, descriptors: &[String]) -> Option<String> {
    let target = selector.trim();
    descriptors
        .iter()
        .map(|candidate| (edit_distance(target, candidate), candidate.clone()))
        .min_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1)))
        .map(|(_, candidate)| candidate)
}

fn check_shadowing(flat: &[FlatRule], diagnostics: &mut Vec<Diagnostic>) {
    for (later_index, later) in flat.iter().enumerate() {
        if later.has_pseudo || later.certain.is_empty() {
            continue;
        }
        let later_properties = later
            .declarations
            .iter()
            .map(|declaration| declaration.name.to_ascii_lowercase())
            .collect::<BTreeSet<_>>();
        for earlier in flat.iter().take(later_index) {
            // Provable overlap only: both rules must reach the same
            // elements without depending on a runtime `class` value.
            if earlier.has_pseudo
                || earlier.context != later.context
                || earlier.certain.is_empty()
                || !earlier.certain.is_subset(&later.certain)
                || !earlier.matched.is_subset(&later.matched)
                || earlier.specificity > later.specificity
            {
                continue;
            }
            for declaration in &earlier.declarations {
                let name = declaration.name.to_ascii_lowercase();
                if !later_properties.contains(&name) {
                    continue;
                }
                diagnostics.push(
                    Diagnostic::error(
                        "CSS_SHADOWED_DECLARATION",
                        format!(
                            "`{}` declared on `{}` is fully overridden by `{}` on the later rule `{}`, which matches the same elements at equal or higher specificity, so this declaration can never take effect. Delete it, or narrow one of the two selectors so they no longer overlap.",
                            declaration.name, earlier.selector, declaration.name, later.selector
                        ),
                        declaration.span,
                    )
                    .with_symbol(declaration.id.to_string())
                    .with_field("shadowedBy", later.id.to_string()),
                );
            }
        }
    }
}

const FLEX_ITEM_PROPERTIES: &[&str] = &[
    "flex",
    "flex-grow",
    "flex-shrink",
    "flex-basis",
    "order",
    "align-self",
];
const GRID_ITEM_PROPERTIES: &[&str] = &[
    "grid-area",
    "grid-column",
    "grid-column-start",
    "grid-column-end",
    "grid-row",
    "grid-row-start",
    "grid-row-end",
    "justify-self",
];
const FLEX_CONTAINER_PROPERTIES: &[&str] =
    &["flex-direction", "flex-wrap", "flex-flow", "place-items"];
const GRID_CONTAINER_PROPERTIES: &[&str] = &[
    "grid-template",
    "grid-template-columns",
    "grid-template-rows",
    "grid-template-areas",
    "grid-auto-columns",
    "grid-auto-rows",
    "grid-auto-flow",
];

fn check_nesting(model: &ViewModel, flat: &[FlatRule], diagnostics: &mut Vec<Diagnostic>) {
    // Only displays declared in this same block are provable; anything the
    // block does not declare is unknown and never refuses.
    let mut declared_display = BTreeMap::<usize, String>::new();
    for rule in flat {
        for declaration in &rule.declarations {
            if declaration.name.eq_ignore_ascii_case("display") {
                let value = declaration.value.trim().to_ascii_lowercase();
                for index in &rule.certain {
                    declared_display.insert(*index, value.clone());
                }
            }
        }
    }
    for rule in flat {
        if rule.certain.is_empty() || rule.certain != rule.matched {
            continue;
        }
        for declaration in &rule.declarations {
            let property = declaration.name.to_ascii_lowercase();
            let (needs_parent, wanted, family) =
                if FLEX_ITEM_PROPERTIES.contains(&property.as_str()) {
                    (true, ["flex", "inline-flex"].as_slice(), "flex")
                } else if GRID_ITEM_PROPERTIES.contains(&property.as_str()) {
                    (true, ["grid", "inline-grid"].as_slice(), "grid")
                } else if FLEX_CONTAINER_PROPERTIES.contains(&property.as_str()) {
                    (false, ["flex", "inline-flex"].as_slice(), "flex")
                } else if GRID_CONTAINER_PROPERTIES.contains(&property.as_str()) {
                    (false, ["grid", "inline-grid"].as_slice(), "grid")
                } else {
                    continue;
                };
            let mut offender = None;
            let mut provable = true;
            for index in &rule.certain {
                let subject = if needs_parent {
                    model.elements[*index].parent
                } else {
                    Some(*index)
                };
                let Some(subject) = subject else {
                    provable = false;
                    break;
                };
                let Some(display) = declared_display.get(&subject) else {
                    provable = false;
                    break;
                };
                if wanted.iter().any(|value| display == value) {
                    provable = false;
                    break;
                }
                offender.get_or_insert((subject, display.clone()));
            }
            let (Some((subject, display)), true) = (offender, provable) else {
                continue;
            };
            let owner = describe_element(&model.elements[subject]);
            let message = if needs_parent {
                format!(
                    "`{property}` only has an effect on a {family} item, but this block declares `display: {display}` on the parent `{owner}`. Declare `display: {family}` on `{owner}`, or delete `{property}`."
                )
            } else {
                format!(
                    "`{property}` only has an effect on a {family} container, but this block declares `display: {display}` on `{owner}`. Declare `display: {family}` on `{owner}`, or delete `{property}`."
                )
            };
            diagnostics.push(
                Diagnostic::error("CSS_INVALID_NESTING", message, declaration.span)
                    .with_symbol(declaration.id.to_string())
                    .with_field("property", property.clone()),
            );
        }
    }
}

fn describe_element(element: &ViewElement) -> String {
    if let Some(class) = element.classes.iter().next() {
        return format!(".{class}");
    }
    if let Some(id) = &element.id {
        return format!("#{id}");
    }
    element.tag.clone()
}

fn split_top_level(value: &str, delimiter: char) -> Vec<&str> {
    let mut values = Vec::new();
    let mut start = 0;
    let mut paren = 0usize;
    let mut bracket = 0usize;
    let mut quote = None;
    for (index, ch) in value.char_indices() {
        if let Some(active) = quote {
            if ch == active {
                quote = None;
            }
            continue;
        }
        match ch {
            '\'' | '"' => quote = Some(ch),
            '(' => paren += 1,
            ')' => paren = paren.saturating_sub(1),
            '[' => bracket += 1,
            ']' => bracket = bracket.saturating_sub(1),
            current if current == delimiter && paren == 0 && bracket == 0 => {
                values.push(&value[start..index]);
                start = index + ch.len_utf8();
            }
            _ => {}
        }
    }
    values.push(&value[start..]);
    values
}

fn edit_distance(left: &str, right: &str) -> usize {
    let left = left.chars().collect::<Vec<_>>();
    let right = right.chars().collect::<Vec<_>>();
    let mut previous = (0..=right.len()).collect::<Vec<_>>();
    let mut current = vec![0usize; right.len() + 1];
    for (row, left_char) in left.iter().enumerate() {
        current[0] = row + 1;
        for (column, right_char) in right.iter().enumerate() {
            let cost = usize::from(left_char != right_char);
            current[column + 1] = (previous[column] + cost)
                .min(previous[column + 1] + 1)
                .min(current[column] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[right.len()]
}

// ---------------------------------------------------------------------
// WO-55 stage (b): `strict` design mode.
//
// Under `design Name strict { … }` the token vocabulary is the closed set
// of words a component `style` block may use for a design decision. A raw
// colour, length, duration, shadow, font, or z-index literal refuses and
// the message enumerates the declared tokens of that kind, so the fix is
// a name the next model can reuse rather than another one-off value.
// Structural literals (`0`, `100%`, `auto`, `1fr`, `none`) carry no design
// decision and stay legal.
// ---------------------------------------------------------------------

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TokenNeed {
    Color,
    Spacing,
    Radius,
    Shadow,
    Font,
    Duration,
    Breakpoint,
    ZIndex,
}

impl TokenNeed {
    fn label(self) -> &'static str {
        match self {
            Self::Color => "Color",
            Self::Spacing => "Spacing",
            Self::Radius => "Radius",
            Self::Shadow => "Shadow",
            Self::Font => "Font",
            Self::Duration => "Duration",
            Self::Breakpoint => "Breakpoint",
            Self::ZIndex => "ZIndex",
        }
    }

    /// The declared categories that satisfy this need. `Length`, `Elevation`,
    /// `FontFamily`, and `Typography` are the pre-WO-55 spellings of the
    /// same decisions and still count.
    fn categories(self) -> &'static [&'static str] {
        match self {
            Self::Color => &["Color"],
            Self::Spacing => &["Spacing", "Length"],
            Self::Radius => &["Radius", "Length"],
            Self::Shadow => &["Shadow", "Elevation"],
            Self::Font => &["Font", "FontFamily", "Typography"],
            Self::Duration => &["Duration"],
            Self::Breakpoint => &["Breakpoint"],
            Self::ZIndex => &["ZIndex"],
        }
    }
}

/// The declared design vocabulary a style block is checked against.
pub(crate) struct Vocabulary {
    pub(crate) strict: bool,
    pub(crate) system: String,
    /// `(name, category, value)` for every declared token.
    pub(crate) tokens: Vec<(String, String, String)>,
}

impl Vocabulary {
    pub(crate) fn from_design(design: &noxid_design_ir::DesignProgram) -> Self {
        let strict = design.systems.iter().any(|system| system.strict);
        let system = design
            .systems
            .iter()
            .find(|system| system.strict)
            .or_else(|| design.systems.first())
            .map(|system| system.name.clone())
            .unwrap_or_default();
        let tokens = design
            .systems
            .iter()
            .flat_map(|system| {
                system.tokens.iter().map(|token| {
                    (
                        token.name.clone(),
                        token.category.clone(),
                        token.value.clone(),
                    )
                })
            })
            .collect();
        Self {
            strict,
            system,
            tokens,
        }
    }

    fn declared(&self, need: TokenNeed) -> Vec<&str> {
        self.tokens
            .iter()
            .filter(|(_, category, _)| need.categories().contains(&category.as_str()))
            .map(|(name, _, _)| name.as_str())
            .collect()
    }

    fn color_value(&self, name: &str) -> Option<&str> {
        self.tokens
            .iter()
            .find(|(token, category, _)| token == name && category == "Color")
            .map(|(_, _, value)| value.as_str())
    }

    fn offer(&self, need: TokenNeed) -> String {
        let declared = self.declared(need);
        let kind = need.label();
        if declared.is_empty() {
            format!(
                "`{}` declares no {kind} token yet; declare one in its `tokens` block and reference it as `token(<name>)`",
                self.system
            )
        } else {
            format!(
                "write one of `{}`'s declared {kind} tokens instead: {}",
                self.system,
                declared
                    .iter()
                    .map(|name| format!("`token({name})`"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    }
}

/// Which token kind, if any, a literal in this position stands in for.
fn token_need(property: &str, component: &str) -> Option<TokenNeed> {
    use noxid_css_syntax::properties::{LiteralKind, classify_literal, is_structural_literal};
    if is_structural_literal(component) {
        return None;
    }
    let property = property.to_ascii_lowercase();
    let kind = classify_literal(component);
    // Property-directed needs first: the same literal means a radius in one
    // position and a spacing in another.
    if property.contains("shadow") {
        return Some(TokenNeed::Shadow);
    }
    if property == "font-family" || property == "font" {
        return matches!(kind, LiteralKind::String | LiteralKind::Identifier)
            .then_some(TokenNeed::Font);
    }
    if property == "z-index" {
        return matches!(kind, LiteralKind::Integer).then_some(TokenNeed::ZIndex);
    }
    match kind {
        LiteralKind::Color => Some(TokenNeed::Color),
        LiteralKind::Time => Some(TokenNeed::Duration),
        LiteralKind::Length if property.contains("radius") => Some(TokenNeed::Radius),
        LiteralKind::Length => Some(TokenNeed::Spacing),
        _ => None,
    }
}

pub(crate) fn check_strict_declarations(
    vocabulary: &Vocabulary,
    declarations: &[StyleDeclaration],
    diagnostics: &mut Vec<Diagnostic>,
) {
    use noxid_css_syntax::properties::split_components;
    if !vocabulary.strict {
        return;
    }
    for declaration in declarations {
        // Custom properties are the declared escape hatch for a value the
        // token vocabulary does not model, so they are not literals to
        // police here.
        if declaration.name.starts_with("--") {
            continue;
        }
        for component in split_components(&declaration.value) {
            let Some(need) = token_need(&declaration.name, component) else {
                continue;
            };
            diagnostics.push(
                Diagnostic::error(
                    "CSS_TOKEN_REQUIRED",
                    format!(
                        "`{}` is a raw {} value, and `design {} strict` requires every {} to be a declared token: {}.",
                        component,
                        need.label(),
                        vocabulary.system,
                        need.label(),
                        vocabulary.offer(need)
                    ),
                    declaration.span,
                )
                .with_symbol(declaration.id.to_string())
                .with_field("tokenKind", need.label()),
            );
        }
    }
}

/// Under strict mode a width query names a Breakpoint token, so the set of
/// breakpoints an app has is a list a model can read instead of a set of
/// magic numbers scattered through the stylesheets.
pub(crate) fn check_strict_media_prelude(
    vocabulary: &Vocabulary,
    name: &str,
    prelude: &str,
    span: Span,
    owner: &SemanticId,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !vocabulary.strict || !name.eq_ignore_ascii_case("media") {
        return;
    }
    let lowered = prelude.to_ascii_lowercase();
    let mut rest = lowered.as_str();
    while let Some(index) = rest.find("width") {
        let after = &rest[index + "width".len()..];
        let Some(colon) = after.find(':') else {
            break;
        };
        let value = after[colon + 1..]
            .split(')')
            .next()
            .unwrap_or("")
            .trim()
            .to_string();
        if !value.is_empty() && !value.starts_with("token(") {
            diagnostics.push(
                Diagnostic::error(
                    "CSS_TOKEN_REQUIRED",
                    format!(
                        "`{value}` is a raw Breakpoint value, and `design {} strict` requires every width query to name a declared Breakpoint token: {}.",
                        vocabulary.system,
                        vocabulary.offer(TokenNeed::Breakpoint)
                    ),
                    span,
                )
                .with_symbol(owner.to_string())
                .with_field("tokenKind", "Breakpoint"),
            );
        }
        rest = &after[colon + 1..];
    }
}

/// WCAG AA at compile time, for the one case the compiler can resolve
/// without guessing: a `color`/`background` pair in one rule where both
/// sides are declared Color tokens.
pub(crate) fn check_contrast(
    vocabulary: &Vocabulary,
    selector: &str,
    declarations: &[StyleDeclaration],
    diagnostics: &mut Vec<Diagnostic>,
) {
    fn token_name(value: &str) -> Option<&str> {
        value
            .trim()
            .strip_prefix("token(")?
            .strip_suffix(')')
            .map(str::trim)
    }
    let mut foreground: Option<(&StyleDeclaration, &str)> = None;
    let mut background: Option<(&StyleDeclaration, &str)> = None;
    for declaration in declarations {
        let lowered = declaration.name.to_ascii_lowercase();
        let Some(name) = token_name(&declaration.value) else {
            continue;
        };
        match lowered.as_str() {
            "color" => foreground = Some((declaration, name)),
            "background" | "background-color" => background = Some((declaration, name)),
            _ => {}
        }
    }
    let (Some((declaration, foreground)), Some((_, background))) = (foreground, background) else {
        return;
    };
    let (Some(foreground_value), Some(background_value)) = (
        vocabulary.color_value(foreground),
        vocabulary.color_value(background),
    ) else {
        return;
    };
    let Some(ratio) = noxid_design_ir::contrast_ratio(foreground_value, background_value) else {
        return;
    };
    if ratio >= noxid_design_ir::CONTRAST_AA {
        return;
    }
    diagnostics.push(
        Diagnostic::error(
            "CSS_CONTRAST_INSUFFICIENT",
            format!(
                "`{selector}` sets `color: token({foreground})` ({foreground_value}) on `token({background})` ({background_value}), a contrast ratio of {ratio:.2}:1, below the WCAG AA minimum of {:.1}:1 for normal text. Pick a declared Color token that clears AA against `{background}`, or change one of the two tokens' values.",
                noxid_design_ir::CONTRAST_AA
            ),
            declaration.span,
        )
        .with_symbol(declaration.id.to_string())
        .with_field("ratio", format!("{ratio:.2}")),
    );
}