parsec_css/values/
properties.rs1use std::collections::HashSet;
9use std::sync::OnceLock;
10
11use super::generated::{FUNCTIONS, PROPERTIES, TYPES};
12use super::grammar::Grammar;
13
14#[derive(Debug, PartialEq, Eq)]
16pub struct PropertyData {
17 pub name: &'static str,
18 pub syntax: Option<&'static str>,
21 pub initial: Option<&'static str>,
24 pub inherited: Option<bool>,
27 pub longhands: &'static [&'static str],
29 pub alias_of: Option<&'static str>,
32 pub href: &'static str,
34}
35
36pub type Property = PropertyData;
38
39impl PropertyData {
40 pub fn is_shorthand(&self) -> bool {
41 !self.longhands.is_empty()
42 }
43
44 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 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 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 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
93pub fn property(name: &str) -> Option<&'static Property> {
101 index(name).map(|i| &PROPERTIES[i])
102}
103
104pub fn properties() -> &'static [Property] {
106 PROPERTIES
107}
108
109fn index(name: &str) -> Option<usize> {
110 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
131fn 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
151fn 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#[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
193pub(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 _ => {}
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 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
262pub(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
281pub(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
287pub(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 assert!(
307 PROPERTIES
308 .iter()
309 .all(|p| p.syntax.is_none() || p.grammar().is_some())
310 );
311 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 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}