Skip to main content

parsec_css/values/
custom.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Custom properties and `var()`, CSS Custom Properties Level 1 and CSS
5//! Values 5's substitution: an element's custom properties resolved
6//! against each other, cycles found and made the guaranteed-invalid
7//! value, and `var()` in any value replaced from them.
8//!
9//! Inheriting from a parent is what the cascade does (#30); here you hand
10//! in the parent's resolved properties if there is one.
11
12use std::collections::HashMap;
13
14use super::value::{InvalidValue, Specified, parse_value};
15use crate::parser::{ComponentValue, Function, SimpleBlock};
16use crate::tokenizer::Token;
17
18/// How many component values a substituted value may grow to. Substitution
19/// can grow a value exponentially (`--b: var(--a) var(--a)`, and so on);
20/// past this the value is invalid, as the spec lets a browser decide.
21const MAX_VALUES: usize = 100_000;
22/// How deep `var()` fallbacks and functions may nest while substituting.
23const MAX_DEPTH: usize = 128;
24
25/// An element's custom properties, as declared.
26///
27/// ```
28/// use parsec_css::values::CustomProperties;
29///
30/// let mut props = CustomProperties::new();
31/// props.declare("--gap", parsec_css::parse_component_values("4px"));
32/// props.declare("--pad", parsec_css::parse_component_values("calc(var(--gap) * 2)"));
33/// props.declare("--a", parsec_css::parse_component_values("var(--b)"));
34/// props.declare("--b", parsec_css::parse_component_values("var(--a)"));
35/// let resolved = props.resolve(None);
36/// assert_eq!(resolved.get_css("--pad").as_deref(), Some("calc(4px * 2)"));
37/// assert_eq!(resolved.get_css("--a"), None); // a cycle: guaranteed-invalid
38/// ```
39#[derive(Clone, Debug, Default)]
40pub struct CustomProperties<'a> {
41    declared: Vec<(String, Vec<ComponentValue<'a>>)>,
42    index: HashMap<String, usize>,
43}
44
45/// Custom properties with every `var()` in them substituted. A name that
46/// maps to `None` holds the guaranteed-invalid value.
47#[derive(Clone, Debug, Default)]
48pub struct Resolved<'a> {
49    values: HashMap<String, Option<Vec<ComponentValue<'a>>>>,
50}
51
52impl<'a> CustomProperties<'a> {
53    pub fn new() -> CustomProperties<'a> {
54        CustomProperties::default()
55    }
56
57    /// Declares `name` (with its `--`), replacing an earlier declaration.
58    pub fn declare(&mut self, name: &str, value: Vec<ComponentValue<'a>>) {
59        let value = trim(value);
60        match self.index.get(name) {
61            Some(&i) => self.declared[i].1 = value,
62            None => {
63                self.index.insert(name.to_string(), self.declared.len());
64                self.declared.push((name.to_string(), value));
65            }
66        }
67    }
68
69    /// Resolves every declared property: `var()` substituted, cycles made
70    /// guaranteed-invalid. What isn't declared here comes from `parent`.
71    pub fn resolve(&self, parent: Option<&Resolved<'a>>) -> Resolved<'a> {
72        let n = self.declared.len();
73        let index = &self.index;
74        // Who each property refers to, fallbacks included.
75        let edges: Vec<Vec<usize>> = self
76            .declared
77            .iter()
78            .map(|(_, v)| {
79                let mut out = Vec::new();
80                references(v, &mut |name| {
81                    if let Some(&j) = index.get(name) {
82                        out.push(j);
83                    }
84                });
85                out
86            })
87            .collect();
88        let mut resolved = Resolved {
89            values: parent.map(|p| p.values.clone()).unwrap_or_default(),
90        };
91        // Tarjan's strongly connected components, without recursion: each
92        // component completes after those it refers to, so its references
93        // are resolved by the time it's substituted.
94        let mut order = vec![usize::MAX; n];
95        let mut low = vec![0; n];
96        let mut on_stack = vec![false; n];
97        let mut stack = Vec::new();
98        let mut counter = 0;
99        for root in 0..n {
100            if order[root] != usize::MAX {
101                continue;
102            }
103            let mut work = vec![(root, 0usize)];
104            while let Some(&mut (v, ref mut next)) = work.last_mut() {
105                if *next == 0 {
106                    order[v] = counter;
107                    low[v] = counter;
108                    counter += 1;
109                    stack.push(v);
110                    on_stack[v] = true;
111                }
112                if let Some(&w) = edges[v].get(*next) {
113                    *next += 1;
114                    if order[w] == usize::MAX {
115                        work.push((w, 0));
116                    } else if on_stack[w] {
117                        low[v] = low[v].min(order[w]);
118                    }
119                    continue;
120                }
121                work.pop();
122                if let Some(&(parent, _)) = work.last() {
123                    low[parent] = low[parent].min(low[v]);
124                }
125                if low[v] != order[v] {
126                    continue;
127                }
128                let mut component = Vec::new();
129                loop {
130                    let w = stack.pop().unwrap();
131                    on_stack[w] = false;
132                    component.push(w);
133                    if w == v {
134                        break;
135                    }
136                }
137                let cyclic = component.len() > 1 || edges[v].contains(&v);
138                for w in component {
139                    let (name, value) = &self.declared[w];
140                    let result = if cyclic {
141                        None
142                    } else {
143                        custom_value(value, &resolved)
144                    };
145                    resolved.values.insert(name.clone(), result);
146                }
147            }
148        }
149        resolved
150    }
151}
152
153/// A custom property's own value, substituted: `initial` is the
154/// guaranteed-invalid value, `inherit` and `unset` the parent's (already
155/// in `resolved`, since custom properties inherit).
156fn custom_value<'a>(
157    value: &[ComponentValue<'a>],
158    resolved: &Resolved<'a>,
159) -> Option<Vec<ComponentValue<'a>>> {
160    if let [ComponentValue::Token(Token::Ident(w), _)] = value {
161        if w.eq_ignore_ascii_case("initial") {
162            return None;
163        }
164        if ["inherit", "unset", "revert", "revert-layer"]
165            .iter()
166            .any(|k| w.eq_ignore_ascii_case(k))
167        {
168            return None;
169        }
170    }
171    substitute(value, resolved).ok()
172}
173
174impl<'a> Resolved<'a> {
175    /// Resolved properties from values worked out already, as a parent's
176    /// are by the time its children are styled. `None` is the
177    /// guaranteed-invalid value.
178    pub fn from_values(
179        values: impl IntoIterator<Item = (String, Option<Vec<ComponentValue<'a>>>)>,
180    ) -> Resolved<'a> {
181        Resolved {
182            values: values.into_iter().collect(),
183        }
184    }
185
186    /// Every property here and its value.
187    pub fn iter(&self) -> impl Iterator<Item = (&str, Option<&[ComponentValue<'a>]>)> {
188        self.values.iter().map(|(k, v)| (k.as_str(), v.as_deref()))
189    }
190
191    /// A resolved custom property's value; `None` if it's guaranteed-invalid
192    /// or not there at all.
193    pub fn get(&self, name: &str) -> Option<&[ComponentValue<'a>]> {
194        self.values.get(name)?.as_deref()
195    }
196
197    /// [`Resolved::get`], written as CSS.
198    pub fn get_css(&self, name: &str) -> Option<String> {
199        self.get(name).map(crate::to_css)
200    }
201}
202
203/// The guaranteed-invalid value turned up where a value was needed: a
204/// `var()` with nothing to stand for and no fallback.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct GuaranteedInvalid;
207
208impl std::fmt::Display for GuaranteedInvalid {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        f.write_str("a var() refers to the guaranteed-invalid value")
211    }
212}
213
214impl std::error::Error for GuaranteedInvalid {}
215
216/// Replaces every `var()` in `value` from `custom`.
217pub fn substitute<'a>(
218    value: &[ComponentValue<'a>],
219    custom: &Resolved<'a>,
220) -> Result<Vec<ComponentValue<'a>>, GuaranteedInvalid> {
221    let mut out = Vec::new();
222    let mut count = 0;
223    substitute_into(value, custom, &mut out, &mut count, 0)?;
224    Ok(out)
225}
226
227/// Substitutes `var()` in a property's value and parses what results, as
228/// computing a value with `var()` in it does. An error is "invalid at
229/// computed-value time", which the cascade turns into `unset`.
230pub fn substitute_value<'a>(
231    property: &str,
232    value: &[ComponentValue<'a>],
233    custom: &Resolved<'a>,
234) -> Result<Specified<'a>, InvalidValue> {
235    let values = substitute(value, custom).map_err(|_| InvalidValue)?;
236    // Substituted tokens stay the tokens they were: `var(--n)px` with `--n:
237    // 1` is a number and an ident, never a dimension, so no re-reading.
238    // `env()` isn't substituted: no environment is given here.
239    if super::value::has_substitution(&values) {
240        return Err(InvalidValue);
241    }
242    parse_value(property, &values)
243}
244
245fn substitute_into<'a>(
246    value: &[ComponentValue<'a>],
247    custom: &Resolved<'a>,
248    out: &mut Vec<ComponentValue<'a>>,
249    count: &mut usize,
250    depth: usize,
251) -> Result<(), GuaranteedInvalid> {
252    if depth > MAX_DEPTH {
253        return Err(GuaranteedInvalid);
254    }
255    for v in value {
256        *count += 1;
257        if *count > MAX_VALUES {
258            return Err(GuaranteedInvalid);
259        }
260        match v {
261            ComponentValue::Function(f) if f.name.eq_ignore_ascii_case("var") => {
262                let (name, fallback) = var_parts(f).ok_or(GuaranteedInvalid)?;
263                match custom.get(name) {
264                    Some(found) => {
265                        *count += found.len();
266                        if *count > MAX_VALUES {
267                            return Err(GuaranteedInvalid);
268                        }
269                        out.extend(found.iter().cloned());
270                    }
271                    None => {
272                        let fallback = fallback.ok_or(GuaranteedInvalid)?;
273                        substitute_into(trim_slice(fallback), custom, out, count, depth + 1)?;
274                    }
275                }
276            }
277            ComponentValue::Function(f) => {
278                let mut arguments = Vec::new();
279                substitute_into(&f.arguments, custom, &mut arguments, count, depth + 1)?;
280                out.push(ComponentValue::Function(Function {
281                    name: f.name.clone(),
282                    arguments,
283                    span: f.span,
284                }));
285            }
286            ComponentValue::Block(b) => {
287                let mut contents = Vec::new();
288                substitute_into(&b.contents, custom, &mut contents, count, depth + 1)?;
289                out.push(ComponentValue::Block(SimpleBlock {
290                    bracket: b.bracket,
291                    contents,
292                    span: b.span,
293                }));
294            }
295            v => out.push(v.clone()),
296        }
297    }
298    Ok(())
299}
300
301/// `var(--name)` or `var(--name, fallback)`: the name, and the fallback if
302/// there's a comma. `None` if it isn't a well-formed `var()`.
303fn var_parts<'v, 'a>(f: &'v Function<'a>) -> Option<(&'v str, Option<&'v [ComponentValue<'a>]>)> {
304    let args = &f.arguments;
305    let start = args.iter().position(|v| !v.is_whitespace())?;
306    let ComponentValue::Token(Token::Ident(name), _) = &args[start] else {
307        return None;
308    };
309    if !name.starts_with("--") {
310        return None;
311    }
312    let rest = &args[start + 1..];
313    let comma = rest
314        .iter()
315        .position(|v| matches!(v, ComponentValue::Token(Token::Comma, _)));
316    match comma {
317        Some(i) if rest[..i].iter().all(ComponentValue::is_whitespace) => {
318            Some((name, Some(&rest[i + 1..])))
319        }
320        None if rest.iter().all(ComponentValue::is_whitespace) => Some((name, None)),
321        _ => None,
322    }
323}
324
325/// Every custom property name a `var()` in `value` refers to.
326fn references<'v>(value: &'v [ComponentValue<'_>], found: &mut impl FnMut(&'v str)) {
327    let mut stack = vec![value];
328    while let Some(list) = stack.pop() {
329        for v in list {
330            match v {
331                ComponentValue::Function(f) => {
332                    if f.name.eq_ignore_ascii_case("var")
333                        && let Some((name, _)) = var_parts(f)
334                    {
335                        found(name);
336                    }
337                    stack.push(&f.arguments);
338                }
339                ComponentValue::Block(b) => stack.push(&b.contents),
340                ComponentValue::Token(..) => {}
341            }
342        }
343    }
344}
345
346fn trim(mut v: Vec<ComponentValue<'_>>) -> Vec<ComponentValue<'_>> {
347    while v.last().is_some_and(ComponentValue::is_whitespace) {
348        v.pop();
349    }
350    let lead = v.iter().take_while(|c| c.is_whitespace()).count();
351    v.drain(..lead);
352    v
353}
354
355fn trim_slice<'v, 'a>(v: &'v [ComponentValue<'a>]) -> &'v [ComponentValue<'a>] {
356    let start = v.iter().position(|c| !c.is_whitespace()).unwrap_or(v.len());
357    let end = v
358        .iter()
359        .rposition(|c| !c.is_whitespace())
360        .map_or(start, |i| i + 1);
361    &v[start..end]
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    fn props(decls: &[(&'static str, &'static str)]) -> Resolved<'static> {
369        let mut p = CustomProperties::new();
370        for (n, v) in decls {
371            p.declare(n, crate::parse_component_values(v));
372        }
373        p.resolve(None)
374    }
375
376    #[test]
377    fn fallbacks_chains_and_cycles() {
378        let r = props(&[
379            ("--a", "1px"),
380            ("--b", "var(--a) var(--missing, 2px)"),
381            ("--c", "var(--missing)"),
382            ("--d", "var(--c, var(--a))"),
383            ("--x", "var(--y)"),
384            ("--y", "var(--z, 1)"),
385            ("--z", "var(--x)"),
386            ("--w", "var(--x, ok)"),
387            ("--self", "var(--self)"),
388            ("--i", "initial"),
389        ]);
390        assert_eq!(r.get_css("--b").as_deref(), Some("1px 2px"));
391        assert_eq!(r.get_css("--c"), None);
392        assert_eq!(r.get_css("--d").as_deref(), Some("1px"));
393        // A cycle through a fallback is still a cycle.
394        for n in ["--x", "--y", "--z", "--self", "--i"] {
395            assert_eq!(r.get_css(n), None, "{n}");
396        }
397        // Referring to a cycle isn't being in one.
398        assert_eq!(r.get_css("--w").as_deref(), Some("ok"));
399    }
400
401    #[test]
402    fn exponential_growth_is_cut_off() {
403        let mut decls = vec![("--l0".to_string(), "x x x x x x x x x x".to_string())];
404        for i in 1..12 {
405            let prev = format!("var(--l{})", i - 1);
406            decls.push((format!("--l{i}"), [prev.as_str(); 10].join(" ")));
407        }
408        let texts: Vec<(&'static str, &'static str)> = decls
409            .into_iter()
410            .map(|(n, v)| {
411                (
412                    &*Box::leak(n.into_boxed_str()),
413                    &*Box::leak(v.into_boxed_str()),
414                )
415            })
416            .collect();
417        let r = props(&texts);
418        assert!(r.get("--l3").is_some());
419        assert_eq!(r.get("--l11"), None);
420    }
421
422    #[test]
423    fn long_chains_resolve_without_recursion() {
424        let names: Vec<String> = (0..50_000).map(|i| format!("--v{i}")).collect();
425        let texts: Vec<String> = (0..50_000)
426            .map(|i| {
427                if i == 0 {
428                    "7".into()
429                } else {
430                    format!("var(--v{})", i - 1)
431                }
432            })
433            .collect();
434        let mut p = CustomProperties::new();
435        for (n, t) in names.iter().zip(&texts) {
436            p.declare(n, crate::parse_component_values(t));
437        }
438        let r = p.resolve(None);
439        assert_eq!(r.get_css("--v49999").as_deref(), Some("7"));
440    }
441
442    #[test]
443    fn parent_values_and_property_values() {
444        let parent = props(&[("--color", "red")]);
445        let mut child = CustomProperties::new();
446        child.declare(
447            "--border",
448            crate::parse_component_values("1px solid var(--color)"),
449        );
450        let r = child.resolve(Some(&parent));
451        let value = crate::parse_component_values("var(--border)");
452        let v = substitute_value("border-top", &value, &r).unwrap();
453        assert_eq!(v.to_string(), "1px solid red");
454        let bad = crate::parse_component_values("var(--nope)");
455        assert!(substitute_value("color", &bad, &r).is_err());
456    }
457}