Skip to main content

parsec_css/values/
value.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! A declaration's value, typed against its property's grammar: what
5//! `div.style[property] = value` would accept, and how CSSOM writes it
6//! back. Shorthands expand into their longhands.
7
8use std::borrow::Cow;
9use std::fmt::{self, Write};
10
11use super::color::Color;
12use super::grammar::Grammar;
13use super::matcher::{Matcher, Out, canonical};
14use super::math::Math;
15use super::properties::{Property, property};
16use super::units::{Unit, write_number};
17use crate::parser::{ComponentValue, Declaration};
18use crate::serialize::{write_identifier, write_string, write_values};
19use crate::tokenizer::Token;
20
21/// One typed value in a property's value.
22#[derive(Clone, Debug, PartialEq)]
23pub enum Component<'a> {
24    /// A keyword from the grammar, in lowercase.
25    Keyword(&'static str),
26    /// An identifier the grammar leaves open, as written: `<custom-ident>`.
27    Ident(Cow<'a, str>),
28    Number {
29        value: f64,
30        integer: bool,
31    },
32    Percentage(f64),
33    Dimension(f64, Unit),
34    Math(Math),
35    Color(Color),
36    String(Cow<'a, str>),
37    Url(Cow<'a, str>),
38    /// `,`, `/` and the like, where the grammar has them.
39    Literal(char),
40    Function {
41        /// In lowercase.
42        name: &'static str,
43        arguments: Vec<Component<'a>>,
44    },
45    /// `[ … ]`, as grid line names are written.
46    Block(Vec<Component<'a>>),
47    /// `( … )`.
48    Parens(Vec<Component<'a>>),
49    /// `<declaration-value>`: tokens the grammar takes as they are.
50    Tokens(Vec<ComponentValue<'a>>),
51}
52
53/// The CSS-wide keywords, which every property takes.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum CssWide {
56    Initial,
57    Inherit,
58    Unset,
59    Revert,
60    RevertLayer,
61}
62
63impl CssWide {
64    fn parse(word: &str) -> Option<CssWide> {
65        // By length first: most words are none of these.
66        let k = match word.len() {
67            7 if word.eq_ignore_ascii_case("initial") => CssWide::Initial,
68            7 if word.eq_ignore_ascii_case("inherit") => CssWide::Inherit,
69            5 if word.eq_ignore_ascii_case("unset") => CssWide::Unset,
70            6 if word.eq_ignore_ascii_case("revert") => CssWide::Revert,
71            12 if word.eq_ignore_ascii_case("revert-layer") => CssWide::RevertLayer,
72            _ => return None,
73        };
74        Some(k)
75    }
76
77    pub fn as_str(self) -> &'static str {
78        match self {
79            CssWide::Initial => "initial",
80            CssWide::Inherit => "inherit",
81            CssWide::Unset => "unset",
82            CssWide::Revert => "revert",
83            CssWide::RevertLayer => "revert-layer",
84        }
85    }
86}
87
88/// A property's specified value.
89#[derive(Clone, Debug, PartialEq)]
90pub enum Specified<'a> {
91    CssWide(CssWide),
92    /// A value with `var()` or `env()` in it: valid until substitution
93    /// says otherwise, so kept as written, to be parsed then.
94    Unparsed(Vec<ComponentValue<'a>>),
95    /// A custom property's value, as written.
96    Custom(Vec<ComponentValue<'a>>),
97    /// A value that matched the property's grammar.
98    Value(Vec<Component<'a>>),
99}
100
101/// The value didn't match the property's grammar, or the property isn't
102/// one the specs define.
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub struct InvalidValue;
105
106impl fmt::Display for InvalidValue {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.write_str("invalid value")
109    }
110}
111
112impl std::error::Error for InvalidValue {}
113
114fn trim<'v, 'a>(values: &'v [ComponentValue<'a>]) -> &'v [ComponentValue<'a>] {
115    let start = values
116        .iter()
117        .position(|v| !v.is_whitespace())
118        .unwrap_or(values.len());
119    let end = values
120        .iter()
121        .rposition(|v| !v.is_whitespace())
122        .map_or(start, |i| i + 1);
123    &values[start..end]
124}
125
126/// Whether `var()` or `env()` is anywhere in the values.
127pub(crate) fn has_substitution(values: &[ComponentValue<'_>]) -> bool {
128    // Most values have no functions or blocks, and need no stack.
129    let mut stack = Vec::new();
130    let mut list = values;
131    loop {
132        for v in list {
133            match v {
134                ComponentValue::Function(f) => {
135                    if f.name.eq_ignore_ascii_case("var") || f.name.eq_ignore_ascii_case("env") {
136                        return true;
137                    }
138                    stack.push(&f.arguments[..]);
139                }
140                ComponentValue::Block(b) => stack.push(&b.contents[..]),
141                ComponentValue::Token(..) => {}
142            }
143        }
144        match stack.pop() {
145            Some(next) => list = next,
146            None => return false,
147        }
148    }
149}
150
151/// Parses `value` as a value of `property`, `--` custom properties
152/// included.
153///
154/// ```
155/// use parsec_css::values::parse_value;
156///
157/// let v = parsec_css::parse_component_values("1PX  calc(2px + 3px) AUTO");
158/// assert_eq!(parse_value("margin", &v).unwrap().to_string(), "1px calc(5px) auto");
159/// let v = parsec_css::parse_component_values("solid");
160/// assert!(parse_value("margin", &v).is_err());
161/// ```
162pub fn parse_value<'a>(
163    property_name: &str,
164    value: &[ComponentValue<'a>],
165) -> Result<Specified<'a>, InvalidValue> {
166    let value = trim(value);
167    if property_name.starts_with("--") {
168        return Ok(Specified::Custom(value.to_vec()));
169    }
170    let p = property(property_name).ok_or(InvalidValue)?;
171    parse_for(p, value)
172}
173
174fn parse_for<'a>(
175    p: &'static Property,
176    value: &[ComponentValue<'a>],
177) -> Result<Specified<'a>, InvalidValue> {
178    if let [ComponentValue::Token(Token::Ident(w), _)] = value
179        && let Some(k) = CssWide::parse(w)
180    {
181        return Ok(Specified::CssWide(k));
182    }
183    if value.is_empty() {
184        return Err(InvalidValue);
185    }
186    if let [ComponentValue::Token(Token::Ident(w), _)] = value {
187        let Some(lone) = lone(p, w) else {
188            if !p.takes_names() {
189                return Err(InvalidValue);
190            }
191            return parse_matched(p, value);
192        };
193        return match lone {
194            Lone::Invalid => Err(InvalidValue),
195            Lone::Keywords(k) => Ok(Specified::Value(
196                k.iter().map(|k| Component::Keyword(k)).collect(),
197            )),
198            Lone::Other => parse_matched(p, value),
199        };
200    }
201    if has_substitution(value) {
202        return Ok(Specified::Unparsed(value.to_vec()));
203    }
204    if p.name == "font-family"
205        && let Some(found) = font_family(value)
206    {
207        return found;
208    }
209    // One token, `1px` or `#fff`, for a grammar of plain alternatives.
210    if let [v @ ComponentValue::Token(..)] = value {
211        let f = flags(p);
212        if !f.form
213            && !f.restricted
214            && let Some(g) = p.grammar()
215            && let Some(found) = super::matcher::single(g, v)
216        {
217            return found.map(|c| Specified::Value(vec![c])).ok_or(InvalidValue);
218        }
219    }
220    parse_matched(p, value)
221}
222
223/// `font-family` without the matcher, which takes a while over a long
224/// list: each name a string, identifiers, or a generic family's keyword,
225/// as CSS Fonts 4 §2.1 says. `None` for anything else, `generic(kai)` say.
226fn font_family<'a>(value: &[ComponentValue<'a>]) -> Option<Result<Specified<'a>, InvalidValue>> {
227    use super::restrict::{CSS_WIDE, GENERIC_FAMILIES};
228    let mut c = Vec::with_capacity(value.len());
229    for item in value.split(|v| matches!(v, ComponentValue::Token(Token::Comma, _))) {
230        if !c.is_empty() {
231            c.push(Component::Literal(','));
232        }
233        let mut words = item.iter().filter(|v| !v.is_whitespace()).peekable();
234        match words.peek() {
235            None => return Some(Err(InvalidValue)),
236            Some(ComponentValue::Token(Token::String(s), _)) => {
237                c.push(Component::String(s.clone()));
238                words.next();
239                if words.next().is_some() {
240                    return Some(Err(InvalidValue));
241                }
242            }
243            Some(_) => {
244                let start = c.len();
245                for w in words {
246                    let ComponentValue::Token(Token::Ident(s), _) = w else {
247                        return None;
248                    };
249                    c.push(Component::Ident(s.clone()));
250                }
251                // One word that's a generic family is its keyword; a
252                // generic family or a CSS-wide keyword in a name is no
253                // name at all.
254                let generic = |x: &Component<'_>| {
255                    GENERIC_FAMILIES
256                        .iter()
257                        .find(|g| matches!(x, Component::Ident(s) if s.eq_ignore_ascii_case(g)))
258                };
259                if c.len() - start == 1
260                    && let Some(g) = generic(&c[start])
261                {
262                    c[start] = Component::Keyword(g);
263                    continue;
264                }
265                let reserved = c[start..].iter().any(|x| {
266                    generic(x).is_some()
267                        || matches!(x, Component::Ident(s) if CSS_WIDE.iter().any(|w| s.eq_ignore_ascii_case(w)))
268                });
269                if reserved {
270                    return Some(Err(InvalidValue));
271                }
272            }
273        }
274    }
275    super::canonical::form("font-family", &mut c);
276    Some(Ok(Specified::Value(c)))
277}
278
279/// What [`parse_matched`] has to do for a property, worked out once.
280#[derive(Clone, Copy)]
281struct Flags {
282    keep_order: bool,
283    restricted: bool,
284    form: bool,
285}
286
287fn flags(p: &'static Property) -> Flags {
288    use std::sync::OnceLock;
289    static ALL: OnceLock<Vec<OnceLock<Flags>>> = OnceLock::new();
290    let all = ALL.get_or_init(|| {
291        super::properties::properties()
292            .iter()
293            .map(|_| OnceLock::new())
294            .collect()
295    });
296    let work = || {
297        let name = p.alias_of.unwrap_or(p.name);
298        Flags {
299            keep_order: super::canonical::KEEP_ORDER.contains(&name),
300            restricted: super::restrict::PROPERTIES.contains(&name),
301            form: super::canonical::has_form(name),
302        }
303    };
304    match p.position().and_then(|i| all.get(i)) {
305        Some(cell) => *cell.get_or_init(work),
306        None => work(),
307    }
308}
309
310/// What one of a property's keywords alone parses to.
311enum Lone {
312    Invalid,
313    Keywords(Vec<&'static str>),
314    /// Something else, `0 0 auto` for `flex: none`: worked out each time.
315    Other,
316}
317
318type LoneTable = std::collections::HashMap<&'static [u8], Lone, super::properties::FnvBuild>;
319
320/// A value of one keyword, worked out the long way once for each keyword
321/// of each property, the first time the property's value is parsed: most
322/// declarations are a keyword alone (`display: none`), and its grammar
323/// can take many steps to say so. `None` for a word that's no keyword of
324/// the property's, or one that parses to something else, a name.
325fn lone(p: &'static Property, word: &str) -> Option<&'static Lone> {
326    use std::sync::OnceLock;
327    static ALL: OnceLock<Vec<OnceLock<LoneTable>>> = OnceLock::new();
328    let all = ALL.get_or_init(|| {
329        super::properties::properties()
330            .iter()
331            .map(|_| OnceLock::new())
332            .collect()
333    });
334    let table = all.get(p.position()?)?.get_or_init(|| {
335        p.keywords()
336            .iter()
337            .map(|k| {
338                let values = crate::parse_component_values(k);
339                let lone = match parse_matched(p, &values) {
340                    Err(_) => Lone::Invalid,
341                    Ok(Specified::Value(c)) => c
342                        .iter()
343                        .map(|c| match c {
344                            Component::Keyword(k) => Some(*k),
345                            _ => None,
346                        })
347                        .collect::<Option<_>>()
348                        .map_or(Lone::Other, Lone::Keywords),
349                    Ok(_) => Lone::Other,
350                };
351                (k.as_bytes(), lone)
352            })
353            .collect()
354    });
355    // Lowercased as bytes: no need to check it's still UTF-8.
356    let mut buf = [0u8; 32];
357    let out = buf.get_mut(..word.len())?;
358    out.copy_from_slice(word.as_bytes());
359    out.make_ascii_lowercase();
360    table.get(&*out)
361}
362
363/// [`parse_for`] after its shortcuts: the value matched against the
364/// grammar.
365fn parse_matched<'a>(
366    p: &'static Property,
367    value: &[ComponentValue<'a>],
368) -> Result<Specified<'a>, InvalidValue> {
369    let g = p.grammar().ok_or(InvalidValue)?;
370    // A keyword the grammar has elsewhere is taken as that keyword where it
371    // can be (`span` in `grid-column`), and as a name only if nothing
372    // else reads.
373    let mut m = Matcher::new(value).for_property(p);
374    if !m.whole(g) {
375        m = Matcher::new(value);
376        if !m.whole(g) {
377            return Err(InvalidValue);
378        }
379    }
380    let name = p.alias_of.unwrap_or(p.name);
381    let f = flags(p);
382    let outs = canonical(m.out, f.keep_order);
383    let mut c = match same_pair(g, &outs) {
384        Some(first) => components(first),
385        None => components(outs),
386    };
387    if f.restricted && !super::restrict::property(name, value, &c) {
388        return Err(InvalidValue);
389    }
390    shortest(g, &mut c);
391    if f.form {
392        super::canonical::form(name, &mut c);
393    }
394    Ok(Specified::Value(c))
395}
396
397/// For `<'a'> <'b'>?`, as `place-items` is, the first part alone when the
398/// second is the same: `center center` is `center`.
399fn same_pair<'a>(g: &Grammar, outs: &[Out<'a>]) -> Option<Vec<Out<'a>>> {
400    let Grammar::Sequence(items) = g else {
401        return None;
402    };
403    let [
404        Grammar::Property(_) | Grammar::Type(_),
405        Grammar::Repeat {
406            item,
407            min: 0,
408            max: 1,
409            ..
410        },
411    ] = &items[..]
412    else {
413        return None;
414    };
415    if let (Grammar::Type(a), Grammar::Type(b)) = (&items[0], &**item)
416        && a == b
417        && single(&items[0])
418    {
419        // `<inset-value> <inset-value>?`: the second left out is the first.
420        let values: Vec<&Out<'a>> = outs.iter().filter(|o| matches!(o, Out::C(_))).collect();
421        if let [Out::C(x), Out::C(y)] = values[..]
422            && x == y
423        {
424            return Some(vec![Out::C(x.clone())]);
425        }
426        return None;
427    }
428    if !matches!(**item, Grammar::Property(_)) {
429        return None;
430    }
431    let parts = segments(outs);
432    let [(Some(_), a), (Some(_), b)] = &parts[..] else {
433        return None;
434    };
435    let text = |o: &[Out<'a>]| Specified::Value(components(o.to_vec())).to_string();
436    (text(a) == text(b)).then(|| a.to_vec())
437}
438
439/// Leaves out what a box shorthand repeats, as CSSOM writes them:
440/// `1px 2px 1px 2px` is `1px 2px`, `3px 3px` is `3px`.
441fn shortest(g: &Grammar, c: &mut Vec<Component<'_>>) {
442    let Grammar::Repeat {
443        item,
444        min: 1,
445        max: max @ (2 | 4),
446        commas: false,
447    } = g
448    else {
449        return;
450    };
451    // Only where each item is one value.
452    if !single(item) || c.len() > *max as usize {
453        return;
454    }
455    super::canonical::sides(c);
456}
457
458/// [`shortest`] for a property by name.
459pub(crate) fn shortest_of(name: &str, c: &mut Vec<Component<'_>>) {
460    if let Some(g) = property(name).and_then(|p| p.grammar()) {
461        shortest(g, c);
462    }
463}
464
465/// Whether a grammar always matches exactly one value.
466fn single(g: &Grammar) -> bool {
467    match g {
468        Grammar::Keyword(_) | Grammar::Property(_) | Grammar::Function(..) => true,
469        Grammar::Type(t) => !matches!(&*t.name, "position" | "bg-position" | "track-list"),
470        Grammar::One(alts) => alts.iter().all(single),
471        _ => false,
472    }
473}
474
475fn components(out: Vec<Out<'_>>) -> Vec<Component<'_>> {
476    out.into_iter()
477        .filter_map(|o| match o {
478            Out::C(c) => Some(c),
479            _ => None,
480        })
481        .collect()
482}
483
484/// Matches `values` against the grammar the specs give a function, as
485/// `<color-mix()>`, for the colors that are matched that way.
486pub(crate) fn match_function<'a>(
487    name: &str,
488    values: &[ComponentValue<'a>],
489) -> Option<Vec<Component<'a>>> {
490    let g = super::properties::function_grammar(name)?;
491    let mut m = Matcher::new(values);
492    if !m.whole(g) {
493        return None;
494    }
495    Some(components(canonical(m.out, false)))
496}
497
498/// Matches all of `values` against a grammar of the caller's: an
499/// at-rule's descriptor, a registered property's syntax.
500pub(crate) fn match_grammar<'a>(
501    g: &'static Grammar,
502    values: &[ComponentValue<'a>],
503) -> Option<Vec<Component<'a>>> {
504    let values = trim(values);
505    if values.is_empty() {
506        return None;
507    }
508    let mut m = Matcher::new(values);
509    if !m.whole(g) {
510        return None;
511    }
512    Some(components(canonical(m.out, false)))
513}
514
515/// Parses a declaration's value for its property.
516pub fn parse_declaration_value<'a>(d: &Declaration<'a>) -> Result<Specified<'a>, InvalidValue> {
517    parse_value(&d.name, &d.value)
518}
519
520/// Parses a shorthand's value and splits it into a value for each of its
521/// longhands, in the order the spec lists them; a longhand the value
522/// leaves out gets its initial value. A longhand that is itself a
523/// shorthand (`border-width` in `border`) is followed by its own. A
524/// longhand gives itself.
525///
526/// ```
527/// use parsec_css::values::expand;
528///
529/// let v = parsec_css::parse_component_values("1px 2px");
530/// let longhands: Vec<String> = expand("margin", &v)
531///     .unwrap()
532///     .iter()
533///     .map(|(name, value)| format!("{name}: {value}"))
534///     .collect();
535/// assert_eq!(
536///     longhands,
537///     ["margin-top: 1px", "margin-right: 2px", "margin-bottom: 1px", "margin-left: 2px"]
538/// );
539/// ```
540pub fn expand<'a>(
541    shorthand: &str,
542    value: &[ComponentValue<'a>],
543) -> Result<Vec<(&'static str, Specified<'a>)>, InvalidValue> {
544    let p = property(shorthand).ok_or(InvalidValue)?;
545    let value = trim(value);
546    if !p.is_shorthand() {
547        return Ok(vec![(p.name, parse_for(p, value)?)]);
548    }
549    match parse_for(p, value)? {
550        Specified::Value(_) => {}
551        // Every longhand takes the keyword, or waits for substitution.
552        other => {
553            let mut leaves = Vec::new();
554            leaf_longhands(p, &mut leaves);
555            return Ok(leaves.into_iter().map(|l| (l, other.clone())).collect());
556        }
557    }
558    if let Some(special) = expand_special(p, value) {
559        return Ok(special);
560    }
561    let g = p.grammar().ok_or(InvalidValue)?;
562    let mut m = Matcher::new(value).for_property(p);
563    if !m.whole(g) {
564        m = Matcher::new(value);
565        m.whole(g);
566    }
567    let outs = canonical(m.out, false);
568    let mut result = Vec::with_capacity(p.longhands.len());
569    assign(p, g, &outs, &mut result)?;
570    // CSS Masking 1 §7.10 and CSS Backgrounds 3 §4.4: `mask` resets
571    // `mask-border` too, and `border` `border-image`.
572    let resets = match p.name {
573        "mask" => Some("mask-border"),
574        "border" => Some("border-image"),
575        _ => None,
576    };
577    if let Some(border) = resets.and_then(property) {
578        result.push((border.name, initial(border.name)));
579        result.extend(border.longhands.iter().map(|l| (*l, initial(l))));
580    }
581    Ok(result)
582}
583
584/// Splits a match of shorthand `p`'s grammar `g` into its longhands, and
585/// those that are shorthands into theirs after them, onto `result`.
586fn assign<'a>(
587    p: &'static Property,
588    g: &'static Grammar,
589    outs: &[Out<'a>],
590    result: &mut Vec<(&'static str, Specified<'a>)>,
591) -> Result<(), InvalidValue> {
592    let mut assigned: Vec<Option<Vec<Out<'a>>>> = vec![None; p.longhands.len()];
593    // Lists of layers, `background` or `transition`, layer by layer.
594    let listed = matches!(g, Grammar::Repeat { commas: true, .. }) || p.name == "background";
595    let by_layer = listed && (p.longhands.len() > 2 || p.name == "animation-range");
596    if by_layer || split(p, g, outs, &mut assigned).is_none() {
597        assigned = layers(p, outs).ok_or(InvalidValue)?;
598    }
599    for (name, part) in p.longhands.iter().zip(assigned) {
600        let Some(lp) = property(name) else { continue };
601        if lp.is_shorthand() {
602            // The shorthand itself, then its own longhands.
603            match (part, lp.grammar()) {
604                (Some(outs), Some(sg)) => {
605                    let mut c = components(outs.clone());
606                    super::canonical::property(name, &mut c);
607                    result.push((*name, Specified::Value(c)));
608                    assign(lp, sg, &outs, result)?
609                }
610                _ => {
611                    result.push((*name, initial(name)));
612                    let mut leaves = Vec::new();
613                    leaf_longhands(lp, &mut leaves);
614                    result.extend(leaves.into_iter().map(|l| (l, initial(l))));
615                }
616            }
617            continue;
618        }
619        let value = match part {
620            Some(outs) => {
621                let mut c = components(outs);
622                shortest_of(name, &mut c);
623                super::canonical::property(name, &mut c);
624                Specified::Value(c)
625            }
626            None => initial(name),
627        };
628        result.push((*name, value));
629    }
630    Ok(())
631}
632
633/// A shorthand's longhands, those that are shorthands by theirs.
634fn leaf_longhands(p: &'static Property, out: &mut Vec<&'static str>) {
635    for l in p.longhands {
636        out.push(l);
637        if let Some(lp) = property(l)
638            && lp.is_shorthand()
639        {
640            leaf_longhands(lp, out);
641        }
642    }
643}
644
645/// Splits a comma-separated list of layers, `background` or `transition`
646/// say, by finding for each run of values in a layer the longhand that
647/// takes it, longest runs first, in the longhands' order; what follows a
648/// `/` goes first. A longhand with no list (`background-color`) takes its
649/// value from the layer that has it.
650fn layers<'a>(p: &'static Property, outs: &[Out<'a>]) -> Option<Vec<Option<Vec<Out<'a>>>>> {
651    let all = components(outs.to_vec());
652    let n = p.longhands.len();
653    let mut per: Vec<Vec<Option<Vec<Component<'a>>>>> = Vec::new();
654    for layer in all.split(|c| *c == Component::Literal(',')) {
655        let mut got: Vec<Option<Vec<Component<'a>>>> = vec![None; n];
656        let mut rest: Vec<Component<'a>> = layer.to_vec();
657        let mut slashed = None;
658        if let Some(s) = rest.iter().position(|c| *c == Component::Literal('/')) {
659            let after = rest.split_off(s);
660            slashed = Some(after[1..].to_vec());
661        }
662        if let Some(after) = slashed {
663            // The run before the `/` and the run after it, for the two
664            // longhands that take them.
665            let (i, before) = take_run(p, &mut rest, &got, true)?;
666            got[i] = Some(before);
667            let mut after = after;
668            let (j, run) = take_run(p, &mut after, &got, false)?;
669            got[j] = Some(run);
670            if !after.is_empty() {
671                rest.extend(after);
672            }
673        }
674        while !rest.is_empty() {
675            let (i, run) = take_run(p, &mut rest, &got, false)?;
676            got[i] = Some(run);
677        }
678        // Scroll Animations 1 §4.4: an end left out is the start's range
679        // name, at its own default, or `normal`.
680        if p.name == "animation-range"
681            && got[1].is_none()
682            && let Some(start) = &got[0]
683            && let Some(Component::Keyword(name)) = start.first()
684            && *name != "normal"
685        {
686            got[1] = Some(vec![Component::Keyword(name)]);
687        }
688        // One box is both the origin and the clip.
689        let origin = p.longhands.iter().position(|l| l.ends_with("-origin"));
690        let clip = p.longhands.iter().position(|l| l.ends_with("-clip"));
691        if let (Some(o), Some(c)) = (origin, clip)
692            && got[c].is_none()
693            && let Some(b) = got[o].clone()
694        {
695            got[c] = Some(b);
696        }
697        per.push(got);
698    }
699    let mut out = vec![None; n];
700    for (i, name) in p.longhands.iter().enumerate() {
701        let listed = property(name).and_then(|lp| lp.grammar()).is_some_and(|g| {
702            let list = |g: &Grammar| matches!(g, Grammar::Repeat { commas: true, .. });
703            match g {
704                // `none | <single-transition-property>#`
705                Grammar::One(alts) => alts.iter().any(list),
706                g => list(g),
707            }
708        });
709        if !listed {
710            out[i] = per
711                .iter()
712                .rev()
713                .find_map(|l| l[i].clone())
714                .map(|c| c.into_iter().map(Out::C).collect());
715            continue;
716        }
717        let mut joined = Vec::new();
718        for (k, l) in per.iter().enumerate() {
719            if k > 0 {
720                joined.push(Out::C(Component::Literal(',')));
721            }
722            match &l[i] {
723                Some(c) => joined.extend(c.iter().cloned().map(Out::C)),
724                None => joined.extend(initial_components(name)?.into_iter().map(Out::C)),
725            }
726        }
727        out[i] = Some(joined);
728    }
729    Some(out)
730}
731
732/// The longest run at the start of `rest` (or all of it, for `whole`)
733/// that a longhand not yet given a value takes, and which one.
734fn take_run<'a>(
735    p: &'static Property,
736    rest: &mut Vec<Component<'a>>,
737    got: &[Option<Vec<Component<'a>>>],
738    whole: bool,
739) -> Option<(usize, Vec<Component<'a>>)> {
740    // No longhand takes more than a few values (a position takes four), so
741    // runs are capped: a long hostile layer stays linear.
742    let ends: Vec<usize> = if whole {
743        vec![rest.len()]
744    } else {
745        (1..=rest.len().min(8)).rev().collect()
746    };
747    for end in ends {
748        let run = &rest[..end];
749        let text = Specified::Value(run.to_vec()).to_string();
750        let values = crate::parse_component_values(&text);
751        for (i, name) in p.longhands.iter().enumerate() {
752            if got[i].is_some() {
753                continue;
754            }
755            let Some(lp) = property(name) else { continue };
756            let Ok(Specified::Value(c)) = parse_for(lp, &values) else {
757                continue;
758            };
759            // A keyword stays one: `paused` isn't an animation's name.
760            let renamed = run.iter().any(|r| match r {
761                Component::Keyword(k) => c
762                    .iter()
763                    .any(|x| matches!(x, Component::Ident(s) if s.eq_ignore_ascii_case(k))),
764                _ => false,
765            });
766            if renamed || c.contains(&Component::Literal(',')) {
767                continue;
768            }
769            let run: Vec<Component<'a>> = rest.drain(..end).collect();
770            return Some((i, run));
771        }
772    }
773    None
774}
775
776/// The shorthands whose left-out parts aren't their longhands' initial
777/// values: `flex`, where they're `1 1 0%` (CSS Flexbox §7.1), and
778/// `white-space`'s legacy keywords (CSS Text 4 §3).
779fn expand_special<'a>(
780    p: &'static Property,
781    value: &[ComponentValue<'a>],
782) -> Option<Vec<(&'static str, Specified<'a>)>> {
783    let keyword = match value {
784        [ComponentValue::Token(Token::Ident(w), _)] => Some(w.to_ascii_lowercase()),
785        _ => None,
786    };
787    let text = |s: &'static str| -> Specified<'a> {
788        let values = crate::parse_component_values(s);
789        let Ok(Specified::Value(c)) = parse_value_static(s, &values) else {
790            unreachable!("{s}")
791        };
792        Specified::Value(c)
793    };
794    match p.name {
795        "white-space" => {
796            let (collapse, wrap) = match keyword.as_deref()? {
797                "normal" => ("collapse", "wrap"),
798                "pre" => ("preserve", "nowrap"),
799                "pre-wrap" => ("preserve", "wrap"),
800                "pre-line" => ("preserve-breaks", "wrap"),
801                _ => return None,
802            };
803            let kw = |k: &'static str| Specified::Value(vec![Component::Keyword(k)]);
804            Some(vec![
805                ("white-space-collapse", kw(collapse)),
806                ("text-wrap-mode", kw(wrap)),
807            ])
808        }
809        "border-radius" | "grid-area" | "grid-row" | "grid-column" | "place-content" => {
810            let Ok(Specified::Value(c)) = parse_for(p, value) else {
811                return None;
812            };
813            // The value before its shortest form: what each part says.
814            let c = match p.name {
815                "place-content" => c,
816                _ => {
817                    let g = p.grammar()?;
818                    let mut m = Matcher::new(value).for_property(p);
819                    if !m.whole(g) {
820                        m = Matcher::new(value);
821                        m.whole(g);
822                    }
823                    components(canonical(m.out, false))
824                }
825            };
826            let parts: Vec<Vec<Component<'a>>> = c
827                .split(|x| *x == Component::Literal('/'))
828                .map(<[_]>::to_vec)
829                .collect();
830            let value = |c: Vec<Component<'a>>| Specified::Value(c);
831            match p.name {
832                // CSS Backgrounds 3 §5.1: one to four corners, then as many
833                // vertical radii, the same if left out.
834                "border-radius" => {
835                    let corner = |part: &[Component<'a>], i: usize| -> Option<Component<'a>> {
836                        let at = match (part.len(), i) {
837                            (1, _) => 0,
838                            (2, i) => i % 2,
839                            (3, 3) => 1,
840                            (3, i) => i,
841                            (4, i) => i,
842                            _ => return None,
843                        };
844                        part.get(at).cloned()
845                    };
846                    let v = parts.get(1).unwrap_or(&parts[0]);
847                    (0..4)
848                        .map(|i| {
849                            let (a, b) = (corner(&parts[0], i)?, corner(v, i)?);
850                            let c = if a == b { vec![a] } else { vec![a, b] };
851                            Some((p.longhands[i], value(c)))
852                        })
853                        .collect()
854                }
855                // CSS Box Alignment §5.1: with a baseline, `start` across.
856                "place-content" => {
857                    // In its shortest form, the baseline and then what's
858                    // across: `start` if nothing was given.
859                    let at = c
860                        .iter()
861                        .position(|x| *x == Component::Keyword("baseline"))?;
862                    let mut align = c;
863                    let mut justify = align.split_off(at + 1);
864                    if justify.is_empty() {
865                        justify.push(Component::Keyword("start"));
866                    }
867                    Some(vec![
868                        (p.longhands[0], value(align)),
869                        (p.longhands[1], value(justify)),
870                    ])
871                }
872                // CSS Grid 2 §8.4: a line left out is the one it pairs
873                // with if that's a name, `auto` if not.
874                _ => {
875                    let default = |of: &Vec<Component<'a>>| match &of[..] {
876                        [Component::Ident(_)] => of.clone(),
877                        _ => vec![Component::Keyword("auto")],
878                    };
879                    let n = p.longhands.len();
880                    let mut lines: Vec<Vec<Component<'a>>> = parts.clone();
881                    let pairs: &[usize] = if n == 4 { &[0, 0, 0, 1] } else { &[0, 0] };
882                    while lines.len() < n {
883                        let i = lines.len();
884                        let d = default(&lines[pairs[i]]);
885                        lines.push(d);
886                    }
887                    // `grid-area`'s order is row start, column start, row
888                    // end, column end; its longhands' differs.
889                    Some(
890                        p.longhands
891                            .iter()
892                            .enumerate()
893                            .map(|(i, l)| {
894                                let at = match (n, *l) {
895                                    (4, "grid-row-start") => 0,
896                                    (4, "grid-column-start") => 1,
897                                    (4, "grid-row-end") => 2,
898                                    (4, "grid-column-end") => 3,
899                                    _ => i,
900                                };
901                                let mut c = lines[at].clone();
902                                super::canonical::span_one(&mut c);
903                                (*l, value(c))
904                            })
905                            .collect(),
906                    )
907                }
908            }
909        }
910        "flex" => {
911            let (grow, shrink, basis) = match keyword.as_deref() {
912                Some("none") => ("0", "0", "auto"),
913                Some("auto") => ("1", "1", "auto"),
914                _ => {
915                    // Split as the grammar does, then fill in 1, 1 and 0%.
916                    let g = p.grammar()?;
917                    let mut m = Matcher::new(value).for_property(p);
918                    if !m.whole(g) {
919                        return None;
920                    }
921                    let outs = canonical(m.out, false);
922                    let mut assigned: Vec<Option<Vec<Out<'a>>>> = vec![None; 3];
923                    split(p, g, &outs, &mut assigned)?;
924                    let mut fill = |i: usize, d: &'static str| match assigned[i].take() {
925                        Some(o) => Specified::Value(components(o)),
926                        None => text(d),
927                    };
928                    let (gw, sh, ba) = (fill(0, "1"), fill(1, "1"), fill(2, "0%"));
929                    return Some(vec![
930                        ("flex-grow", gw),
931                        ("flex-shrink", sh),
932                        ("flex-basis", ba),
933                    ]);
934                }
935            };
936            Some(vec![
937                ("flex-grow", text(grow)),
938                ("flex-shrink", text(shrink)),
939                ("flex-basis", text(basis)),
940            ])
941        }
942        _ => None,
943    }
944}
945
946/// A value from text that lives for the program: for the defaults above.
947fn parse_value_static<'a>(
948    s: &'static str,
949    values: &[ComponentValue<'static>],
950) -> Result<Specified<'a>, InvalidValue> {
951    // A number alone is `flex-grow`'s or `flex-shrink`'s; anything else
952    // is a basis.
953    let name = if s.parse::<f64>().is_ok() {
954        "flex-grow"
955    } else {
956        "flex-basis"
957    };
958    parse_value(name, values)
959}
960
961/// A longhand's initial value as its shortest form writes it, worked out
962/// once: what a shorthand leaves out when a longhand has it.
963pub(crate) fn initial_text(name: &str) -> Option<&'static str> {
964    use std::sync::OnceLock;
965    static ALL: OnceLock<Vec<OnceLock<Option<String>>>> = OnceLock::new();
966    let all = ALL.get_or_init(|| {
967        super::properties::properties()
968            .iter()
969            .map(|_| OnceLock::new())
970            .collect()
971    });
972    let p = property(name)?;
973    let cell = all.get(p.position()?)?;
974    cell.get_or_init(|| {
975        if p.is_shorthand() {
976            // Its longhands', in order: `0% 0%` for `background-position`.
977            let parts: Option<Vec<&str>> = p.longhands.iter().map(|l| initial_text(l)).collect();
978            let text = parts?.join(" ");
979            let values = crate::parse_component_values(&text);
980            return match parse_for(p, &values) {
981                Ok(v @ Specified::Value(_)) => Some(v.to_string()),
982                _ => None,
983            };
984        }
985        match initial(p.name) {
986            v @ Specified::Value(_) => Some(v.to_string()),
987            _ => p.initial.map(str::to_ascii_lowercase),
988        }
989    })
990    .as_deref()
991}
992
993/// A longhand's initial value, typed, worked out once.
994pub(crate) fn initial_cached(name: &str) -> Option<&'static [Component<'static>]> {
995    use std::sync::OnceLock;
996    static ALL: OnceLock<Vec<OnceLock<Option<Vec<Component<'static>>>>>> = OnceLock::new();
997    let all = ALL.get_or_init(|| {
998        super::properties::properties()
999            .iter()
1000            .map(|_| OnceLock::new())
1001            .collect()
1002    });
1003    let p = property(name)?;
1004    all.get(p.position()?)?
1005        .get_or_init(|| initial_components(p.name))
1006        .as_deref()
1007}
1008
1009/// A longhand's initial value, typed, if the spec gives one as a value.
1010pub(crate) fn initial_components(name: &str) -> Option<Vec<Component<'static>>> {
1011    match initial(name) {
1012        Specified::Value(c) => Some(c),
1013        _ => None,
1014    }
1015}
1016
1017/// A longhand's initial value, parsed, or `initial` where the spec's is
1018/// prose. The text is the table's, so the value borrows nothing.
1019fn initial(name: &str) -> Specified<'static> {
1020    let parsed = property(name).and_then(|p| {
1021        let text = match p.is_shorthand() {
1022            true => initial_text(p.name)?,
1023            false => p.initial?,
1024        };
1025        let values = crate::parse_component_values(text);
1026        match parse_for(p, &values) {
1027            Ok(v @ Specified::Value(_)) => Some(v),
1028            _ => None,
1029        }
1030    });
1031    parsed.unwrap_or(Specified::CssWide(CssWide::Initial))
1032}
1033
1034/// The top-level parts of a match: each `(property, outs)` that matched a
1035/// property reference, and the values outside any.
1036fn segments<'o, 'a>(outs: &'o [Out<'a>]) -> Vec<(Option<&'static str>, &'o [Out<'a>])> {
1037    let mut parts = Vec::new();
1038    let mut i = 0;
1039    while i < outs.len() {
1040        match &outs[i] {
1041            Out::Start(p) => {
1042                let name = &p.name;
1043                let mut depth = 0;
1044                let mut j = i;
1045                loop {
1046                    match outs[j] {
1047                        Out::Start(_) => depth += 1,
1048                        Out::End => {
1049                            depth -= 1;
1050                            if depth == 0 {
1051                                break;
1052                            }
1053                        }
1054                        _ => {}
1055                    }
1056                    j += 1;
1057                }
1058                parts.push((Some(*name), &outs[i + 1..j]));
1059                i = j + 1;
1060            }
1061            Out::C(_) => {
1062                parts.push((None, &outs[i..i + 1]));
1063                i += 1;
1064            }
1065            _ => i += 1,
1066        }
1067    }
1068    parts
1069}
1070
1071/// Assigns the parts of `outs`, a match of `p`'s grammar `g`, to `p`'s
1072/// longhands in `assigned`.
1073fn split<'a>(
1074    p: &'static Property,
1075    g: &'static Grammar,
1076    outs: &[Out<'a>],
1077    assigned: &mut [Option<Vec<Out<'a>>>],
1078) -> Option<()> {
1079    let parts = segments(outs);
1080    let refs: Vec<&'static str> = parts.iter().filter_map(|(n, _)| *n).collect();
1081    if refs.is_empty() && split_by_position(p, g, outs, assigned).is_some() {
1082        return Some(());
1083    }
1084    let slot = |name: &str| p.longhands.iter().position(|l| *l == name);
1085    // `<'margin-top'>{1,4}`: one property written one to four times, over
1086    // four sides, or `{1,2}` over two.
1087    let repeat_of_one = matches!(g, Grammar::Repeat { item, min: 1, max: 2 | 4, commas: false }
1088        if matches!(**item, Grammar::Property(_)));
1089    if !refs.is_empty() && refs.iter().all(|r| *r == refs[0]) && (refs.len() > 1 || repeat_of_one)
1090        || (refs.len() == 1 && slot(refs[0]).is_none() && matches!(p.longhands.len(), 2 | 4))
1091    {
1092        let values: Vec<&[Out<'a>]> = parts
1093            .iter()
1094            .filter(|(n, _)| n.is_some())
1095            .map(|(_, o)| *o)
1096            .collect();
1097        let order: &[usize] = match (p.longhands.len(), values.len()) {
1098            (4, 1) => &[0, 0, 0, 0],
1099            (4, 2) => &[0, 1, 0, 1],
1100            (4, 3) => &[0, 1, 2, 1],
1101            (4, 4) => &[0, 1, 2, 3],
1102            (2, 1) => &[0, 0],
1103            (2, 2) => &[0, 1],
1104            _ => return None,
1105        };
1106        for (slot, i) in assigned.iter_mut().zip(order) {
1107            *slot = Some(values[*i].to_vec());
1108        }
1109        return Some(());
1110    }
1111    // `rule: <'column-rule'>`: one value for each of its longhands.
1112    if let Grammar::Property(_) = g
1113        && let [(Some(_), part)] = &parts[..]
1114    {
1115        for slot in assigned.iter_mut() {
1116            *slot = Some(part.to_vec());
1117        }
1118        return Some(());
1119    }
1120    for (name, part) in &parts {
1121        let Some(name) = name else { continue };
1122        if let Some(i) = slot(name) {
1123            assigned[i] = Some(part.to_vec());
1124            continue;
1125        }
1126        // A shorthand inside a shorthand: `border-width` in `border`.
1127        let sub = property(name)?;
1128        if sub.is_shorthand() {
1129            let mut inner = vec![None; sub.longhands.len()];
1130            split(sub, sub.grammar()?, part, &mut inner)?;
1131            for (l, v) in sub.longhands.iter().zip(inner) {
1132                if let (Some(i), Some(v)) = (slot(l), v) {
1133                    assigned[i] = Some(v);
1134                }
1135            }
1136        }
1137    }
1138    // `<'row-gap'> <'column-gap'>?`: the second, left out, is the first.
1139    if let Grammar::Sequence(items) = g
1140        && let [
1141            Grammar::Property(a),
1142            Grammar::Repeat {
1143                item,
1144                min: 0,
1145                max: 1,
1146                ..
1147            },
1148        ] = &items[..]
1149        && let Grammar::Property(b) = &**item
1150        && p.longhands == [&*a.name, &*b.name]
1151        && assigned[1].is_none()
1152    {
1153        assigned[1] = assigned[0].clone();
1154    }
1155    // Values outside any property reference go to each longhand that
1156    // takes them: `border: 1px solid red`.
1157    for (name, part) in &parts {
1158        if name.is_some() {
1159            continue;
1160        }
1161        let [Out::C(c)] = part else { continue };
1162        if matches!(c, Component::Literal(_)) {
1163            continue;
1164        }
1165        let text = Specified::Value(vec![c.clone()]).to_string();
1166        let values = crate::parse_component_values(&text);
1167        let mut taken = false;
1168        for (i, l) in p.longhands.iter().enumerate() {
1169            if assigned[i].is_some() {
1170                continue;
1171            }
1172            let lp = property(l)?;
1173            if matches!(parse_for(lp, &values), Ok(Specified::Value(_))) {
1174                assigned[i] = Some(part.to_vec());
1175                taken = true;
1176            }
1177        }
1178        if !taken {
1179            return None;
1180        }
1181    }
1182    Some(())
1183}
1184
1185/// Shorthands whose grammar is positions rather than longhands: one to
1186/// four values over four sides (`border-color: red blue`), one or two
1187/// over a pair, or two separated by `/` (`grid-column: 1 / 3`), where a
1188/// second left out is the first if that's a name, and initial if not.
1189fn split_by_position<'a>(
1190    p: &'static Property,
1191    g: &Grammar,
1192    outs: &[Out<'a>],
1193    assigned: &mut [Option<Vec<Out<'a>>>],
1194) -> Option<()> {
1195    let values: Vec<&Out<'a>> = outs.iter().filter(|o| matches!(o, Out::C(_))).collect();
1196    match g {
1197        Grammar::Repeat {
1198            min: 1,
1199            max: max @ (2 | 4),
1200            commas: false,
1201            ..
1202        } if p.longhands.len() == *max as usize && values.len() <= *max as usize => {
1203            let order: &[usize] = match (max, values.len()) {
1204                (4, 1) => &[0, 0, 0, 0],
1205                (4, 2) => &[0, 1, 0, 1],
1206                (4, 3) => &[0, 1, 2, 1],
1207                (4, 4) => &[0, 1, 2, 3],
1208                (2, 1) => &[0, 0],
1209                (2, 2) => &[0, 1],
1210                _ => return None,
1211            };
1212            for (slot, i) in assigned.iter_mut().zip(order) {
1213                *slot = Some(vec![values[*i].clone()]);
1214            }
1215            Some(())
1216        }
1217        Grammar::Sequence(items) if p.longhands.len() == 2 => {
1218            let [
1219                _,
1220                Grammar::Repeat {
1221                    item,
1222                    min: 0,
1223                    max: 1,
1224                    ..
1225                },
1226            ] = &items[..]
1227            else {
1228                return None;
1229            };
1230            let Grammar::Sequence(inner) = &**item else {
1231                return None;
1232            };
1233            if inner.first() != Some(&Grammar::Literal('/')) {
1234                return None;
1235            }
1236            let slash = outs
1237                .iter()
1238                .position(|o| matches!(o, Out::C(Component::Literal('/'))));
1239            let (first, second) = match slash {
1240                Some(i) => (&outs[..i], Some(&outs[i + 1..])),
1241                None => (outs, None),
1242            };
1243            assigned[0] = Some(first.to_vec());
1244            assigned[1] = match second {
1245                Some(s) => Some(s.to_vec()),
1246                None if matches!(first, [Out::C(Component::Ident(_))]) => Some(first.to_vec()),
1247                None => None,
1248            };
1249            Some(())
1250        }
1251        _ => None,
1252    }
1253}
1254
1255/// Writes typed values as CSSOM serializes a specified value: separated
1256/// by spaces, commas followed by one.
1257pub fn write_components(out: &mut impl Write, components: &[Component<'_>]) -> fmt::Result {
1258    for (i, c) in components.iter().enumerate() {
1259        if i > 0 && *c != Component::Literal(',') {
1260            out.write_char(' ')?;
1261        }
1262        write!(out, "{c}")?;
1263    }
1264    Ok(())
1265}
1266
1267impl fmt::Display for Component<'_> {
1268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1269        match self {
1270            Component::Keyword(k) => f.write_str(k),
1271            Component::Ident(i) => write_identifier(f, i),
1272            Component::Number { value, .. } => write_number(f, *value),
1273            Component::Percentage(v) => {
1274                write_number(f, *v)?;
1275                f.write_char('%')
1276            }
1277            Component::Dimension(v, u) => {
1278                write_number(f, *v)?;
1279                f.write_str(u.as_str())
1280            }
1281            Component::Math(m) => write!(f, "{m}"),
1282            Component::Color(c) => write!(f, "{c}"),
1283            Component::String(s) => write_string(f, s),
1284            Component::Url(u) => {
1285                f.write_str("url(")?;
1286                write_string(f, u)?;
1287                f.write_char(')')
1288            }
1289            Component::Literal(c) => f.write_char(*c),
1290            Component::Function { name, arguments } => {
1291                write!(f, "{name}(")?;
1292                write_components(f, arguments)?;
1293                f.write_char(')')
1294            }
1295            Component::Block(inside) => {
1296                f.write_char('[')?;
1297                write_components(f, inside)?;
1298                f.write_char(']')
1299            }
1300            Component::Parens(inside) => {
1301                f.write_char('(')?;
1302                write_components(f, inside)?;
1303                f.write_char(')')
1304            }
1305            Component::Tokens(t) => write_values(f, trim(t)),
1306        }
1307    }
1308}
1309
1310impl fmt::Display for Specified<'_> {
1311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1312        match self {
1313            Specified::CssWide(k) => f.write_str(k.as_str()),
1314            Specified::Unparsed(v) | Specified::Custom(v) => write_values(f, trim(v)),
1315            Specified::Value(c) => write_components(f, c),
1316        }
1317    }
1318}
1319
1320#[cfg(test)]
1321mod tests {
1322    use super::*;
1323
1324    fn written(property: &str, css: &str) -> Option<String> {
1325        let v = crate::parse_component_values(css);
1326        parse_value(property, &v).ok().map(|s| s.to_string())
1327    }
1328
1329    #[test]
1330    fn font_family_without_the_matcher() {
1331        let p = property("font-family").unwrap();
1332        let cases = [
1333            "a, b",
1334            "\"New Century Schoolbook\", serif",
1335            "Serif",
1336            "cursive serif",
1337            "x, inherit",
1338            "a b c, 'd'",
1339            "MONOSPACE, ui-serif",
1340            ",a",
1341            "a,",
1342            "\"a\" b",
1343            "default",
1344            "revert-rule",
1345            "\"serif\"",
1346            "Emoji",
1347        ];
1348        for css in cases {
1349            let v = crate::parse_component_values(css);
1350            let v = trim(&v);
1351            let fast = font_family(v).expect(css).map(|s| s.to_string());
1352            let slow = parse_matched(p, v).map(|s| s.to_string());
1353            assert_eq!(fast, slow, "{css}");
1354        }
1355    }
1356
1357    #[test]
1358    fn shortest_forms() {
1359        let cases = [
1360            ("display", "inline flex", "inline-flex"),
1361            ("display", "block flow list-item", "list-item"),
1362            ("white-space", "preserve nowrap", "pre"),
1363            ("flex", "1", "1 1 0%"),
1364            ("flex", "none", "0 0 auto"),
1365            ("place-items", "center center", "center"),
1366            ("margin", "1px 2px 1px 2px", "1px 2px"),
1367            ("font", "normal bold 12px/normal serif", "bold 12px serif"),
1368            ("text-decoration-line", "blink underline", "underline blink"),
1369            (
1370                "background-image",
1371                "linear-gradient(in srgb, red, blue)",
1372                "linear-gradient(red, blue)",
1373            ),
1374            (
1375                "color",
1376                "color-mix(in oklab, 25% red, blue)",
1377                "color-mix(red 25%, blue 75%)",
1378            ),
1379            ("font-family", "Monospace", "monospace"),
1380            ("grid-column-start", "span 2", "span 2"),
1381        ];
1382        for (p, css, want) in cases {
1383            assert_eq!(written(p, css).as_deref(), Some(want), "{p}: {css}");
1384        }
1385    }
1386
1387    #[test]
1388    fn what_every_property_takes() {
1389        assert_eq!(written("color", "INHERIT").as_deref(), Some("inherit"));
1390        assert_eq!(
1391            written("width", " var(--w,  10px) ").as_deref(),
1392            Some("var(--w, 10px)")
1393        );
1394        assert_eq!(written("--x", " { a } ").as_deref(), Some("{ a }"));
1395        assert_eq!(written("not-a-property", "1px"), None);
1396        assert_eq!(written("width", ""), None);
1397    }
1398
1399    #[test]
1400    fn shorthands_split() {
1401        let split = |p: &str, css: &str| -> Vec<String> {
1402            let v = crate::parse_component_values(css);
1403            expand(p, &v)
1404                .unwrap()
1405                .into_iter()
1406                .map(|(n, v)| format!("{n}: {v}"))
1407                .collect()
1408        };
1409        assert_eq!(
1410            split("border-color", "red blue"),
1411            [
1412                "border-top-color: red",
1413                "border-right-color: blue",
1414                "border-bottom-color: red",
1415                "border-left-color: blue"
1416            ]
1417        );
1418        assert_eq!(
1419            split("grid-column", "a"),
1420            ["grid-column-start: a", "grid-column-end: a"]
1421        );
1422        assert_eq!(split("gap", "1px"), ["row-gap: 1px", "column-gap: 1px"]);
1423        let border = split("border-top", "1px solid");
1424        assert_eq!(
1425            border,
1426            [
1427                "border-top-width: 1px",
1428                "border-top-style: solid",
1429                "border-top-color: currentcolor"
1430            ]
1431        );
1432        assert!(
1433            split("margin", "inherit")
1434                .iter()
1435                .all(|l| l.ends_with(": inherit"))
1436        );
1437    }
1438}