Skip to main content

parsec_css/cascade/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The cascade, CSS Cascading and Inheritance Level 5, over a Parsec
5//! document: stylesheets from the user agent, the user and the author,
6//! `@media` and `@supports` evaluated against an [`Environment`],
7//! `@layer`, nesting, specificity, `!important` and `style=""`, then
8//! every element's computed values with inheritance, the CSS-wide
9//! keywords (`revert` and `revert-layer` included), custom properties and
10//! `var()`.
11//!
12//! ```
13//! use parsec_css::cascade::Styler;
14//!
15//! let doc = parsec::parse(
16//!     "<style>@media (min-width: 600px) { p { font-size: 2em } } .x { color: red !important }</style>\
17//!      <p class=x style='color: blue'>hi</p>",
18//!     false,
19//! );
20//! let styled = Styler::new(Default::default()).with_document_styles(&doc).style(&doc);
21//! let p = parsec::css::SelectorList::parse("p").unwrap().select_first(&doc, doc.root()).unwrap();
22//! assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(255, 0, 0)"));
23//! assert_eq!(styled.get(p, "font-size").as_deref(), Some("32px"));
24//! assert_eq!(styled.get(p, "display").as_deref(), Some("block"));
25//! ```
26//!
27//! `@scope` applies with scoping proximity in the cascade order;
28//! `@container`, and the `cq*` units, against the sizes
29//! [`Styler::container_sizes`] gives;
30//! `@import` through the fetch [`Styler::fetch`] gives, with `layer()`,
31//! `supports()` and media; `@property` registers custom properties, which
32//! then take their syntax, initial value and inheritance from it; and
33//! [`Styler::at_rules`] gives the `@keyframes`, `@counter-style` and
34//! `@property` rules that win.
35//!
36//! Pseudo-elements are styled too, CSS Pseudo-Elements 4: a rule whose
37//! selector ends in `::before`, `::after`, `::marker`, `::placeholder`,
38//! `::first-line`, `::first-letter`, `::selection`, `::backdrop`,
39//! `::file-selector-button` or `::highlight()` applies to that
40//! pseudo-element of the elements the rest of it matches, and
41//! [`Styled::get_pseudo`] gives its computed values, inherited from the
42//! originating element, with only the properties that apply to it
43//! counted, and `content` worked out. They're computed when asked for,
44//! not before.
45//!
46//! What it doesn't do is layout: a value that needs boxes to work out,
47//! `width: 50%` as pixels say, stays as its computed value, and a
48//! container's size is the caller's to give.
49
50mod compute;
51mod pseudo;
52
53use std::collections::HashMap;
54use std::sync::Arc;
55
56use parsec::css::SelectorList;
57use parsec::{Document, Kind, NodeId};
58
59use crate::media::{Environment, MediaQueryList};
60use crate::parser::{Block, ComponentValue, Item, Rule};
61use crate::rules::{
62    ContainerQuery, CounterStyle, Import, Keyframes, PropertyRule, ScopeBounds, Syntax,
63};
64use crate::tokenizer::Token;
65use crate::values::{CssWide, Specified, expand, property};
66
67pub use compute::Computed;
68pub use pseudo::Pseudo;
69use pseudo::{PseudoRule, PseudoStyles, Split, split_pseudo};
70
71/// Where a stylesheet comes from, which decides what wins between them.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
73pub enum Origin {
74    UserAgent,
75    User,
76    Author,
77}
78
79/// The HTML Standard's default styles, from its rendering section
80/// (§15.3), the parts that don't need layout or form controls.
81pub const HTML_UA_STYLESHEET: &str = include_str!("html.css");
82
83struct Sheet {
84    css: String,
85    origin: Origin,
86    media: Option<MediaQueryList>,
87    /// The `<style>` it came from, whose parent an `@scope` with no root
88    /// is scoped to.
89    owner: Option<NodeId>,
90}
91
92/// What an `@import`'s URL gives: the stylesheet's text, or `None`.
93pub type Fetch = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
94
95/// A container's size, width and height in CSS pixels, from the element
96/// and its computed values; `None` for one whose size isn't known.
97pub type ContainerSize = Arc<dyn Fn(NodeId, &Computed) -> Option<(f64, f64)> + Send + Sync>;
98
99/// Collects stylesheets and styles documents with them.
100#[derive(Default)]
101pub struct Styler {
102    env: Environment,
103    sheets: Vec<Sheet>,
104    /// Whether `style=""` attributes count, as they do in a browser.
105    style_attributes: bool,
106    fetch: Option<Fetch>,
107    container_size: Option<ContainerSize>,
108}
109
110/// How deep `@import`s may nest, and how many one styling may follow:
111/// past either, the rest aren't fetched.
112const MAX_IMPORT_DEPTH: usize = 16;
113const MAX_IMPORTS: usize = 256;
114
115/// The `@keyframes`, `@counter-style` and `@property` rules that win, by
116/// name: the last of a name in the cascade's order, layers counted.
117#[derive(Clone, Debug, Default, PartialEq)]
118pub struct AtRules {
119    pub keyframes: Vec<Keyframes>,
120    pub counter_styles: Vec<CounterStyle>,
121    pub properties: Vec<PropertyRule>,
122}
123
124/// A declaration where the cascade put it.
125#[derive(Clone)]
126struct Declared<'s> {
127    value: Specified<'s>,
128    /// For a longhand set from a shorthand with `var()` in it: the
129    /// shorthand, whose value is split once it's substituted.
130    from_shorthand: Option<&'static str>,
131    key: Key,
132}
133
134/// What orders declarations, CSS Cascade 5 §6: origin and importance,
135/// then `style=""`, then layer, then specificity, then order.
136#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
137struct Key {
138    origin: u8,
139    attached: bool,
140    layer: u32,
141    specificity: (u32, u32, u32),
142    /// Scoping proximity, CSS Cascade 6 §6.6: nearer roots win, and an
143    /// unscoped rule is the farthest of all.
144    proximity: u32,
145    order: u32,
146}
147
148/// One style rule's selector, one complex selector of its list each, and
149/// its declarations.
150#[derive(Clone)]
151struct Entry<'s> {
152    selector: SelectorList,
153    /// What an element must have for the selector to have a chance.
154    bucket: Bucket,
155    specificity: (u32, u32, u32),
156    origin: Origin,
157    layer: usize,
158    order: u32,
159    declarations: Vec<(&'s str, &'s [ComponentValue<'s>], bool)>,
160    scope: Option<Arc<Scope>>,
161    /// The `@container` rules it's in, each a list of queries any of
162    /// which may hold.
163    containers: Vec<Arc<Vec<ContainerQuery>>>,
164    /// The pseudo-element a rule styles, whose originating element
165    /// `selector` matches.
166    pseudo: Option<Pseudo>,
167    /// Whether the selector is `*`, which every element matches.
168    any: bool,
169}
170
171/// An `@scope` a rule is in.
172struct Scope {
173    start: ScopeStart,
174    end: Option<SelectorList>,
175    /// The `@scope` this one is in, which its roots must be in scope of.
176    outer: Option<Arc<Scope>>,
177}
178
179enum ScopeStart {
180    Selector(SelectorList),
181    /// No `<scope-start>`: the parent of the `<style>` it's in, or the
182    /// document for a sheet with none.
183    Owner(Option<NodeId>),
184}
185
186/// Every element's computed values.
187pub struct Styled {
188    styles: HashMap<NodeId, Computed>,
189    pseudo: PseudoStyles,
190}
191
192impl Styled {
193    /// `property`'s value on `el`, as `getComputedStyle()` writes it, or
194    /// `None` for a node that isn't an element or a property that isn't.
195    pub fn get(&self, el: NodeId, property: &str) -> Option<String> {
196        self.styles.get(&el)?.get(property)
197    }
198
199    /// Everything about one element's style.
200    pub fn computed(&self, el: NodeId) -> Option<&Computed> {
201        self.styles.get(&el)
202    }
203}
204
205impl Styler {
206    /// A styler with the HTML user agent stylesheet, `style=""` counted.
207    pub fn new(env: Environment) -> Styler {
208        let mut s = Styler {
209            env,
210            style_attributes: true,
211            ..Styler::default()
212        };
213        s.add(HTML_UA_STYLESHEET, Origin::UserAgent);
214        s
215    }
216
217    /// A styler with no stylesheet at all, not even the user agent's.
218    pub fn bare(env: Environment) -> Styler {
219        Styler {
220            env,
221            style_attributes: true,
222            ..Styler::default()
223        }
224    }
225
226    pub fn environment(&self) -> &Environment {
227        &self.env
228    }
229
230    /// Adds a stylesheet.
231    pub fn add(&mut self, css: &str, origin: Origin) -> &mut Styler {
232        self.sheets.push(Sheet {
233            css: css.to_string(),
234            origin,
235            media: None,
236            owner: None,
237        });
238        self
239    }
240
241    /// Adds a stylesheet that applies only where `media` matches, as a
242    /// `<style media>` or `<link media>` does.
243    pub fn add_with_media(&mut self, css: &str, origin: Origin, media: &str) -> &mut Styler {
244        self.sheets.push(Sheet {
245            css: css.to_string(),
246            origin,
247            media: Some(MediaQueryList::parse_str(media)),
248            owner: None,
249        });
250        self
251    }
252
253    /// Fetches `@import`ed stylesheets with `fetch`, given each URL as
254    /// written; without it, `@import` is ignored.
255    pub fn fetch(
256        mut self,
257        fetch: impl Fn(&str) -> Option<String> + Send + Sync + 'static,
258    ) -> Styler {
259        self.fetch = Some(Arc::new(fetch));
260        self
261    }
262
263    /// Gives each container's size, for `@container` and the `cq*` units:
264    /// `size` is asked for an element whose `container-type` makes it a
265    /// container, with its computed values, and gives its width and height
266    /// in CSS pixels. A query on a container with no size given is false,
267    /// and `cq*` units look past it to the next container out, or the
268    /// viewport.
269    pub fn container_sizes(
270        mut self,
271        size: impl Fn(NodeId, &Computed) -> Option<(f64, f64)> + Send + Sync + 'static,
272    ) -> Styler {
273        self.container_size = Some(Arc::new(size));
274        self
275    }
276
277    /// Adds the document's own `<style>` elements, with their `media`, as
278    /// author stylesheets.
279    pub fn with_document_styles(mut self, doc: &Document) -> Styler {
280        let style = SelectorList::parse("style").unwrap();
281        for el in style.select(doc, doc.root()) {
282            let media = doc
283                .attrs(el)
284                .find(|(_, n, _)| *n == "media")
285                .map(|(_, _, v)| v.to_string());
286            let css = doc.text(el);
287            match media {
288                Some(m) => self.add_with_media(&css, Origin::Author, &m),
289                None => self.add(&css, Origin::Author),
290            };
291            if let Some(last) = self.sheets.last_mut() {
292                last.owner = Some(el);
293            }
294        }
295        self
296    }
297
298    /// Whether `style=""` attributes count; they do unless this says not.
299    pub fn style_attributes(mut self, on: bool) -> Styler {
300        self.style_attributes = on;
301        self
302    }
303
304    /// Styles every element of `doc`.
305    pub fn style(&self, doc: &Document) -> Styled {
306        self.style_some(doc, None)
307    }
308
309    /// Styles one element, and the ancestors it inherits from, but no
310    /// other: the cheap way to one element's computed values.
311    pub fn style_element(&self, doc: &Document, el: NodeId) -> Option<Computed> {
312        let mut chain = vec![el];
313        let mut at = el;
314        while let Some(p) = doc.parent(at) {
315            if matches!(doc.kind(p), Kind::Element { .. }) {
316                chain.push(p);
317            }
318            at = p;
319        }
320        chain.reverse();
321        let mut styled = self.style_some(doc, Some(&chain));
322        styled.styles.remove(&el)
323    }
324
325    /// Each sheet that applies, with what it `@import`s before it, in the
326    /// cascade's order.
327    fn units(&self) -> Vec<Unit> {
328        let mut out = Vec::new();
329        let mut count = 0;
330        for s in &self.sheets {
331            if s.origin == Origin::UserAgent && s.css == HTML_UA_STYLESHEET {
332                continue;
333            }
334            if !s.media.as_ref().is_none_or(|m| m.matches(&self.env)) {
335                continue;
336            }
337            self.expand(
338                s.css.clone(),
339                (s.origin, s.owner),
340                (Vec::new(), Vec::new()),
341                0,
342                &mut count,
343                &mut out,
344            );
345        }
346        out
347    }
348
349    /// A sheet, after the sheets its `@import`s bring in, each in the
350    /// layer the import puts it.
351    #[allow(clippy::too_many_arguments)]
352    fn expand(
353        &self,
354        css: String,
355        (origin, owner): (Origin, Option<NodeId>),
356        (layer, scopes): (Vec<String>, Vec<ScopeBounds>),
357        depth: usize,
358        count: &mut usize,
359        out: &mut Vec<Unit>,
360    ) {
361        if let Some(fetch) = &self.fetch {
362            let sheet = crate::parse_stylesheet(&css);
363            // `@layer` statements before the imports name their layers
364            // first.
365            let mut declared = Vec::new();
366            for rule in &sheet.rules {
367                let Rule::At(a) = rule else { break };
368                match a.name.to_ascii_lowercase().as_str() {
369                    "charset" => {}
370                    "layer" if a.block.is_none() => {
371                        for n in layer_names(&a.prelude) {
372                            let mut path = layer.clone();
373                            path.extend(n);
374                            declared.push(path);
375                        }
376                    }
377                    "import" => {
378                        let Some(import) = Import::parse(a) else {
379                            continue;
380                        };
381                        if !import.applies(&self.env)
382                            || depth >= MAX_IMPORT_DEPTH
383                            || *count >= MAX_IMPORTS
384                        {
385                            continue;
386                        }
387                        *count += 1;
388                        let mut path = layer.clone();
389                        match &import.layer {
390                            Some(Some(n)) => path.extend(n.split('.').map(String::from)),
391                            // Each anonymous layer its own.
392                            Some(None) => path.push(format!("\u{0}import{count}")),
393                            None => {}
394                        }
395                        // The layer is named whether the sheet loads or not.
396                        if import.layer.is_some() {
397                            declared.push(path.clone());
398                        }
399                        out.push(Unit::layers(std::mem::take(&mut declared)));
400                        let Some(text) = fetch(&import.url) else {
401                            continue;
402                        };
403                        let mut inner = scopes.clone();
404                        inner.extend(import.scope.clone());
405                        self.expand(text, (origin, owner), (path, inner), depth + 1, count, out);
406                    }
407                    _ => break,
408                }
409            }
410        }
411        out.push(Unit {
412            css,
413            origin,
414            owner,
415            layer,
416            declare: Vec::new(),
417            scopes,
418        });
419    }
420
421    /// The rules of every sheet that applies, collected.
422    fn collect<'u>(
423        &self,
424        parsed: &'u [(&'u Unit, crate::Stylesheet<'u, Block<'u>>)],
425        layers: &mut Layers,
426        entries: &mut Vec<Entry<'u>>,
427        at: &mut Collected,
428    ) {
429        let mut order = 0;
430        // The HTML user agent stylesheet is the same every time: its rules
431        // are collected once, for every styler.
432        if self
433            .sheets
434            .iter()
435            .any(|s| s.origin == Origin::UserAgent && s.css == HTML_UA_STYLESHEET)
436        {
437            let (ua, n) = ua_entries();
438            entries.extend(ua.iter().cloned());
439            order = *n;
440        }
441        for (unit, parsed) in parsed {
442            for path in &unit.declare {
443                layers.id(path);
444            }
445            let mut cx = Collect {
446                env: &self.env,
447                origin: unit.origin,
448                layers,
449                entries,
450                order: &mut order,
451                owner: unit.owner,
452                scope: None,
453                containers: Vec::new(),
454                at,
455            };
456            // An `@import … scope()`'s sheet is as if in that `@scope`.
457            if unit.scopes.iter().all(|b| cx.enter_scope(b, &[])) {
458                cx.rules(&parsed.rules, &[], &unit.layer);
459            }
460        }
461    }
462
463    /// The `@keyframes`, `@counter-style` and `@property` rules in force:
464    /// for each name, the one the cascade's order puts last.
465    pub fn at_rules(&self) -> AtRules {
466        let units = self.units();
467        let parsed: Vec<_> = units
468            .iter()
469            .map(|u| (u, crate::parse_stylesheet_deep(&u.css)))
470            .collect();
471        let mut layers = Layers::default();
472        let mut entries = Vec::new();
473        let mut at = Collected::default();
474        self.collect(&parsed, &mut layers, &mut entries, &mut at);
475        let ranks = layers.ranks();
476        at.resolved(&ranks)
477    }
478
479    fn style_some(&self, doc: &Document, only: Option<&[NodeId]>) -> Styled {
480        let units = self.units();
481        let parsed: Vec<_> = units
482            .iter()
483            .map(|u| (u, crate::parse_stylesheet_deep(&u.css)))
484            .collect();
485        let mut layers = Layers::default();
486        let mut entries = Vec::new();
487        let mut at = Collected::default();
488        self.collect(&parsed, &mut layers, &mut entries, &mut at);
489        let ranks = layers.ranks();
490        let registered: HashMap<String, (PropertyRule, Syntax)> = at
491            .resolved(&ranks)
492            .properties
493            .into_iter()
494            .filter(PropertyRule::registers)
495            .filter_map(|p| {
496                let syntax = Syntax::parse(&p.syntax)?;
497                Some((p.name.clone(), (p, syntax)))
498            })
499            .collect();
500        let mut scope_cache = ScopeCache::default();
501        let mut index = Index::default();
502        let mut pseudo = PseudoStyles {
503            env: self.env.clone(),
504            root: doc_element(doc),
505            ..PseudoStyles::default()
506        };
507        // Each pseudo-element rule's place in `pseudo.rules`, where it's
508        // copied the first time an element matches it.
509        let mut rule_of: HashMap<usize, usize> = HashMap::new();
510        for (i, e) in entries.iter().enumerate() {
511            // On every element alike: kept once, not per element.
512            if e.pseudo.is_some() && e.any && e.scope.is_none() && e.containers.is_empty() {
513                let rule = PseudoRule::of(e);
514                if !rule.needs_attrs {
515                    pseudo.rules.push(rule);
516                    let key = self.key(e, &ranks, 0);
517                    pseudo.always.push((pseudo.rules.len() - 1, key));
518                    continue;
519                }
520            }
521            match &e.bucket {
522                Bucket::Id(x) => index.ids.entry(x.clone()).or_default().push(i),
523                Bucket::Class(x) => index.classes.entry(x.clone()).or_default().push(i),
524                Bucket::Tag(x) => index.tags.entry(x.clone()).or_default().push(i),
525                Bucket::Attr(x) => index.attrs.entry(x.clone()).or_default().push(i),
526                Bucket::Universal => index.universal.push(i),
527            }
528        }
529        // Style attributes, parsed once each.
530        let mut inline = HashMap::new();
531        let attrs: Vec<(NodeId, String)> = if self.style_attributes {
532            elements(doc)
533                .filter_map(|el| {
534                    doc.attrs(el)
535                        .find(|(_, n, _)| *n == "style")
536                        .map(|(_, _, v)| (el, v.to_string()))
537                })
538                .collect()
539        } else {
540            Vec::new()
541        };
542        let parsed_attrs: Vec<(NodeId, crate::BlockContents<'_>)> = attrs
543            .iter()
544            .map(|(el, css)| (*el, crate::parse_declaration_list(css)))
545            .collect();
546        for (el, block) in &parsed_attrs {
547            inline.insert(*el, block);
548        }
549        let mut styles = HashMap::new();
550        let root = doc_element(doc);
551        // Parents before children: document order.
552        let order: Vec<NodeId> = match only {
553            Some(chain) => chain.to_vec(),
554            None => elements(doc).collect(),
555        };
556        for el in order {
557            let mut declared: HashMap<&'static str, Vec<Declared<'_>>> = HashMap::new();
558            let mut custom: HashMap<String, Vec<(Key, Vec<ComponentValue<'_>>)>> = HashMap::new();
559            // Only the rules whose rightmost id, class or type this element
560            // has are tried.
561            let mut candidates: Vec<usize> = index.universal.clone();
562            if let Some(name) = doc.lower_name(el) {
563                candidates.extend(index.tags.get(name).into_iter().flatten());
564            }
565            for (_, n, v) in doc.attrs(el) {
566                candidates.extend(index.attrs.get(n).into_iter().flatten());
567                if n == "id" {
568                    candidates.extend(index.ids.get(v).into_iter().flatten());
569                } else if n == "class" {
570                    for c in v.split_ascii_whitespace() {
571                        candidates.extend(index.classes.get(c).into_iter().flatten());
572                    }
573                }
574            }
575            candidates.sort_unstable();
576            candidates.dedup();
577            let mut pseudo_candidates = Vec::new();
578            for &i in &candidates {
579                let e = &entries[i];
580                if e.pseudo.is_some() {
581                    // Once this element's style is known: a pseudo-element's
582                    // container may be its originating element.
583                    pseudo_candidates.push(i);
584                    continue;
585                }
586                let Some(proximity) =
587                    self.entry_matches(e, doc, el, &styles, &mut scope_cache, false)
588                else {
589                    continue;
590                };
591                let key = self.key(e, &ranks, proximity);
592                for (name, value, important) in &e.declarations {
593                    add(&mut declared, &mut custom, name, value, *important, key);
594                }
595            }
596            if let Some(block) = inline.get(&el) {
597                for item in &block.items {
598                    if let Item::Declaration(d) = item {
599                        let key = Key {
600                            origin: Origin::Author as u8,
601                            attached: true,
602                            layer: ranks[0],
603                            specificity: (0, 0, 0),
604                            proximity: 0,
605                            order: u32::MAX,
606                        };
607                        add(
608                            &mut declared,
609                            &mut custom,
610                            &d.name,
611                            &d.value,
612                            d.important,
613                            key,
614                        );
615                    }
616                }
617            }
618            for list in declared.values_mut() {
619                list.sort_by_key(|d| d.key);
620            }
621            for list in custom.values_mut() {
622                list.sort_by_key(|d| d.0);
623            }
624            let parent_id = doc.parent(el);
625            let parent = parent_id.and_then(|p| styles.get(&p));
626            let parent_id = parent_id.filter(|_| parent.is_some());
627            let root_style = if Some(el) == root {
628                None
629            } else {
630                root.and_then(|r| styles.get(&r))
631            };
632            let mut computed = compute::compute(compute::Input {
633                declared: &declared,
634                custom: &custom,
635                parent,
636                root: root_style,
637                is_root: Some(el) == root,
638                env: &self.env,
639                cq: parent.map_or((self.env.width, self.env.height), |p| p.cq_children),
640                registered: &registered,
641            });
642            // A size container is what its descendants' `cq*` units are
643            // relative to, on the axes it contains; one with no size given
644            // passes its own on.
645            let (w, h) = computed.size_axes();
646            if (w || h)
647                && let Some((width, height)) =
648                    self.container_size.as_ref().and_then(|f| f(el, &computed))
649            {
650                if w {
651                    computed.cq_children.0 = width;
652                }
653                if h {
654                    computed.cq_children.1 = height;
655                }
656            }
657            computed.parent = parent_id;
658            styles.insert(el, computed);
659            let mut matched = Vec::new();
660            for i in pseudo_candidates {
661                let e = &entries[i];
662                if let Some(proximity) =
663                    self.entry_matches(e, doc, el, &styles, &mut scope_cache, true)
664                {
665                    let r = *rule_of.entry(i).or_insert_with(|| {
666                        pseudo.rules.push(PseudoRule::of(e));
667                        pseudo.rules.len() - 1
668                    });
669                    if pseudo.rules[r].needs_attrs && !pseudo.attrs.contains_key(&el) {
670                        let attrs = doc
671                            .attrs(el)
672                            .map(|(_, n, v)| (n.to_string(), v.to_string()))
673                            .collect();
674                        pseudo.attrs.insert(el, attrs);
675                    }
676                    matched.push((r, self.key(e, &ranks, proximity)));
677                }
678            }
679            if !matched.is_empty() {
680                pseudo.matched.insert(el, matched);
681            }
682        }
683        pseudo.registered = registered;
684        Styled { styles, pseudo }
685    }
686
687    /// Where a rule's declarations go in the cascade's order.
688    #[inline]
689    fn key(&self, e: &Entry<'_>, ranks: &[u32], proximity: u32) -> Key {
690        Key {
691            origin: e.origin as u8,
692            attached: false,
693            layer: ranks[e.layer],
694            specificity: e.specificity,
695            proximity,
696            order: e.order,
697        }
698    }
699
700    /// Whether a rule applies to `el`, with its scoping proximity if so.
701    /// `inclusive` is for a pseudo-element's rule, whose containers start
702    /// at `el`, the originating element, which must be styled already.
703    #[inline]
704    fn entry_matches(
705        &self,
706        e: &Entry<'_>,
707        doc: &Document,
708        el: NodeId,
709        styles: &HashMap<NodeId, Computed>,
710        scope_cache: &mut ScopeCache,
711        inclusive: bool,
712    ) -> Option<u32> {
713        if !e
714            .containers
715            .iter()
716            .all(|c| self.container_holds(c, doc, el, styles, inclusive))
717        {
718            return None;
719        }
720        match &e.scope {
721            None => e.selector.matches(doc, el, None).then_some(0),
722            Some(scope) => {
723                let levels = scope_roots(scope, doc, el, scope_cache);
724                let roots = levels.last().map_or(&[][..], |r| &r[..]);
725                roots
726                    .iter()
727                    .find(|(r, _)| e.selector.matches(doc, el, Some(*r)))
728                    .map(|(_, hops)| u32::MAX - hops)
729            }
730        }
731    }
732}
733
734/// Puts a declaration where the cascade sorts it: shorthands split, custom
735/// properties apart.
736fn add<'x>(
737    declared: &mut HashMap<&'static str, Vec<Declared<'x>>>,
738    custom: &mut HashMap<String, Vec<(Key, Vec<ComponentValue<'x>>)>>,
739    name: &str,
740    value: &'x [ComponentValue<'x>],
741    important: bool,
742    key: Key,
743) {
744    let mut key = key;
745    key.origin = rank(key.origin, important);
746    if important {
747        key.layer = u32::MAX - key.layer;
748    }
749    if name.starts_with("--") {
750        custom
751            .entry(name.to_string())
752            .or_default()
753            .push((key, trim(value).to_vec()));
754        return;
755    }
756    let Some(p) = property(name) else { return };
757    let p = p.alias_of.and_then(property).unwrap_or(p);
758    // `all`: a CSS-wide keyword for every property but `direction`,
759    // `unicode-bidi` and the custom ones.
760    if p.name == "all" {
761        if let Ok(v @ Specified::CssWide(_)) = crate::values::parse_value("all", value) {
762            for q in crate::values::properties() {
763                if q.is_shorthand()
764                    || q.alias_of.is_some()
765                    || matches!(q.name, "all" | "direction" | "unicode-bidi")
766                {
767                    continue;
768                }
769                declared.entry(q.name).or_default().push(Declared {
770                    value: v.clone(),
771                    from_shorthand: None,
772                    key,
773                });
774            }
775        }
776        return;
777    }
778    if !p.is_shorthand() {
779        if let Ok(v) = crate::values::parse_value(p.name, value) {
780            declared.entry(p.name).or_default().push(Declared {
781                value: v,
782                from_shorthand: None,
783                key,
784            });
785        }
786        return;
787    }
788    // The shorthand too, so its computed value can be written as it was
789    // given when none of its longhands comes from anything later.
790    if let Ok(v) = crate::values::parse_value(p.name, value) {
791        declared.entry(p.name).or_default().push(Declared {
792            value: v,
793            from_shorthand: None,
794            key,
795        });
796    }
797    let Ok(longhands) = expand(p.name, value) else {
798        return;
799    };
800    let pending = matches!(longhands.first(), Some((_, Specified::Unparsed(_))));
801    for (l, v) in longhands {
802        declared.entry(l).or_default().push(Declared {
803            value: v,
804            from_shorthand: pending.then_some(p.name),
805            key,
806        });
807    }
808}
809
810/// The HTML user agent stylesheet's rules, collected once. Nothing in it
811/// depends on the environment.
812fn ua_entries() -> &'static (Vec<Entry<'static>>, u32) {
813    static SHEET: std::sync::OnceLock<crate::Stylesheet<'static, Block<'static>>> =
814        std::sync::OnceLock::new();
815    static ENTRIES: std::sync::OnceLock<(Vec<Entry<'static>>, u32)> = std::sync::OnceLock::new();
816    ENTRIES.get_or_init(|| {
817        let sheet = SHEET.get_or_init(|| crate::parse_stylesheet_deep(HTML_UA_STYLESHEET));
818        let env = Environment::default();
819        let mut layers = Layers::default();
820        let mut entries = Vec::new();
821        let mut order = 0;
822        let mut at = Collected::default();
823        let mut cx = Collect {
824            env: &env,
825            origin: Origin::UserAgent,
826            layers: &mut layers,
827            entries: &mut entries,
828            order: &mut order,
829            owner: None,
830            scope: None,
831            containers: Vec::new(),
832            at: &mut at,
833        };
834        cx.rules(&sheet.rules, &[], &[]);
835        (entries, order)
836    })
837}
838
839impl Styler {
840    /// Whether one of an `@container`'s queries holds for `el`: its
841    /// nearest container of the name with the axes the query needs, of
842    /// the size [`Styler::container_sizes`] gives.
843    fn container_holds(
844        &self,
845        queries: &[ContainerQuery],
846        doc: &Document,
847        el: NodeId,
848        styles: &HashMap<NodeId, Computed>,
849        inclusive: bool,
850    ) -> bool {
851        queries.iter().any(|q| {
852            let axes = q.axes();
853            let sized = axes.inline || axes.block;
854            let mut at = if inclusive { Some(el) } else { doc.parent(el) };
855            while let Some(a) = at {
856                at = doc.parent(a);
857                let Some(c) = styles.get(&a) else { continue };
858                let ty = c.get("container-type").unwrap_or_default();
859                let size = ty.split_ascii_whitespace().any(|w| w == "size");
860                let inline = size || ty.split_ascii_whitespace().any(|w| w == "inline-size");
861                // Every element is a style container; a size container
862                // needs the type for the axes asked of it, and a box.
863                let boxed = !matches!(c.get("display").as_deref(), Some("none" | "contents"));
864                let eligible = if axes.block {
865                    size && boxed
866                } else if axes.inline {
867                    inline && boxed
868                } else {
869                    true
870                };
871                let named = q.name.as_ref().is_none_or(|n| {
872                    c.get("container-name")
873                        .is_some_and(|names| names.split_ascii_whitespace().any(|x| x == n))
874                });
875                if !eligible || !named {
876                    continue;
877                }
878                let size = match sized {
879                    true => match self.container_size.as_ref().and_then(|f| f(a, c)) {
880                        Some(s) => Some(s),
881                        None => return false,
882                    },
883                    false => None,
884                };
885                let get = |name: &str| c.get(name);
886                let number = |value: &str| c.range_value(value);
887                return q.evaluate(size, &c.query_lengths(), &get, &number) == Some(true);
888            }
889            false
890        })
891    }
892}
893
894/// Each nesting level's scoping roots, outermost first, each root with
895/// how many generations up it is.
896type Levels = Vec<Vec<(NodeId, u32)>>;
897
898/// Each element's scoping roots for each `@scope`, worked out once: an
899/// element's are its parent's, a generation farther, less those it limits,
900/// and itself if it's a root.
901#[derive(Default)]
902struct ScopeCache {
903    /// By the scope's address and the node: the roots at each level of
904    /// nesting, outermost first.
905    roots: HashMap<(usize, NodeId), Arc<Levels>>,
906}
907
908/// The scoping roots `el` is in scope of for `scope`, nearest first, each
909/// with how many generations up it is.
910fn scope_roots(scope: &Scope, doc: &Document, el: NodeId, cache: &mut ScopeCache) -> Arc<Levels> {
911    let key = |n: NodeId| (scope as *const Scope as usize, n);
912    // Up to the nearest element already done, then down from there, so
913    // nothing recurses on the document's depth.
914    let mut chain = vec![el];
915    let mut start = None;
916    let mut at = el;
917    if let Some(r) = cache.roots.get(&key(el)) {
918        return r.clone();
919    }
920    while let Some(p) = doc.parent(at) {
921        if let Some(r) = cache.roots.get(&key(p)) {
922            start = Some(r.clone());
923            break;
924        }
925        chain.push(p);
926        at = p;
927    }
928    let mut levels: Vec<&Scope> = Vec::new();
929    let mut s = Some(scope);
930    while let Some(x) = s {
931        levels.push(x);
932        s = x.outer.as_deref();
933    }
934    levels.reverse();
935    let owner_root = |o: &Option<NodeId>| o.and_then(|o| doc.parent(o)).unwrap_or(doc.root());
936    let mut roots: Levels = match start {
937        Some(r) => (*r).clone(),
938        None => vec![Vec::new(); levels.len()],
939    };
940    for &n in chain.iter().rev() {
941        let element = matches!(doc.kind(n), Kind::Element { .. });
942        for i in 0..levels.len() {
943            let sc = levels[i];
944            for r in &mut roots[i] {
945                r.1 += 1;
946            }
947            // A limit, and what's under it, is out of its root's scope.
948            if let Some(end) = &sc.end
949                && element
950            {
951                roots[i].retain(|(r, _)| !end.matches(doc, n, Some(*r)));
952            }
953            let is_root = match &sc.start {
954                ScopeStart::Owner(o) => n == owner_root(o),
955                ScopeStart::Selector(sel) => {
956                    element
957                        && if i == 0 {
958                            sel.matches(doc, n, None)
959                        } else {
960                            roots[i - 1]
961                                .iter()
962                                .any(|(r, _)| sel.matches(doc, n, Some(*r)))
963                        }
964                }
965            };
966            // A root that's its own limit, `to (:scope)`, scopes nothing.
967            let own_limit = is_root
968                && sc
969                    .end
970                    .as_ref()
971                    .is_some_and(|end| end.matches(doc, n, Some(n)));
972            if is_root && !own_limit {
973                roots[i].insert(0, (n, 0));
974            }
975        }
976        cache.roots.insert(key(n), Arc::new(roots.clone()));
977    }
978    cache.roots[&key(el)].clone()
979}
980
981/// Origin and importance as one rank: normal user agent, user, author,
982/// then important author, user, user agent.
983fn rank(origin: u8, important: bool) -> u8 {
984    if important { 5 - origin } else { origin }
985}
986
987fn trim<'v, 'a>(values: &'v [ComponentValue<'a>]) -> &'v [ComponentValue<'a>] {
988    let start = values
989        .iter()
990        .position(|v| !v.is_whitespace())
991        .unwrap_or(values.len());
992    let end = values
993        .iter()
994        .rposition(|v| !v.is_whitespace())
995        .map_or(start, |i| i + 1);
996    &values[start..end]
997}
998
999fn elements(doc: &Document) -> impl Iterator<Item = NodeId> + '_ {
1000    // Every node in document order, elements only.
1001    let mut stack = vec![doc.root()];
1002    std::iter::from_fn(move || {
1003        while let Some(n) = stack.pop() {
1004            let children: Vec<NodeId> = doc.children(n).collect();
1005            stack.extend(children.into_iter().rev());
1006            if matches!(doc.kind(n), Kind::Element { .. }) {
1007                return Some(n);
1008            }
1009        }
1010        None
1011    })
1012}
1013
1014fn doc_element(doc: &Document) -> Option<NodeId> {
1015    doc.children(doc.root())
1016        .find(|n| matches!(doc.kind(*n), Kind::Element { .. }))
1017}
1018
1019#[derive(Clone, Debug, PartialEq)]
1020enum Bucket {
1021    Id(String),
1022    Class(String),
1023    Tag(String),
1024    /// `[name…]`: an attribute the element must have.
1025    Attr(String),
1026    Universal,
1027}
1028
1029#[derive(Default)]
1030struct Index {
1031    ids: HashMap<String, Vec<usize>>,
1032    classes: HashMap<String, Vec<usize>>,
1033    tags: HashMap<String, Vec<usize>>,
1034    attrs: HashMap<String, Vec<usize>>,
1035    universal: Vec<usize>,
1036}
1037
1038/// The id, class or type a complex selector's rightmost compound needs,
1039/// read from its text; universal when that can't be told simply.
1040fn bucket(selector: &str) -> Bucket {
1041    if selector.contains('\\') {
1042        return Bucket::Universal;
1043    }
1044    // The rightmost compound: after the last combinator outside brackets.
1045    let b = selector.as_bytes();
1046    let (mut depth, mut start) = (0i32, 0);
1047    for (i, c) in b.iter().enumerate() {
1048        match c {
1049            b'(' | b'[' => depth += 1,
1050            b')' | b']' => depth -= 1,
1051            b' ' | b'>' | b'+' | b'~' if depth == 0 => start = i + 1,
1052            _ => {}
1053        }
1054    }
1055    let compound = &selector[start..];
1056    let name_end = |s: &str| {
1057        s.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
1058            .unwrap_or(s.len())
1059    };
1060    // Only what's outside any brackets counts.
1061    let (mut depth, mut i) = (0i32, 0);
1062    let cb = compound.as_bytes();
1063    let (mut id, mut class, mut attr) = (None, None, None);
1064    while i < cb.len() {
1065        match cb[i] {
1066            b'[' if depth == 0 && attr.is_none() => {
1067                let rest = compound[i + 1..].trim_start();
1068                let n = name_end(rest);
1069                // `[ns|name]` and the like stay universal.
1070                if n > 0 && !rest[n..].starts_with('|') {
1071                    attr = Some(rest[..n].to_ascii_lowercase());
1072                }
1073                depth += 1;
1074            }
1075            b'(' | b'[' => depth += 1,
1076            b')' | b']' => depth -= 1,
1077            b'#' if depth == 0 && id.is_none() => {
1078                let n = name_end(&compound[i + 1..]);
1079                if n > 0 {
1080                    id = Some(compound[i + 1..i + 1 + n].to_string());
1081                }
1082            }
1083            b'.' if depth == 0 && class.is_none() => {
1084                let n = name_end(&compound[i + 1..]);
1085                if n > 0 {
1086                    class = Some(compound[i + 1..i + 1 + n].to_string());
1087                }
1088            }
1089            _ => {}
1090        }
1091        i += 1;
1092    }
1093    if let Some(id) = id {
1094        return Bucket::Id(id);
1095    }
1096    if let Some(class) = class {
1097        return Bucket::Class(class);
1098    }
1099    let n = name_end(compound);
1100    if n > 0 && compound.as_bytes()[0].is_ascii_alphabetic() && !compound[n..].starts_with('|') {
1101        return Bucket::Tag(compound[..n].to_ascii_lowercase());
1102    }
1103    attr.map_or(Bucket::Universal, Bucket::Attr)
1104}
1105
1106/// Cascade layers, in the order they were first named. Each layer's
1107/// rank sorts its sublayers before its own declarations, and unlayered
1108/// declarations last of all (§6.4).
1109#[derive(Default)]
1110struct Layers {
1111    /// Every layer's full name, `a.b`, in the order first seen; index 0
1112    /// is the unlayered declarations.
1113    names: Vec<Vec<String>>,
1114}
1115
1116impl Layers {
1117    fn id(&mut self, path: &[String]) -> usize {
1118        if self.names.is_empty() {
1119            self.names.push(Vec::new());
1120        }
1121        // Naming `a.b` names `a` first.
1122        for n in 1..path.len() {
1123            if !self.names.iter().any(|p| p == &path[..n]) {
1124                self.names.push(path[..n].to_vec());
1125            }
1126        }
1127        match self.names.iter().position(|p| p == path) {
1128            Some(i) => i,
1129            None => {
1130                self.names.push(path.to_vec());
1131                self.names.len() - 1
1132            }
1133        }
1134    }
1135
1136    /// Each layer's rank: higher wins for normal declarations.
1137    fn ranks(&mut self) -> Vec<u32> {
1138        if self.names.is_empty() {
1139            self.names.push(Vec::new());
1140        }
1141        // Order of first mention among siblings, depth first, a layer
1142        // after its sublayers; unlayered (the empty path) at the end.
1143        let mut order: Vec<usize> = (0..self.names.len()).collect();
1144        let first = |path: &[String], names: &[Vec<String>]| -> Vec<usize> {
1145            (1..=path.len())
1146                .map(|n| names.iter().position(|p| p[..] == path[..n]).unwrap())
1147                .collect()
1148        };
1149        let keys: Vec<Vec<usize>> = self
1150            .names
1151            .iter()
1152            .map(|p| {
1153                let mut k = first(p, &self.names);
1154                // A layer's own declarations come after its sublayers.
1155                k.push(usize::MAX);
1156                k
1157            })
1158            .collect();
1159        order.sort_by(|a, b| {
1160            let (ka, kb) = (&keys[*a], &keys[*b]);
1161            ka.cmp(kb)
1162        });
1163        let mut ranks = vec![0; self.names.len()];
1164        for (r, i) in order.iter().enumerate() {
1165            ranks[*i] = r as u32;
1166        }
1167        // The unlayered sort last: its key is just [MAX].
1168        ranks
1169    }
1170}
1171
1172struct Collect<'c, 's> {
1173    env: &'c Environment,
1174    origin: Origin,
1175    layers: &'c mut Layers,
1176    entries: &'c mut Vec<Entry<'s>>,
1177    order: &'c mut u32,
1178    owner: Option<NodeId>,
1179    scope: Option<Arc<Scope>>,
1180    containers: Vec<Arc<Vec<ContainerQuery>>>,
1181    at: &'c mut Collected,
1182}
1183
1184/// One stylesheet to collect: its text, where it's from, and the layer
1185/// an `@import` put it in; or, with no text, layers to name first.
1186struct Unit {
1187    css: String,
1188    origin: Origin,
1189    owner: Option<NodeId>,
1190    layer: Vec<String>,
1191    declare: Vec<Vec<String>>,
1192    /// The `scope()`s `@import`s put its rules in, outermost first.
1193    scopes: Vec<ScopeBounds>,
1194}
1195
1196impl Unit {
1197    fn layers(declare: Vec<Vec<String>>) -> Unit {
1198        Unit {
1199            css: String::new(),
1200            origin: Origin::Author,
1201            owner: None,
1202            layer: Vec::new(),
1203            declare,
1204            scopes: Vec::new(),
1205        }
1206    }
1207}
1208
1209/// `@layer a.b, c`'s names, each as its parts.
1210fn layer_names(prelude: &[ComponentValue<'_>]) -> Vec<Vec<String>> {
1211    prelude
1212        .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
1213        .map(|n| {
1214            crate::to_css(n)
1215                .trim()
1216                .split('.')
1217                .map(|p| p.trim().to_string())
1218                .filter(|p| !p.is_empty())
1219                .collect()
1220        })
1221        .collect()
1222}
1223
1224/// The named at-rules as collected, each with its layer and order.
1225#[derive(Default)]
1226struct Collected {
1227    keyframes: Vec<(usize, u32, Keyframes)>,
1228    counter_styles: Vec<(usize, u32, CounterStyle)>,
1229    properties: Vec<(usize, u32, PropertyRule)>,
1230}
1231
1232impl Collected {
1233    /// For each name, the rule that's last in the cascade's order.
1234    fn resolved(&self, ranks: &[u32]) -> AtRules {
1235        fn last<T: Clone>(
1236            items: &[(usize, u32, T)],
1237            ranks: &[u32],
1238            name: impl Fn(&T) -> &str,
1239        ) -> Vec<T> {
1240            let mut sorted: Vec<&(usize, u32, T)> = items.iter().collect();
1241            sorted.sort_by_key(|(l, o, _)| (ranks.get(*l).copied().unwrap_or(0), *o));
1242            let mut out: Vec<T> = Vec::new();
1243            for (_, _, t) in sorted {
1244                out.retain(|x| name(x) != name(t));
1245                out.push(t.clone());
1246            }
1247            out
1248        }
1249        AtRules {
1250            keyframes: last(&self.keyframes, ranks, |k| &k.name),
1251            counter_styles: last(&self.counter_styles, ranks, |c| &c.name),
1252            properties: last(&self.properties, ranks, |p| &p.name),
1253        }
1254    }
1255}
1256
1257/// The parent "selector" of the rules straight inside an `@scope`.
1258const IN_SCOPE: &str = "\u{1}scope";
1259
1260/// How deep `@scope`s may nest; deeper ones are ignored, since each level
1261/// multiplies the work of finding roots.
1262const MAX_SCOPE_DEPTH: usize = 8;
1263
1264/// A prelude's complex selectors, each as text.
1265fn complex_selectors(prelude: &[ComponentValue<'_>]) -> Vec<String> {
1266    prelude
1267        .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
1268        .map(|p| crate::to_css(p).trim().to_string())
1269        .collect()
1270}
1271
1272/// A nested selector against its parent's: `&` replaced by `:is(parent)`,
1273/// or the parent put in front, as CSS Nesting reads them.
1274fn nest(selector: &str, parents: &[String]) -> String {
1275    if parents.is_empty() {
1276        return selector.to_string();
1277    }
1278    // In `@scope`, CSS Cascade 6 §3.5.1: `&` is `:where(:scope)`, and a
1279    // selector without `:scope` or `&` is under the root.
1280    if parents == [IN_SCOPE] {
1281        let scope = ":where(:scope)";
1282        if selector.contains('&') {
1283            return selector.replace('&', scope);
1284        }
1285        if selector.contains(":scope") {
1286            return selector.to_string();
1287        }
1288        return format!("{scope} {selector}");
1289    }
1290    let parent = format!(":is({})", parents.join(", "));
1291    if selector.contains('&') {
1292        return selector.replace('&', &parent);
1293    }
1294    format!("{parent} {selector}")
1295}
1296
1297impl<'s> Collect<'_, 's> {
1298    /// Makes `bounds` the scope rules are collected in, inside the one
1299    /// they're in now; `false` if its selectors don't parse or scopes
1300    /// nest too deep.
1301    fn enter_scope(&mut self, bounds: &ScopeBounds, parents: &[String]) -> bool {
1302        let mut depth = 0;
1303        let mut s = self.scope.as_deref();
1304        while let Some(x) = s {
1305            depth += 1;
1306            s = x.outer.as_deref();
1307        }
1308        if depth >= MAX_SCOPE_DEPTH {
1309            return false;
1310        }
1311        // Real parents: a style rule's selectors.
1312        let parents: Vec<String> = parents.iter().filter(|p| *p != IN_SCOPE).cloned().collect();
1313        let start = match &bounds.start {
1314            Some(sel) => match SelectorList::parse(&nest(sel, &parents)) {
1315                Ok(l) => ScopeStart::Selector(l),
1316                Err(_) => return false,
1317            },
1318            None if !parents.is_empty() => match SelectorList::parse(&parents.join(", ")) {
1319                Ok(l) => ScopeStart::Selector(l),
1320                Err(_) => return false,
1321            },
1322            None => ScopeStart::Owner(self.owner),
1323        };
1324        let end = match &bounds.end {
1325            Some(sel) => match SelectorList::parse(sel) {
1326                Ok(l) => Some(l),
1327                Err(_) => return false,
1328            },
1329            None => None,
1330        };
1331        self.scope = Some(Arc::new(Scope {
1332            start,
1333            end,
1334            outer: self.scope.take(),
1335        }));
1336        true
1337    }
1338
1339    fn rules(&mut self, rules: &'s [Rule<'s, Block<'s>>], parents: &[String], layer: &[String]) {
1340        for r in rules {
1341            self.rule(r, parents, layer);
1342        }
1343    }
1344
1345    fn items(&mut self, items: &'s [Item<'s, Block<'s>>], parents: &[String], layer: &[String]) {
1346        // Declarations straight in a nested group rule belong to the
1347        // parent's selector.
1348        let declarations: Vec<_> = items
1349            .iter()
1350            .filter_map(|i| match i {
1351                Item::Declaration(d) => Some((&*d.name, &d.value[..], d.important)),
1352                _ => None,
1353            })
1354            .collect();
1355        if !declarations.is_empty() && !parents.is_empty() {
1356            self.push(parents, declarations, layer);
1357        }
1358        for i in items {
1359            if let Item::Rule(r) = i {
1360                self.rule(r, parents, layer);
1361            }
1362        }
1363    }
1364
1365    fn push(
1366        &mut self,
1367        selectors: &[String],
1368        declarations: Vec<(&'s str, &'s [ComponentValue<'s>], bool)>,
1369        layer: &[String],
1370    ) {
1371        let layer = self.layers.id(layer);
1372        for s in selectors {
1373            let s = if s == IN_SCOPE {
1374                ":where(:scope)"
1375            } else {
1376                s.as_str()
1377            };
1378            let Ok(list) = SelectorList::parse(s) else {
1379                continue;
1380            };
1381            // A pseudo-element's rule matches its originating element, and
1382            // counts the pseudo-element in its specificity.
1383            let specificity = list.specificity();
1384            let mut origin_any = false;
1385            let (bucket, list, pseudo) = match split_pseudo(s) {
1386                Split::No => (bucket(s), list, None),
1387                // Only after a state, or as part of another pseudo-element.
1388                Split::Unstyled => continue,
1389                Split::Pseudo(origin, p) => match SelectorList::parse(&origin) {
1390                    Ok(l) => {
1391                        origin_any = origin == "*";
1392                        (bucket(&origin), l, Some(p))
1393                    }
1394                    Err(_) => continue,
1395                },
1396            };
1397            *self.order += 1;
1398            self.entries.push(Entry {
1399                bucket,
1400                specificity,
1401                selector: list,
1402                origin: self.origin,
1403                layer,
1404                order: *self.order,
1405                declarations: declarations.clone(),
1406                scope: self.scope.clone(),
1407                containers: self.containers.clone(),
1408                any: origin_any,
1409                pseudo,
1410            });
1411        }
1412    }
1413
1414    fn rule(&mut self, r: &'s Rule<'s, Block<'s>>, parents: &[String], layer: &[String]) {
1415        match r {
1416            Rule::Qualified(q) => {
1417                let selectors: Vec<String> = complex_selectors(&q.prelude)
1418                    .iter()
1419                    .map(|s| nest(s, parents))
1420                    .collect();
1421                // A selector list with one bad selector is no rule at all.
1422                if selectors.iter().any(|s| SelectorList::parse(s).is_err()) {
1423                    return;
1424                }
1425                let declarations = q
1426                    .block
1427                    .items
1428                    .iter()
1429                    .filter_map(|i| match i {
1430                        Item::Declaration(d) => Some((&*d.name, &d.value[..], d.important)),
1431                        _ => None,
1432                    })
1433                    .collect();
1434                self.push(&selectors, declarations, layer);
1435                for i in &q.block.items {
1436                    if let Item::Rule(r) = i {
1437                        self.rule(r, &selectors, layer);
1438                    }
1439                }
1440            }
1441            Rule::At(a) => {
1442                let name = a.name.to_ascii_lowercase();
1443                match name.as_str() {
1444                    "media" => {
1445                        if MediaQueryList::parse(&a.prelude).matches(self.env)
1446                            && let Some(b) = &a.block
1447                        {
1448                            self.items(&b.items, parents, layer);
1449                        }
1450                    }
1451                    "supports" => {
1452                        if crate::supports::supports(&a.prelude) == Some(true)
1453                            && let Some(b) = &a.block
1454                        {
1455                            self.items(&b.items, parents, layer);
1456                        }
1457                    }
1458                    "container" => {
1459                        if let (Some(queries), Some(b)) =
1460                            (ContainerQuery::parse_list(&a.prelude), &a.block)
1461                        {
1462                            self.containers.push(Arc::new(queries));
1463                            self.items(&b.items, parents, layer);
1464                            self.containers.pop();
1465                        }
1466                    }
1467                    "scope" => {
1468                        let (Some(bounds), Some(b)) = (ScopeBounds::parse(&a.prelude), &a.block)
1469                        else {
1470                            return;
1471                        };
1472                        let outer = self.scope.clone();
1473                        if self.enter_scope(&bounds, parents) {
1474                            self.items(&b.items, &[IN_SCOPE.to_string()], layer);
1475                        }
1476                        self.scope = outer;
1477                    }
1478                    "keyframes" | "-webkit-keyframes" | "counter-style" | "property" => {
1479                        let l = self.layers.id(layer);
1480                        *self.order += 1;
1481                        let o = *self.order;
1482                        if let Some(k) = Keyframes::parse(a) {
1483                            self.at.keyframes.push((l, o, k));
1484                        } else if let Some(c) = CounterStyle::parse(a) {
1485                            self.at.counter_styles.push((l, o, c));
1486                        } else if let Some(p) = PropertyRule::parse(a) {
1487                            self.at.properties.push((l, o, p));
1488                        }
1489                    }
1490                    "layer" => {
1491                        let names = layer_names(&a.prelude);
1492                        match &a.block {
1493                            // `@layer a, b;` names them, in that order.
1494                            None => {
1495                                for n in &names {
1496                                    let mut path = layer.to_vec();
1497                                    path.extend(n.iter().cloned());
1498                                    self.layers.id(&path);
1499                                }
1500                            }
1501                            Some(b) => {
1502                                let mut path = layer.to_vec();
1503                                match names.first() {
1504                                    Some(n) if !n.is_empty() && names.len() == 1 => {
1505                                        path.extend(n.iter().cloned())
1506                                    }
1507                                    Some(n) if !n.is_empty() => return,
1508                                    // An anonymous layer, its own each time.
1509                                    _ => path.push(format!("\u{0}{}", *self.order)),
1510                                }
1511                                *self.order += 1;
1512                                self.layers.id(&path);
1513                                self.items(&b.items, parents, &path);
1514                            }
1515                        }
1516                    }
1517                    _ => {}
1518                }
1519            }
1520        }
1521    }
1522}
1523
1524/// The CSS-wide keyword a value is, if it is one.
1525pub(crate) fn css_wide(v: &Specified<'_>) -> Option<CssWide> {
1526    match v {
1527        Specified::CssWide(k) => Some(*k),
1528        _ => None,
1529    }
1530}
1531
1532#[cfg(test)]
1533mod tests {
1534    use super::*;
1535
1536    fn style(html: &str, sel: &str, property: &str) -> String {
1537        let doc = parsec::parse(html, false);
1538        let styled = Styler::new(Environment::default())
1539            .with_document_styles(&doc)
1540            .style(&doc);
1541        let el = SelectorList::parse(sel)
1542            .unwrap()
1543            .select_first(&doc, doc.root())
1544            .unwrap();
1545        styled.get(el, property).unwrap_or_default()
1546    }
1547
1548    #[test]
1549    fn origins_importance_and_style_attributes() {
1550        let html = "<style>p { color: red !important } #a { color: blue }</style><p id=a style='color: green'>";
1551        assert_eq!(style(html, "p", "color"), "rgb(255, 0, 0)");
1552        let html = "<style>#a { color: blue }</style><p id=a style='color: green'>";
1553        assert_eq!(style(html, "p", "color"), "rgb(0, 128, 0)");
1554        let html = "<style>p { color: red !important }</style><p style='color: green !important'>";
1555        assert_eq!(style(html, "p", "color"), "rgb(0, 128, 0)");
1556        // The user agent's `display: block` loses to the author's.
1557        assert_eq!(
1558            style(
1559                "<style>div { display: inline }</style><div>",
1560                "div",
1561                "display"
1562            ),
1563            "inline"
1564        );
1565    }
1566
1567    #[test]
1568    fn layers_order_and_importance() {
1569        let css = "@layer a, b; @layer b { p { color: green } } @layer a { p { color: red } }";
1570        assert_eq!(
1571            style(&format!("<style>{css}</style><p>"), "p", "color"),
1572            "rgb(0, 128, 0)"
1573        );
1574        // Unlayered beats layered, unless important, where it's the other way.
1575        let css = "p { color: green } @layer x { p { color: red } }";
1576        assert_eq!(
1577            style(&format!("<style>{css}</style><p>"), "p", "color"),
1578            "rgb(0, 128, 0)"
1579        );
1580        let css = "p { color: red !important } @layer x { p { color: green !important } }";
1581        assert_eq!(
1582            style(&format!("<style>{css}</style><p>"), "p", "color"),
1583            "rgb(0, 128, 0)"
1584        );
1585        // A layer's sublayers come before its own rules.
1586        let css = "@layer a { p { color: green } @layer b { p { color: red } } }";
1587        assert_eq!(
1588            style(&format!("<style>{css}</style><p>"), "p", "color"),
1589            "rgb(0, 128, 0)"
1590        );
1591    }
1592
1593    #[test]
1594    fn revert_and_revert_layer() {
1595        let html = "<style>div { display: inline } div { display: revert }</style><div>";
1596        assert_eq!(style(html, "div", "display"), "block");
1597        let css = "@layer a { p { color: green } } @layer b { p { color: revert-layer } }";
1598        assert_eq!(
1599            style(&format!("<style>{css}</style><p>"), "p", "color"),
1600            "rgb(0, 128, 0)"
1601        );
1602        let html =
1603            "<style>.r { all: revert }</style><style>div { display: inline }</style><div class=r>";
1604        assert_eq!(style(html, "div", "display"), "block");
1605    }
1606
1607    #[test]
1608    fn inheritance_and_keywords() {
1609        let html = "<div style='color: blue; margin-top: 3px; font-size: 20px'><p style='width: inherit'></div>";
1610        assert_eq!(style(html, "p", "color"), "rgb(0, 0, 255)");
1611        assert_eq!(style(html, "p", "margin-top"), "0px");
1612        let html = "<div style='font-size: 20px'><p style='font-size: 1.5em; line-height: 2em; margin-left: calc(1em + 2px)'></div>";
1613        assert_eq!(style(html, "p", "font-size"), "30px");
1614        assert_eq!(style(html, "p", "line-height"), "60px");
1615        assert_eq!(style(html, "p", "margin-left"), "32px");
1616        let html = "<div style='color: red'><p style='color: unset; border-top: 2px solid; border-bottom-width: 9px'></div>";
1617        assert_eq!(style(html, "p", "color"), "rgb(255, 0, 0)");
1618        assert_eq!(style(html, "p", "border-top-color"), "rgb(255, 0, 0)");
1619        assert_eq!(style(html, "p", "border-top-width"), "2px");
1620        // No style, no width.
1621        assert_eq!(style(html, "p", "border-bottom-width"), "0px");
1622        assert_eq!(style("<b><i>x", "b", "font-weight"), "700");
1623    }
1624
1625    #[test]
1626    fn custom_properties_and_var() {
1627        let html = "<style>:root { --gap: 4px; --c: var(--d) } p { margin: calc(var(--gap) * 2) var(--nope, 1px); color: var(--c, green) }</style><p>";
1628        assert_eq!(style(html, "p", "margin-top"), "8px");
1629        assert_eq!(style(html, "p", "margin-right"), "1px");
1630        // --c refers to nothing, so it's guaranteed-invalid, and the
1631        // var() that refers to it takes its fallback.
1632        assert_eq!(style(html, "p", "color"), "rgb(0, 128, 0)");
1633        let html = "<style>p { color: red; color: var(--missing) }</style><div style='color: blue'><p></div>";
1634        // Invalid at computed-value time is `unset`: inherited here.
1635        assert_eq!(style(html, "p", "color"), "rgb(0, 0, 255)");
1636        assert_eq!(style(html, "p", "--missing"), "");
1637    }
1638
1639    #[test]
1640    fn media_supports_and_nesting() {
1641        let css = "@media (min-width: 2000px) { p { color: red } } @supports (display: grid) { p { margin-top: 1px } } \
1642                   @supports (display: nonsense) { p { margin-top: 9px } } div { & > p { color: green } }";
1643        let html = format!("<style>{css}</style><div><p></div>");
1644        assert_eq!(style(&html, "p", "color"), "rgb(0, 128, 0)");
1645        assert_eq!(style(&html, "p", "margin-top"), "1px");
1646        let html = "<style media='print'>p { color: red }</style><p>";
1647        assert_eq!(style(html, "p", "color"), "rgb(0, 0, 0)");
1648    }
1649
1650    #[test]
1651    fn scope_and_proximity() {
1652        let html = "<style>@scope (.a) { p { color: green } } @scope (.b) to (.c) { p { color: blue } }</style>\
1653                    <div class=a><p id=one></p><div class=b><p id=two></p><div class=c><p id=three></p></div></div></div><p id=four>";
1654        assert_eq!(style(html, "#one", "color"), "rgb(0, 128, 0)");
1655        // .b is nearer than .a, so its rule wins though it's not later.
1656        let html2 = html
1657            .replace("@scope (.b) to (.c) { p { color: blue } }", "")
1658            .replace(
1659                "<style>",
1660                "<style>@scope (.b) to (.c) { p { color: blue } }",
1661            );
1662        assert_eq!(style(&html2, "#two", "color"), "rgb(0, 0, 255)");
1663        // Past the limit only .a's applies.
1664        assert_eq!(style(html, "#three", "color"), "rgb(0, 128, 0)");
1665        assert_eq!(style(html, "#four", "color"), "rgb(0, 0, 0)");
1666        // `:scope` itself, and declarations straight in the rule.
1667        let html = "<style>@scope (.a) { :scope { color: green } } @scope (.b) { color: blue }</style><div class=a></div><div class=b>";
1668        assert_eq!(style(html, ".a", "color"), "rgb(0, 128, 0)");
1669        assert_eq!(style(html, ".b", "color"), "rgb(0, 0, 255)");
1670        // With no root: the <style>'s parent.
1671        let html = "<div id=x><style>@scope { p { color: green } }</style><p></p></div><p id=y>";
1672        assert_eq!(style(html, "#x p", "color"), "rgb(0, 128, 0)");
1673        assert_eq!(style(html, "#y", "color"), "rgb(0, 0, 0)");
1674    }
1675
1676    #[test]
1677    fn container_units_and_style_ranges() {
1678        // `cqw` from the inline-size container, `cqh` from the size one
1679        // beyond it, and the small viewport's with no container.
1680        let doc = parsec::parse(
1681            "<style>.s { container-type: size } .i { container-type: inline-size } \
1682             p { width: 10cqw; height: 10cqh; margin-left: 10cqi; margin-top: 10cqmax }</style>\
1683             <div class=s id=s><div class=i id=i><p></p></div></div><p id=bare>",
1684            false,
1685        );
1686        let find = |s: &str| {
1687            SelectorList::parse(s)
1688                .unwrap()
1689                .select_first(&doc, doc.root())
1690                .unwrap()
1691        };
1692        let styled = Styler::new(Environment::default())
1693            .with_document_styles(&doc)
1694            .container_sizes(|_, c| {
1695                Some(match c.get("container-type").as_deref() {
1696                    Some("size") => (1000.0, 500.0),
1697                    _ => (200.0, 50.0),
1698                })
1699            })
1700            .style(&doc);
1701        let p = find("#i p");
1702        assert_eq!(styled.get(p, "width").as_deref(), Some("20px"));
1703        assert_eq!(styled.get(p, "height").as_deref(), Some("50px"));
1704        assert_eq!(styled.get(p, "margin-left").as_deref(), Some("20px"));
1705        assert_eq!(styled.get(p, "margin-top").as_deref(), Some("50px"));
1706        let bare = find("#bare");
1707        assert_eq!(styled.get(bare, "width").as_deref(), Some("128px"));
1708        assert_eq!(styled.get(bare, "height").as_deref(), Some("72px"));
1709
1710        // A range in `style()`, with a custom property's value and `em`
1711        // on the container.
1712        let doc = parsec::parse(
1713            "<style>.c { --n: 30px; font-size: 10px } @container style(2em < --n <= 3em) { p { color: green } } \
1714             @container style(--n > 5) { p { background-color: red } }</style><div class=c><p>",
1715            false,
1716        );
1717        let p = SelectorList::parse("p")
1718            .unwrap()
1719            .select_first(&doc, doc.root())
1720            .unwrap();
1721        let styled = Styler::new(Environment::default())
1722            .with_document_styles(&doc)
1723            .style(&doc);
1724        assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(0, 128, 0)"));
1725        // A length against a number is false, not unknown.
1726        assert_eq!(
1727            styled.get(p, "background-color").as_deref(),
1728            Some("rgba(0, 0, 0, 0)")
1729        );
1730    }
1731
1732    #[test]
1733    fn containers_imports_and_registrations() {
1734        let doc = parsec::parse(
1735            "<style>.c { container: card / inline-size } @container card (width > 400px) { p { color: green } }</style><div class=c><p>",
1736            false,
1737        );
1738        let p = SelectorList::parse("p")
1739            .unwrap()
1740            .select_first(&doc, doc.root())
1741            .unwrap();
1742        let wide = Styler::new(Environment::default())
1743            .with_document_styles(&doc)
1744            .container_sizes(|_, _| Some((500.0, 100.0)))
1745            .style(&doc);
1746        assert_eq!(wide.get(p, "color").as_deref(), Some("rgb(0, 128, 0)"));
1747        let narrow = Styler::new(Environment::default())
1748            .with_document_styles(&doc)
1749            .container_sizes(|_, _| Some((300.0, 100.0)))
1750            .style(&doc);
1751        assert_eq!(narrow.get(p, "color").as_deref(), Some("rgb(0, 0, 0)"));
1752
1753        let doc = parsec::parse(
1754            "<style>@import 'a.css' layer(x); p { color: red } @layer x { p { color: blue } }</style><p>",
1755            false,
1756        );
1757        let p = SelectorList::parse("p")
1758            .unwrap()
1759            .select_first(&doc, doc.root())
1760            .unwrap();
1761        let styled = Styler::new(Environment::default())
1762            .with_document_styles(&doc)
1763            .fetch(|url| {
1764                (url == "a.css").then(|| "p { margin-top: 3px; color: green }".to_string())
1765            })
1766            .style(&doc);
1767        assert_eq!(styled.get(p, "margin-top").as_deref(), Some("3px"));
1768        // Unlayered beats layer x, imports included.
1769        assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(255, 0, 0)"));
1770
1771        let html = "<style>@property --w { syntax: '<length>'; inherits: false; initial-value: 2px } \
1772                    div { --w: 2em; font-size: 10px } p { --w: oops }</style><div><p></p></div>";
1773        assert_eq!(style(html, "div", "--w"), "20px");
1774        // Not inherited, and an invalid value is the initial one.
1775        assert_eq!(style(html, "p", "--w"), "2px");
1776    }
1777
1778    #[test]
1779    fn at_rules() {
1780        let mut s = Styler::bare(Environment::default());
1781        s.add(
1782            "@keyframes a { to { opacity: 0 } } @layer l { @keyframes a { to { opacity: 1 } } } \
1783             @counter-style c { system: cyclic; symbols: x } @media (min-width: 9999px) { @keyframes b {} }",
1784            Origin::Author,
1785        );
1786        let r = s.at_rules();
1787        assert_eq!(r.keyframes.len(), 1);
1788        assert_eq!(r.keyframes[0].frames[0].declarations[0].1, "0");
1789        assert_eq!(r.counter_styles[0].name, "c");
1790    }
1791
1792    #[test]
1793    fn buckets() {
1794        assert_eq!(bucket("div > p.x"), Bucket::Class("x".into()));
1795        assert_eq!(bucket("#a:hover"), Bucket::Id("a".into()));
1796        assert_eq!(bucket("a[href]"), Bucket::Tag("a".into()));
1797        assert_eq!(bucket("[data-x]"), Bucket::Attr("data-x".into()));
1798        assert_eq!(bucket(":is(.a, .b)"), Bucket::Universal);
1799        assert_eq!(bucket("svg|a"), Bucket::Universal);
1800    }
1801}