Skip to main content

parsec_css/values/
properties.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Every property in the CSS specs, from w3c/webref's data: its grammar,
5//! initial value, whether it inherits, and its longhands if it's a
6//! shorthand. `generated.rs` holds the table; this is the way in.
7
8use std::collections::HashSet;
9use std::sync::OnceLock;
10
11use super::generated::{FUNCTIONS, PROPERTIES, TYPES};
12use super::grammar::Grammar;
13
14/// One property, as its spec defines it.
15#[derive(Debug, PartialEq, Eq)]
16pub struct PropertyData {
17    pub name: &'static str,
18    /// The value grammar, in the value definition syntax; `None` for the
19    /// few legacy aliases defined only by what they alias.
20    pub syntax: Option<&'static str>,
21    /// The initial value as the spec writes it, which for a shorthand is
22    /// prose ("see individual properties").
23    pub initial: Option<&'static str>,
24    /// `None` where the spec says something other than yes or no, as a
25    /// shorthand's "see individual properties".
26    pub inherited: Option<bool>,
27    /// For a shorthand, the longhands it sets; empty for a longhand.
28    pub longhands: &'static [&'static str],
29    /// For a legacy alias (`-webkit-box-flex` and the like), the property
30    /// it's another name for.
31    pub alias_of: Option<&'static str>,
32    /// Where the spec defines it.
33    pub href: &'static str,
34}
35
36/// A property: [`PropertyData`] with its grammar parsed.
37pub type Property = PropertyData;
38
39impl PropertyData {
40    pub fn is_shorthand(&self) -> bool {
41        !self.longhands.is_empty()
42    }
43
44    /// Where this is in the table, from its address, so no lookup by
45    /// name; a `PropertyData` made elsewhere is looked up.
46    pub(crate) fn position(&self) -> Option<usize> {
47        let at = (self as *const PropertyData as usize).wrapping_sub(PROPERTIES.as_ptr() as usize)
48            / std::mem::size_of::<PropertyData>();
49        match PROPERTIES.get(at) {
50            Some(p) if std::ptr::eq(p, self) => Some(at),
51            _ => index(self.name),
52        }
53    }
54
55    /// Every keyword its grammar has outside functions, through the types
56    /// and properties it refers to: what a `<custom-ident>` in its value
57    /// can't be, by Values 4 ยง4.2's rule that a keyword some other part of
58    /// the grammar can take isn't an identifier of the author's.
59    pub(crate) fn keywords(&self) -> &'static Keywords {
60        static ALL: OnceLock<Vec<OnceLock<Keywords>>> = OnceLock::new();
61        static NONE: OnceLock<Keywords> = OnceLock::new();
62        let all = ALL.get_or_init(|| PROPERTIES.iter().map(|_| OnceLock::new()).collect());
63        let (Some(i), Some(g)) = (self.position(), self.grammar()) else {
64            return NONE.get_or_init(Keywords::default);
65        };
66        all[i].get_or_init(|| keywords_of(g))
67    }
68
69    /// Whether a lone identifier that isn't one of its keywords can be a
70    /// value of it: a name, a color's, or anything for a grammar that takes
71    /// tokens as they are.
72    pub(crate) fn takes_names(&self) -> bool {
73        static ALL: OnceLock<Vec<OnceLock<bool>>> = OnceLock::new();
74        let all = ALL.get_or_init(|| PROPERTIES.iter().map(|_| OnceLock::new()).collect());
75        let (Some(i), Some(g)) = (self.position(), self.grammar()) else {
76            return true;
77        };
78        *all[i].get_or_init(|| names_in(g))
79    }
80
81    /// The grammar of its value, parsed: the alias target's for an alias.
82    pub fn grammar(&self) -> Option<&'static Grammar> {
83        let grammars = grammars();
84        let i = self.position()?;
85        if let Some(g) = &grammars.properties[i] {
86            return Some(g);
87        }
88        let target = property(self.alias_of?)?;
89        grammars.properties[index(target.name)?].as_ref()
90    }
91}
92
93/// Looks a property up by name, ignoring ASCII case.
94///
95/// ```
96/// let p = parsec_css::values::property("Margin-Top").unwrap();
97/// assert_eq!((p.name, p.initial, p.inherited), ("margin-top", Some("0"), Some(false)));
98/// assert!(parsec_css::values::property("margin").unwrap().is_shorthand());
99/// ```
100pub fn property(name: &str) -> Option<&'static Property> {
101    index(name).map(|i| &PROPERTIES[i])
102}
103
104/// Every property in the table, sorted by name.
105pub fn properties() -> &'static [Property] {
106    PROPERTIES
107}
108
109fn index(name: &str) -> Option<usize> {
110    // Open addressing on FNV-1a of the lowercased name, worked out as it's
111    // read, so no copy: this is looked up once a declaration.
112    let table = by_name();
113    let mask = table.len() - 1;
114    let mut slot = fnv_lower(name.as_bytes()) as usize & mask;
115    loop {
116        match table[slot] {
117            0 => return None,
118            i => {
119                let i = i as usize - 1;
120                let found = PROPERTIES[i].name;
121                if found.len() == name.len() && (found == name || found.eq_ignore_ascii_case(name))
122                {
123                    return Some(i);
124                }
125            }
126        }
127        slot = (slot + 1) & mask;
128    }
129}
130
131/// A hash of a name that ignores ASCII case: its first and last eight
132/// bytes and its length, so a few instructions rather than a loop. Bit
133/// 0x20 set lowercases a letter and leaves `-` and digits as they are;
134/// the comparison after it settles everything else.
135fn fnv_lower(bytes: &[u8]) -> u32 {
136    let word = |b: &[u8]| {
137        let mut w = [0u8; 8];
138        w[..b.len()].copy_from_slice(b);
139        u64::from_le_bytes(w) | 0x2020_2020_2020_2020
140    };
141    let n = bytes.len();
142    let (head, tail) = if n >= 8 {
143        (word(&bytes[..8]), word(&bytes[n - 8..]))
144    } else {
145        (word(bytes), 0)
146    };
147    let h = (head ^ tail.rotate_left(29) ^ n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
148    (h >> 32) as u32
149}
150
151/// Each property's place in the table plus one, by its name's hash; 0
152/// is an empty slot.
153fn by_name() -> &'static [u16] {
154    static TABLE: OnceLock<Vec<u16>> = OnceLock::new();
155    TABLE.get_or_init(|| {
156        let size = (PROPERTIES.len() * 2).next_power_of_two();
157        let mut t = vec![0u16; size];
158        for (i, p) in PROPERTIES.iter().enumerate() {
159            let mut slot = fnv_lower(p.name.as_bytes()) as usize & (size - 1);
160            while t[slot] != 0 {
161                slot = (slot + 1) & (size - 1);
162            }
163            t[slot] = i as u16 + 1;
164        }
165        t
166    })
167}
168
169/// FNV-1a, for the keyword sets: keywords are short.
170#[derive(Default)]
171pub(crate) struct Fnv(u64);
172
173impl std::hash::Hasher for Fnv {
174    fn finish(&self) -> u64 {
175        self.0
176    }
177
178    fn write(&mut self, bytes: &[u8]) {
179        let mut h = if self.0 == 0 {
180            0xcbf2_9ce4_8422_2325
181        } else {
182            self.0
183        };
184        for b in bytes {
185            h = (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
186        }
187        self.0 = h;
188    }
189}
190
191pub(crate) type FnvBuild = std::hash::BuildHasherDefault<Fnv>;
192
193/// A property's keywords, looked up by FNV: they're short.
194pub(crate) type Keywords = HashSet<&'static str, FnvBuild>;
195
196fn keywords_of(g: &'static Grammar) -> Keywords {
197    let mut out = Keywords::default();
198    let mut seen: HashSet<*const Grammar> = HashSet::new();
199    let mut stack = vec![g];
200    while let Some(g) = stack.pop() {
201        if !seen.insert(g) {
202            continue;
203        }
204        match g {
205            Grammar::Keyword(k) => {
206                out.insert(&**k);
207            }
208            Grammar::Type(t) => {
209                let found = match t.name.strip_suffix("()") {
210                    Some(_) => None,
211                    None => type_grammar(&t.name),
212                };
213                stack.extend(found);
214            }
215            Grammar::Property(r) => stack.extend(property(&r.name).and_then(|p| p.grammar())),
216            Grammar::Sequence(v) | Grammar::All(v) | Grammar::Any(v) | Grammar::One(v) => {
217                stack.extend(v.iter())
218            }
219            Grammar::Repeat { item, .. } | Grammar::NonEmpty(item) => stack.push(item),
220            // A function's arguments are a context of their own.
221            _ => {}
222        }
223    }
224    out
225}
226
227fn names_in(g: &'static Grammar) -> bool {
228    let mut seen: HashSet<*const Grammar> = HashSet::new();
229    let mut stack = vec![g];
230    while let Some(g) = stack.pop() {
231        if !seen.insert(g) {
232            continue;
233        }
234        match g {
235            Grammar::Type(t) => {
236                if t.name.ends_with("()") {
237                    continue;
238                }
239                match &*t.name {
240                    "ident"
241                    | "custom-ident"
242                    | "dashed-ident"
243                    | "custom-property-name"
244                    | "color"
245                    | "declaration-value"
246                    | "any-value" => return true,
247                    // A type that's prose only matches nothing.
248                    name => stack.extend(type_grammar(name)),
249                }
250            }
251            Grammar::Property(r) => stack.extend(property(&r.name).and_then(|p| p.grammar())),
252            Grammar::Sequence(v) | Grammar::All(v) | Grammar::Any(v) | Grammar::One(v) => {
253                stack.extend(v.iter())
254            }
255            Grammar::Repeat { item, .. } | Grammar::NonEmpty(item) => stack.push(item),
256            _ => {}
257        }
258    }
259    false
260}
261
262/// Every grammar in the table, parsed once, on first use.
263pub(crate) struct Grammars {
264    pub properties: Vec<Option<Grammar>>,
265    pub types: Vec<Option<Grammar>>,
266    pub functions: Vec<Option<Grammar>>,
267}
268
269pub(crate) fn grammars() -> &'static Grammars {
270    static G: OnceLock<Grammars> = OnceLock::new();
271    G.get_or_init(|| Grammars {
272        properties: PROPERTIES
273            .iter()
274            .map(|p| p.syntax.and_then(Grammar::parse))
275            .collect(),
276        types: TYPES.iter().map(|(_, s)| Grammar::parse(s)).collect(),
277        functions: FUNCTIONS.iter().map(|(_, s)| Grammar::parse(s)).collect(),
278    })
279}
280
281/// A named type's grammar, `<line-style>` say, when the specs give one.
282pub(crate) fn type_grammar(name: &str) -> Option<&'static Grammar> {
283    let i = TYPES.binary_search_by(|(n, _)| (*n).cmp(name)).ok()?;
284    grammars().types[i].as_ref()
285}
286
287/// A function's grammar, `<rect()>` say, by its name without the `()`.
288pub(crate) fn function_grammar(name: &str) -> Option<&'static Grammar> {
289    let i = FUNCTIONS.binary_search_by(|(n, _)| (*n).cmp(name)).ok()?;
290    grammars().functions[i].as_ref()
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn the_table() {
299        let longhands: Vec<_> = PROPERTIES
300            .iter()
301            .filter(|p| !p.is_shorthand() && p.alias_of.is_none())
302            .collect();
303        assert_eq!(PROPERTIES.len(), 822);
304        assert_eq!(longhands.len(), 597);
305        // Every grammar parses, aliases through their target.
306        assert!(
307            PROPERTIES
308                .iter()
309                .all(|p| p.syntax.is_none() || p.grammar().is_some())
310        );
311        // And every longhand's initial value, where the spec gives one as a
312        // value rather than prose, is a value of its own grammar.
313        let mut prose = Vec::new();
314        for p in &longhands {
315            let Some(initial) = p.initial else { continue };
316            let values = crate::parse_component_values(initial);
317            if super::super::parse_value(p.name, &values).is_err() {
318                prose.push(format!("{}: {initial}", p.name));
319            }
320        }
321        // Prose, or (`fill`, `text-spacing-trim`) a grammar whose types the
322        // data doesn't define.
323        assert_eq!(
324            prose,
325            [
326                "all: see individual properties",
327                "background-tbd: see individual properties",
328                "fill: black",
329                "glyph-orientation-vertical: n/a",
330                "text-spacing-trim: normal",
331                "voice-family: implementation-dependent",
332            ]
333        );
334    }
335}