Skip to main content

sk_css/
vars.rs

1//! Custom properties (`--x`) and `var()` / `env()` substitution: an inherited string map on the
2//! element, read at computed-value time. Substitution is textual; it differs from token-level only
3//! in strings and comments, and the scanner skips quoted strings.
4
5use std::collections::HashMap;
6use std::rc::Rc;
7
8/// `Eq` matters: `Rc<T>` equality short-circuits on pointer identity for `T: Eq`, and a node with
9/// no custom properties shares its parent's `Rc`, keeping the change test O(1).
10#[derive(Clone, Debug, Default, PartialEq, Eq)]
11pub struct Vars {
12    /// `Rc<str>` so a child overriding one property carries the other ~40 through by refcount bump,
13    /// not allocation.
14    entries: Vec<(Rc<str>, Rc<str>)>,
15}
16
17impl Vars {
18    pub fn is_empty(&self) -> bool {
19        self.entries.is_empty()
20    }
21
22    pub fn len(&self) -> usize {
23        self.entries.len()
24    }
25
26    pub fn get(&self, name: &str) -> Option<&str> {
27        self.entries
28            .binary_search_by(|(k, _)| (**k).cmp(name))
29            .ok()
30            .map(|i| &*self.entries[i].1)
31    }
32
33    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
34        self.entries.iter().map(|(k, v)| (&**k, &**v))
35    }
36}
37
38pub(crate) fn resolve_registered(
39    parent: &Rc<Vars>,
40    own: &[&(String, String)],
41    registrations: &[crate::registered::PercentageRegistration],
42    env: &crate::Env,
43    diagnostics: &mut Vec<String>,
44) -> Rc<Vars> {
45    if registrations.is_empty() {
46        return resolve(parent, own, env, diagnostics);
47    }
48    let defaults_needed = registrations.iter().any(|r| {
49        if r.inherits {
50            parent.get(&r.name).is_none()
51        } else {
52            parent.get(&r.name).and_then(crate::registered::percentage) != Some(r.initial)
53        }
54    });
55    let owns_registered = own
56        .iter()
57        .any(|(name, _)| registrations.iter().any(|r| r.name == *name));
58    if !defaults_needed && !owns_registered {
59        return resolve(parent, own, env, diagnostics);
60    }
61    let defaults: Vec<(String, String)> = registrations
62        .iter()
63        .filter(|r| !r.inherits || parent.get(&r.name).is_none())
64        .map(|r| (r.name.clone(), format!("{}%", r.initial * 100.)))
65        .collect();
66    let basis = resolve(
67        parent,
68        &defaults.iter().collect::<Vec<_>>(),
69        env,
70        diagnostics,
71    );
72    let declarations: Vec<(String, String)> = own
73        .iter()
74        .map(|(name, raw)| {
75            let Some(registration) = registrations.iter().find(|r| r.name == *name) else {
76                return (name.clone(), raw.clone());
77            };
78            let keyword = raw.trim();
79            let value = if keyword.eq_ignore_ascii_case("inherit") {
80                parent
81                    .get(name)
82                    .map(str::to_owned)
83                    .unwrap_or_else(|| format!("{}%", registration.initial * 100.))
84            } else if keyword.eq_ignore_ascii_case("initial")
85                || (!registration.inherits
86                    && ["unset", "revert", "revert-layer"]
87                        .iter()
88                        .any(|v| keyword.eq_ignore_ascii_case(v)))
89            {
90                format!("{}%", registration.initial * 100.)
91            } else {
92                raw.clone()
93            };
94            (name.clone(), value)
95        })
96        .collect();
97    let computed = resolve(
98        &basis,
99        &declarations.iter().collect::<Vec<_>>(),
100        env,
101        diagnostics,
102    );
103    let invalid: Vec<(String, String)> = registrations
104        .iter()
105        .filter(|r| {
106            computed
107                .get(&r.name)
108                .and_then(crate::registered::percentage)
109                .is_none()
110        })
111        .map(|r| {
112            (
113                r.name.clone(),
114                basis.get(&r.name).unwrap_or("0%").to_owned(),
115            )
116        })
117        .collect();
118    resolve(
119        &computed,
120        &invalid.iter().collect::<Vec<_>>(),
121        env,
122        diagnostics,
123    )
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub(crate) enum VarError {
128    Unresolved(String),
129    /// Its own variant because an author cannot set an environment variable, so "declare it" is not
130    /// advice.
131    UnknownEnv(String),
132    Cycle(String),
133    TooLarge,
134    UnknownFunction(String),
135    InvalidCall(String, String),
136}
137
138impl VarError {
139    pub(crate) fn describe(&self) -> String {
140        match self {
141            VarError::Unresolved(name) => format!(
142                "`var({name})` is not set on this element or any ancestor and the reference has no \
143                 fallback"
144            ),
145            VarError::UnknownEnv(name) => format!(
146                "`env({name})` is not an environment variable this host publishes — supported: \
147                 titlebar-area-x | -y | -width | -height, safe-area-inset-top | -right | -bottom \
148                 | -left. Give it a fallback (`env({name}, 0px)`) if it is optional"
149            ),
150            VarError::Cycle(name) => {
151                format!("`{name}` takes part in a var() reference cycle")
152            }
153            VarError::TooLarge => {
154                format!("substitution expanded past {MAX_EXPANSION} characters")
155            }
156            VarError::UnknownFunction(name) => {
157                format!("`{name}()` is called but no @function defines it here")
158            }
159            VarError::InvalidCall(name, why) => format!("the call to `{name}()` is invalid: {why}"),
160        }
161    }
162}
163
164/// `var()` can expand exponentially (`--a: var(--b) var(--b)` chained N deep is 2^N tokens), and a
165/// browser has its own limit for the same reason — better a named advisory than a hang.
166const MAX_EXPANSION: usize = 64 * 1024;
167
168fn is_ident_byte(b: u8) -> bool {
169    b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'\\' || b >= 0x80
170}
171
172pub(crate) fn skip_string(bytes: &[u8], i: usize) -> usize {
173    let quote = bytes[i];
174    let mut j = i + 1;
175    while j < bytes.len() {
176        match bytes[j] {
177            b'\\' => j += 2,
178            b if b == quote => return j + 1,
179            _ => j += 1,
180        }
181    }
182    bytes.len()
183}
184
185#[derive(Clone, Copy, PartialEq, Eq, Debug)]
186enum Subst {
187    Var,
188    Env,
189    /// A `--name(` call; the length of `--name`.
190    Function(usize),
191}
192
193/// `--name(` not preceded by an identifier byte.
194fn dashed_call_at(bytes: &[u8], i: usize) -> Option<usize> {
195    if bytes.get(i..i + 2) != Some(b"--") || (i > 0 && is_ident_byte(bytes[i - 1])) {
196        return None;
197    }
198    let mut j = i + 2;
199    while j < bytes.len() && is_ident_byte(bytes[j]) && bytes[j] != b'\\' {
200        j += 1;
201    }
202    (j > i + 2 && bytes.get(j) == Some(&b'(')).then_some(j - i)
203}
204
205fn is_fn_at(bytes: &[u8], i: usize, name: &[u8]) -> bool {
206    let end = i + name.len();
207    if end >= bytes.len() || bytes[end] != b'(' {
208        return false;
209    }
210    if i > 0 && is_ident_byte(bytes[i - 1]) {
211        return false;
212    }
213    bytes[i..end]
214        .iter()
215        .zip(name)
216        .all(|(a, b)| a.eq_ignore_ascii_case(b))
217}
218
219fn find_subst(bytes: &[u8], from: usize) -> Option<(usize, Subst)> {
220    let mut i = from;
221    while i < bytes.len() {
222        if matches!(bytes[i], b'"' | b'\'') {
223            i = skip_string(bytes, i);
224            continue;
225        }
226        if is_fn_at(bytes, i, b"var") {
227            return Some((i, Subst::Var));
228        }
229        if is_fn_at(bytes, i, b"env") {
230            return Some((i, Subst::Env));
231        }
232        if let Some(len) = dashed_call_at(bytes, i) {
233            return Some((i, Subst::Function(len)));
234        }
235        i += 1;
236    }
237    None
238}
239
240const TITLEBAR_AREA: [&str; 4] = [
241    "titlebar-area-x",
242    "titlebar-area-y",
243    "titlebar-area-width",
244    "titlebar-area-height",
245];
246
247/// `env()` names are ASCII case-sensitive identifiers; the indexed form has no members here, so a
248/// name with an index is unknown.
249fn env_value(name: &str, env: &crate::Env) -> Option<String> {
250    let px = |v: f32| {
251        if v == v.trunc() && v.is_finite() {
252            format!("{}px", v as i64)
253        } else {
254            format!("{v}px")
255        }
256    };
257    let s = env.safe_area_insets;
258    if let Some(i) = TITLEBAR_AREA.iter().position(|n| *n == name) {
259        return env.titlebar_area.map(|t| px(t[i]));
260    }
261    Some(match name {
262        "safe-area-inset-top" => px(s[0]),
263        "safe-area-inset-right" => px(s[1]),
264        "safe-area-inset-bottom" => px(s[2]),
265        "safe-area-inset-left" => px(s[3]),
266        _ => return None,
267    })
268}
269
270/// `None` = unbalanced (the parser would have rejected the sheet, but an inline `style=""` string
271/// reaches us raw).
272fn matching_paren(bytes: &[u8], open: usize) -> Option<usize> {
273    let mut depth = 0usize;
274    let mut i = open;
275    while i < bytes.len() {
276        match bytes[i] {
277            b'"' | b'\'' => {
278                i = skip_string(bytes, i);
279                continue;
280            }
281            b'(' => depth += 1,
282            b')' => {
283                depth -= 1;
284                if depth == 0 {
285                    return Some(i);
286                }
287            }
288            _ => {}
289        }
290        i += 1;
291    }
292    None
293}
294
295/// A missing comma means "no fallback"; `var(--x,)` means "the empty fallback", which is valid CSS
296/// and NOT the same as no fallback.
297fn split_var_args(inner: &str) -> (&str, Option<&str>) {
298    let bytes = inner.as_bytes();
299    let mut depth = 0usize;
300    let mut i = 0;
301    while i < bytes.len() {
302        match bytes[i] {
303            b'"' | b'\'' => {
304                i = skip_string(bytes, i);
305                continue;
306            }
307            b'(' => depth += 1,
308            b')' => depth = depth.saturating_sub(1),
309            b',' if depth == 0 => return (inner[..i].trim(), Some(inner[i + 1..].trim_start())),
310            _ => {}
311        }
312        i += 1;
313    }
314    (inner.trim(), None)
315}
316
317pub(crate) fn substitute(
318    text: &str,
319    env: &crate::Env,
320    lookup: &mut dyn FnMut(&str) -> Result<Option<String>, VarError>,
321) -> Result<String, VarError> {
322    if find_subst(text.as_bytes(), 0).is_none() {
323        return Ok(text.to_string());
324    }
325    let mut out = String::with_capacity(text.len());
326    let mut cursor = 0usize;
327    let bytes = text.as_bytes();
328    while let Some((open, kind)) = find_subst(bytes, cursor) {
329        let paren = match kind {
330            Subst::Function(len) => open + len,
331            Subst::Var | Subst::Env => open + 3,
332        };
333        let Some(close) = matching_paren(bytes, paren) else {
334            break;
335        };
336        out.push_str(&text[cursor..open]);
337        if let Subst::Function(_) = kind {
338            out.push_str(&crate::functions::call(
339                &text[open..paren],
340                &text[paren + 1..close],
341                env,
342                lookup,
343            )?);
344            if out.len() > MAX_EXPANSION {
345                return Err(VarError::TooLarge);
346            }
347            cursor = close + 1;
348            continue;
349        }
350        let (name, fallback) = split_var_args(&text[paren + 1..close]);
351        let resolved = match kind {
352            Subst::Var => lookup(name)?,
353            Subst::Env => env_value(name, env),
354            Subst::Function(_) => unreachable!("handled above"),
355        };
356        match resolved {
357            Some(value) => out.push_str(&value),
358            None => match fallback {
359                Some(f) => out.push_str(&substitute(f, env, lookup)?),
360                None => {
361                    return Err(match kind {
362                        Subst::Env if !TITLEBAR_AREA.contains(&name) => {
363                            VarError::UnknownEnv(name.to_string())
364                        }
365                        // A known variable the window does not define now: as routine as an unset var().
366                        Subst::Var | Subst::Env | Subst::Function(_) => {
367                            VarError::Unresolved(name.to_string())
368                        }
369                    });
370                }
371            },
372        }
373        if out.len() > MAX_EXPANSION {
374            return Err(VarError::TooLarge);
375        }
376        cursor = close + 1;
377    }
378    out.push_str(&text[cursor..]);
379    Ok(out)
380}
381
382pub(crate) fn substitute_with(
383    text: &str,
384    vars: &Vars,
385    env: &crate::Env,
386) -> Result<String, VarError> {
387    substitute(text, env, &mut |name| {
388        Ok(vars.get(name).map(str::to_string))
389    })
390}
391
392enum Slot<'a> {
393    Raw(&'a str),
394    Done(String),
395    Busy,
396    Dropped,
397}
398
399fn force<'a>(
400    slots: &mut HashMap<&'a str, Slot<'a>>,
401    parent: &Vars,
402    env: &crate::Env,
403    name: &str,
404    diagnostics: &mut Vec<String>,
405) -> Result<Option<String>, VarError> {
406    match slots.get(name) {
407        None => Ok(parent.get(name).map(str::to_string)),
408        Some(Slot::Dropped) => Ok(None),
409        Some(Slot::Done(v)) => Ok(Some(v.clone())),
410        Some(Slot::Busy) => Err(VarError::Cycle(name.to_string())),
411        Some(Slot::Raw(_)) => {
412            let (key, raw) = match slots.get_key_value(name) {
413                Some((k, Slot::Raw(raw))) => (*k, *raw),
414                _ => unreachable!("checked Raw above"),
415            };
416            slots.insert(key, Slot::Busy);
417            let resolved = substitute(raw, env, &mut |inner| {
418                force(slots, parent, env, inner, diagnostics)
419            });
420            match resolved {
421                Ok(value) => {
422                    slots.insert(key, Slot::Done(value.clone()));
423                    Ok(Some(value))
424                }
425                // Routine, so silent: Tailwind's `--tw-shadow-colored` reads
426                // `var(--tw-shadow-color)`, set only by a `shadow-<color>` utility. Cycles and
427                // unknown `env()` are author mistakes and still speak.
428                Err(VarError::Unresolved(_)) => {
429                    slots.insert(key, Slot::Dropped);
430                    Ok(None)
431                }
432                Err(e) => {
433                    diagnostics.push(format!(
434                        "`{name}` is invalid at computed-value time — {} (the custom property is \
435                         treated as unset on this element and everything under it)",
436                        e.describe()
437                    ));
438                    slots.insert(key, Slot::Dropped);
439                    Ok(None)
440                }
441            }
442        }
443    }
444}
445
446/// Fast path: Tailwind's universal block declares ~40 literals on every element, almost all equal
447/// to what was inherited, so the parent's `Rc` comes straight back; the general path resolves only
448/// the names declared here and merges sorted lists.
449fn inert(raw: &str, name: &str, parent: &Vars) -> bool {
450    find_subst(raw.as_bytes(), 0).is_none() && parent.get(name) == Some(raw)
451}
452
453/// CSS-wide keywords as a variable's value. `initial` must reset the channel, not substitute
454/// literally: `tailwindcss-animate` writes `--tw-enter-scale: initial`, and `translate3d(initial,
455/// ...)` would not parse and would discard the whole `transform`.
456enum Wide {
457    Initial,
458    Inherited,
459}
460
461fn wide_keyword(raw: &str) -> Option<Wide> {
462    let raw = raw.trim();
463    if raw.eq_ignore_ascii_case("initial") {
464        return Some(Wide::Initial);
465    }
466    if ["inherit", "unset", "revert", "revert-layer"]
467        .iter()
468        .any(|k| raw.eq_ignore_ascii_case(k))
469    {
470        return Some(Wide::Inherited);
471    }
472    None
473}
474
475pub(crate) fn is_wide_initial(raw: &str) -> bool {
476    matches!(wide_keyword(raw), Some(Wide::Initial))
477}
478
479pub(crate) fn resolve(
480    parent: &Rc<Vars>,
481    own: &[&(String, String)],
482    env: &crate::Env,
483    diagnostics: &mut Vec<String>,
484) -> Rc<Vars> {
485    if own.is_empty() {
486        return parent.clone();
487    }
488    if own.iter().all(|(name, raw)| inert(raw, name, parent)) {
489        return parent.clone();
490    }
491
492    let mut folded: Vec<(&str, &str)> = Vec::with_capacity(own.len());
493    let mut seen: std::collections::HashSet<&str> =
494        std::collections::HashSet::with_capacity(own.len());
495    for (name, raw) in own.iter().rev() {
496        if !seen.insert(name.as_str()) {
497            continue;
498        }
499        match wide_keyword(raw) {
500            Some(Wide::Inherited) => continue,
501            Some(Wide::Initial) => folded.push((name.as_str(), raw.as_str())),
502            None => {
503                if !inert(raw, name, parent) {
504                    folded.push((name.as_str(), raw.as_str()));
505                }
506            }
507        }
508    }
509    if folded.is_empty() {
510        return parent.clone();
511    }
512
513    let mut slots: HashMap<&str, Slot<'_>> = HashMap::with_capacity(folded.len());
514    for (name, raw) in &folded {
515        slots.insert(
516            name,
517            match wide_keyword(raw) {
518                Some(Wide::Initial) => Slot::Dropped,
519                _ => Slot::Raw(raw),
520            },
521        );
522    }
523    for (name, _) in &folded {
524        if let Err(e) = force(&mut slots, parent, env, name, diagnostics) {
525            diagnostics.push(format!(
526                "`{name}` is invalid at computed-value time — {}",
527                e.describe()
528            ));
529            slots.insert(name, Slot::Dropped);
530        }
531    }
532
533    let mut mine: Vec<(&str, String)> = slots
534        .into_iter()
535        .filter_map(|(k, v)| match v {
536            Slot::Done(value) => Some((k, value)),
537            _ => None,
538        })
539        .collect();
540    mine.sort_by(|a, b| a.0.cmp(b.0));
541    let declared: std::collections::HashSet<&str> = folded.iter().map(|(n, _)| *n).collect();
542
543    let mut entries: Vec<(Rc<str>, Rc<str>)> =
544        Vec::with_capacity(parent.entries.len() + mine.len());
545    let mut mine_iter = mine.into_iter().peekable();
546    for (k, v) in &parent.entries {
547        while mine_iter.peek().is_some_and(|(mk, _)| *mk < &**k) {
548            let (mk, mv) = mine_iter.next().unwrap();
549            entries.push((mk.into(), mv.into()));
550        }
551        if declared.contains(&**k) {
552            if mine_iter.peek().is_some_and(|(mk, _)| *mk == &**k) {
553                let (mk, mv) = mine_iter.next().unwrap();
554                entries.push((mk.into(), mv.into()));
555            }
556            continue;
557        }
558        entries.push((k.clone(), v.clone()));
559    }
560    for (mk, mv) in mine_iter {
561        entries.push((mk.into(), mv.into()));
562    }
563
564    if entries == parent.entries {
565        return parent.clone();
566    }
567    Rc::new(Vars { entries })
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    fn vars(pairs: &[(&str, &str)]) -> Rc<Vars> {
575        let own: Vec<(String, String)> = pairs
576            .iter()
577            .map(|(k, v)| (k.to_string(), v.to_string()))
578            .collect();
579        let mut d = Vec::new();
580        resolve(
581            &Rc::new(Vars::default()),
582            &refs(&own),
583            &crate::Env::default(),
584            &mut d,
585        )
586    }
587
588    fn refs(own: &[(String, String)]) -> Vec<&(String, String)> {
589        own.iter().collect()
590    }
591
592    #[test]
593    fn the_css_wide_keywords_are_keywords_for_a_custom_property_too() {
594        let v = vars(&[("--tw-enter-scale", "initial")]);
595        assert_eq!(v.get("--tw-enter-scale"), None, "`initial` is not a value");
596        assert_eq!(
597            substitute_with(
598                "scale3d(var(--tw-enter-scale, 1), 1, 1)",
599                &v,
600                &crate::Env::default()
601            )
602            .unwrap(),
603            "scale3d(1, 1, 1)",
604            "so `var()` takes the fallback"
605        );
606
607        let parent = vars(&[("--x", "9")]);
608        let own = vec![("--x".to_string(), "initial".to_string())];
609        let mut d = Vec::new();
610        let child = resolve(&parent, &refs(&own), &crate::Env::default(), &mut d);
611        assert_eq!(
612            child.get("--x"),
613            None,
614            "CSS Variables §3: no inheritance rescue"
615        );
616        assert!(d.is_empty(), "and it is not an error: {d:?}");
617
618        for keyword in ["inherit", "unset", "revert", "REVERT-LAYER"] {
619            let own = vec![("--x".to_string(), keyword.to_string())];
620            let child = resolve(
621                &parent,
622                &refs(&own),
623                &crate::Env::default(),
624                &mut Vec::new(),
625            );
626            assert_eq!(child.get("--x"), Some("9"), "{keyword}");
627        }
628    }
629
630    #[test]
631    fn a_custom_property_may_reference_another() {
632        let v = vars(&[("--a", "10px"), ("--b", "var(--a) var(--a)")]);
633        assert_eq!(v.get("--b"), Some("10px 10px"));
634    }
635
636    #[test]
637    fn declaration_order_does_not_matter_for_resolution() {
638        let v = vars(&[("--b", "var(--a)"), ("--a", "red")]);
639        assert_eq!(v.get("--b"), Some("red"));
640    }
641
642    #[test]
643    fn fallbacks_apply_only_when_unset() {
644        let v = vars(&[
645            ("--a", "1"),
646            ("--x", "var(--a, 9)"),
647            ("--y", "var(--nope, 9)"),
648        ]);
649        assert_eq!(v.get("--x"), Some("1"));
650        assert_eq!(v.get("--y"), Some("9"));
651    }
652
653    #[test]
654    fn a_fallbackless_missing_reference_invalidates_the_declaration() {
655        let own = vec![("--x".to_string(), "var(--nope)".to_string())];
656        let mut d = Vec::new();
657        let v = resolve(
658            &Rc::new(Vars::default()),
659            &refs(&own),
660            &crate::Env::default(),
661            &mut d,
662        );
663        assert_eq!(v.get("--x"), None);
664        assert!(d.is_empty(), "{d:?}");
665    }
666
667    #[test]
668    fn cycles_drop_the_properties() {
669        let own = vec![
670            ("--a".to_string(), "var(--b)".to_string()),
671            ("--b".to_string(), "var(--a)".to_string()),
672        ];
673        let mut d = Vec::new();
674        let v = resolve(
675            &Rc::new(Vars::default()),
676            &refs(&own),
677            &crate::Env::default(),
678            &mut d,
679        );
680        assert!(v.get("--a").is_none() && v.get("--b").is_none(), "{v:?}");
681    }
682
683    #[test]
684    fn inheritance_overrides_by_name_and_shares_the_rc_when_nothing_is_declared() {
685        let parent = vars(&[("--a", "1"), ("--b", "2")]);
686        let mut d = Vec::new();
687        let same = resolve(&parent, &[], &crate::Env::default(), &mut d);
688        assert!(Rc::ptr_eq(&parent, &same));
689
690        let own = vec![("--b".to_string(), "9".to_string())];
691        let child = resolve(&parent, &refs(&own), &crate::Env::default(), &mut d);
692        assert_eq!(child.get("--a"), Some("1"));
693        assert_eq!(child.get("--b"), Some("9"));
694        assert_eq!(parent.get("--b"), Some("2"));
695    }
696
697    #[test]
698    fn redeclaring_the_inherited_value_shares_the_parents_map() {
699        let parent = vars(&[("--a", "1"), ("--b", "0 0 #0000")]);
700        let mut d = Vec::new();
701        let same = vec![
702            ("--a".to_string(), "1".to_string()),
703            ("--b".to_string(), "0 0 #0000".to_string()),
704        ];
705        let child = resolve(&parent, &refs(&same), &crate::Env::default(), &mut d);
706        assert!(
707            Rc::ptr_eq(&parent, &child),
708            "identical declarations must not rebuild the map"
709        );
710
711        let differs = vec![
712            ("--a".to_string(), "1".to_string()),
713            ("--b".to_string(), "2".to_string()),
714        ];
715        let child = resolve(&parent, &refs(&differs), &crate::Env::default(), &mut d);
716        assert!(!Rc::ptr_eq(&parent, &child));
717        assert_eq!(child.get("--a"), Some("1"));
718        assert_eq!(child.get("--b"), Some("2"));
719    }
720
721    #[test]
722    fn dropping_inert_declarations_respects_last_wins() {
723        let parent = vars(&[("--a", "1")]);
724        let mut d = Vec::new();
725
726        let later_differs = vec![
727            ("--a".to_string(), "1".to_string()),
728            ("--a".to_string(), "2".to_string()),
729        ];
730        assert_eq!(
731            resolve(
732                &parent,
733                &refs(&later_differs),
734                &crate::Env::default(),
735                &mut d
736            )
737            .get("--a"),
738            Some("2")
739        );
740
741        let later_matches = vec![
742            ("--a".to_string(), "2".to_string()),
743            ("--a".to_string(), "1".to_string()),
744        ];
745        let child = resolve(
746            &parent,
747            &refs(&later_matches),
748            &crate::Env::default(),
749            &mut d,
750        );
751        assert_eq!(child.get("--a"), Some("1"));
752        assert!(
753            Rc::ptr_eq(&parent, &child),
754            "the winning declaration is inert"
755        );
756    }
757
758    #[test]
759    fn a_var_reference_never_takes_the_identical_fast_path() {
760        let parent = vars(&[("--b", "red"), ("--a", "var(--b)")]);
761        let mut d = Vec::new();
762        let own = vec![("--a".to_string(), "var(--b)".to_string())];
763        let child = resolve(&parent, &refs(&own), &crate::Env::default(), &mut d);
764        assert_eq!(child.get("--a"), Some("red"));
765    }
766
767    #[test]
768    fn an_invalid_declaration_shadows_the_inherited_value() {
769        let parent = vars(&[("--keep", "k"), ("--x", "inherited")]);
770        let mut d = Vec::new();
771        let own = vec![("--x".to_string(), "var(--nope)".to_string())];
772        let child = resolve(&parent, &refs(&own), &crate::Env::default(), &mut d);
773        assert_eq!(
774            child.get("--x"),
775            None,
776            "the parent's value must not come back"
777        );
778        assert_eq!(child.get("--keep"), Some("k"));
779    }
780
781    #[test]
782    fn the_merged_map_stays_sorted() {
783        let parent = vars(&[("--m", "m"), ("--z", "z")]);
784        let mut d = Vec::new();
785        let own = vec![
786            ("--zz".to_string(), "9".to_string()),
787            ("--a".to_string(), "1".to_string()),
788            ("--m".to_string(), "2".to_string()),
789        ];
790        let child = resolve(&parent, &refs(&own), &crate::Env::default(), &mut d);
791        let names: Vec<&str> = child.iter().map(|(k, _)| k).collect();
792        assert_eq!(names, vec!["--a", "--m", "--z", "--zz"]);
793        assert_eq!(child.get("--a"), Some("1"));
794        assert_eq!(child.get("--m"), Some("2"));
795        assert_eq!(child.get("--z"), Some("z"));
796        assert_eq!(child.get("--zz"), Some("9"));
797    }
798
799    #[test]
800    fn an_override_is_seen_by_the_elements_own_references() {
801        let parent = vars(&[("--hue", "10")]);
802        let mut d = Vec::new();
803        let own = vec![
804            ("--hue".to_string(), "200".to_string()),
805            ("--color".to_string(), "hsl(var(--hue) 50% 50%)".to_string()),
806        ];
807        let child = resolve(&parent, &refs(&own), &crate::Env::default(), &mut d);
808        assert_eq!(child.get("--color"), Some("hsl(200 50% 50%)"));
809    }
810
811    #[test]
812    fn substitution_skips_strings_and_identifier_tails() {
813        let v = vars(&[("--a", "X")]);
814        assert_eq!(
815            substitute_with(r#"content: "var(--a)""#, &v, &crate::Env::default()).unwrap(),
816            r#"content: "var(--a)""#
817        );
818        assert_eq!(
819            substitute_with("my-var(--a)", &v, &crate::Env::default()).unwrap(),
820            "my-var(--a)"
821        );
822        assert_eq!(
823            substitute_with("VAR(--a)", &v, &crate::Env::default()).unwrap(),
824            "X"
825        );
826    }
827
828    #[test]
829    fn nested_fallbacks_resolve() {
830        let v = vars(&[("--b", "blue")]);
831        assert_eq!(
832            substitute_with("var(--a, var(--b, red))", &v, &crate::Env::default()).unwrap(),
833            "blue"
834        );
835        assert_eq!(
836            substitute_with("var(--a, var(--z, red))", &v, &crate::Env::default()).unwrap(),
837            "red"
838        );
839    }
840
841    #[test]
842    fn the_fallback_split_is_top_level_only() {
843        let v = vars(&[]);
844        assert_eq!(
845            substitute_with("var(--a, rgb(1, 2, 3))", &v, &crate::Env::default()).unwrap(),
846            "rgb(1, 2, 3)"
847        );
848    }
849
850    #[test]
851    fn an_empty_fallback_is_not_the_same_as_no_fallback() {
852        let v = vars(&[]);
853        assert_eq!(
854            substitute_with("var(--a,)", &v, &crate::Env::default()).unwrap(),
855            ""
856        );
857        assert!(matches!(
858            substitute_with("var(--a)", &v, &crate::Env::default()),
859            Err(VarError::Unresolved(_))
860        ));
861    }
862
863    #[test]
864    fn the_tailwind_ring_compound_substitutes() {
865        let v = vars(&[
866            ("--tw-ring-inset", ""),
867            ("--tw-ring-offset-width", "2px"),
868            ("--tw-ring-offset-color", "#fff"),
869            ("--tw-ring-color", "rgb(59 130 246 / 0.5)"),
870            (
871                "--tw-ring-offset-shadow",
872                "var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)",
873            ),
874            (
875                "--tw-ring-shadow",
876                "var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color)",
877            ),
878        ]);
879        let shadow = substitute_with(
880            "var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000)",
881            &v,
882            &crate::Env::default(),
883        )
884        .unwrap();
885        assert_eq!(
886            shadow,
887            " 0 0 0 2px #fff,  0 0 0 calc(2px + 2px) rgb(59 130 246 / 0.5), 0 0 #0000"
888        );
889    }
890}