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