Repository navigation
CSS values
parsec_css::values is the CSS module's second part: what a declaration's value means. It knows every property in the CSS specs, 822 of them, and parses a value the way element.style[property] = value does in a browser: against the property's grammar, with its colors, lengths and math functions typed, and written back the way CSSOM writes it. Custom properties resolve against each other and var() substitutes into anything. It sits on top of the syntax parser on CSS, in the same crate, with no new dependencies.
What it doesn't do yet is cascade. Which declaration wins, media queries, and computed values with inheritance are #30; the pieces here are shaped for it, and where something needs it (inherit on a custom property, say) the page says so.
On this page: Using it · The property table · Parsing a value · Numbers, units and math · Colors · Shorthands · Custom properties and var() · Conformance · What fails, and why · Speed · Fuzzing · Next to Lexbor
use parsec_css::values::{expand, parse_value, property};
let p = property("border-top-width").unwrap();
assert_eq!((p.initial, p.inherited), (Some("medium"), Some(false)));
let v = parsec_css::parse_component_values("CALC(1in + 2px) AUTO");
assert_eq!(parse_value("margin", &v).unwrap().to_string(), "calc(98px) auto");
let v = parsec_css::parse_component_values("1px 2px");
let sides: Vec<String> = expand("margin", &v)
.unwrap()
.iter()
.map(|(name, value)| format!("{name}: {value}"))
.collect();
assert_eq!(sides, ["margin-top: 1px", "margin-right: 2px", "margin-bottom: 1px", "margin-left: 2px"]);For a declaration you already parsed, parse_declaration_value(&declaration) does the same with its name and value.
property(name) looks a property up, ignoring ASCII case; properties() gives all of them, sorted by name. Each is a PropertyData:
| Field | What it is |
|---|---|
name |
margin-top |
syntax |
The grammar, in the value definition syntax: <length-percentage> | auto | <anchor-size()>
|
initial |
The initial value as the spec writes it; prose for a shorthand ("see individual properties") |
inherited |
Some(true), Some(false), or None where the spec says something else |
longhands |
For a shorthand, the longhands it sets, in the spec's order |
alias_of |
For a legacy alias like -webkit-box-align, the property it names |
href |
Where the spec defines it |
grammar() gives the grammar parsed, and is_shorthand() says whether it has longhands.
The table is generated, not written by hand. @webref/css is the W3C's own scrape of every CSS spec's property definitions, kept so that every grammar in it parses; its css.json is pinned in crates/parsec-css/data/webref with its version (8.7.9, w3c/webref b6b1622) and MIT licence, and node scripts/properties.js turns it into src/values/generated.rs. Updating to new specs is: replace the JSON, run the script, run the tests.
That's 822 properties: 597 longhands, 161 shorthands and 64 legacy aliases. It's every property in the specs, which is more than any one browser ships; webref doesn't say which ship where, so nothing is filtered. cargo test checks that every grammar parses and that every longhand's initial value is a value of its own grammar; six aren't, and they're listed: four are prose (voice-family: implementation-dependent), and two (fill, text-spacing-trim) use types the data defines only in prose.
The types and functions those grammars refer to come from the same data: 530 types and 172 functions, each parsed once, the first time anything uses it.
parse_value(property, &values) returns a Specified:
| Variant | When |
|---|---|
Value(Vec<Component>) |
The value matched the grammar |
CssWide(CssWide) |
initial, inherit, unset, revert or revert-layer, which every property takes |
Unparsed(Vec<ComponentValue>) |
There's a var() or env() in it, so it can't be checked until substitution: kept as written, as the spec says |
Custom(Vec<ComponentValue>) |
A --custom property: any tokens, kept as written |
or InvalidValue if it doesn't match, or the property isn't one. Display writes it back as CSSOM serializes a specified value.
A Component is one typed value: Keyword (lowercase), Ident (a <custom-ident>, as written), Number { value, integer }, Percentage, Dimension(value, Unit), Math, Color, String, Url, Literal (, and /), Function { name, arguments }, Block and Parens for [ … ] and ( … ), and Tokens for the parts a grammar takes as <declaration-value>.
The matcher reads the grammar as Values 4 §2 writes it: juxtaposition, &&, ||, |, brackets, *, +, ?, {A,B}, #, #{A,B} and !, ranges like <length [0,∞]>, <'property'> references, functions, and literal , and /. It backtracks, so <length>{1,4} or a || b || c find a way through the input if there is one, and it leaves out a comma next to an optional term that matched nothing, which is how linear-gradient(red, blue) matches [ <angle> || … ]? , <color-stop-list>. A step budget (200,000 steps a value) keeps a hostile value from taking exponential time; past it, the value is invalid.
When it writes a value back:
- keywords are lowercase, numbers have six significant figures, units are lowercase, strings are in double quotes and
url()s quoted; - what matched a
||or&&group is written in the grammar's order, which is CSSOM's canonical order:text-decoration-line: blink underlineisunderline blink; - a box shorthand leaves out what repeats:
margin: 1px 2px 1px 2pxis1px 2px, and a pair likeplace-items: center centeriscenter; -
normalin a||group is left out, as the shortest serialization has it:font: normal bold 12px/normal serifisbold 12px serif; - gradients leave out their default interpolation (
in srgbwith legacy colors,in oklabotherwise) andshorter hue, writexyzasxyz-d65, and dropellipsebefore two sizes;color-mix()andpalette-mix()fill in or leave out their percentages as CSS Color 5 says; - a few properties have shortest forms of their own, written in:
display(inline flexisinline-flex,block flow list-itemislist-item),white-space(preserve nowrapispre), andflex(1is1 1 0%), andfirst baselineisbaseline.
A keyword the grammar has elsewhere is taken as that keyword, not as a <custom-ident>, where the value can be read that way (Values 4 §4.2): grid-column: span 2 is span and 2, not a line named span, and font-family: Monospace is the generic family monospace.
Other properties' own canonical forms, where browsers leave out or rewrite more (scale: 100% 100% as 1, rotate: 0 0 1 400grad as 400grad), aren't done; they're most of the serialization failures below.
Every unit in Values 4 and the specs it points to is a Unit: the font-relative ones (em, rem, ex, rex, cap, rcap, ch, rch, ic, ric, lh, rlh), the viewport ones in all four sizes (vw to vmax, then sv*, lv* and dv*), the container query ones (cqw to cqmax), the absolute lengths, angles, times, frequencies, resolutions and fr. Each knows its kind() and, for the absolute ones, its ratio to the canonical unit.
Math::parse(&function) parses a math function: calc(), min(), max(), clamp(), round() with its four strategies, mod(), rem(), sin(), cos(), tan(), asin(), acos(), atan(), atan2(), pow(), sqrt(), hypot(), log(), exp(), abs() and sign(), with e, pi, infinity, -infinity and NaN. + and - need whitespace around them, as the spec says.
The tree is simplified as §10.10 says: sums and products are flattened, values with the same unit added, numbers multiplied in, absolute units made canonical, and a function of values that can be worked out worked out. It's written as §10.12 says, children sorted (numbers, then percentages, then dimensions by unit):
| Written | Serialized |
|---|---|
calc(1px + 2px) |
calc(3px) |
calc(1in) |
calc(96px) |
calc(10px + 5%) |
calc(5% + 10px) |
calc(2 * (1em + 2px)) |
calc(2em + 4px) |
calc(50% + (sign(1em - 10px) * 10%)) |
calc(50% + (10% * sign(1em - 10px))) |
min(1em, 2px) |
min(1em, 2px) |
clamp(1px, 5px, 3px) |
calc(3px) |
atan2(1px, 1px) |
calc(45deg) |
fits(Expect) checks the function's type (§10.9) against where it's used: calc(10% + 1px) is a <length-percentage> but not a <length>, and sin(1px) isn't anything. Where the grammar asks for a number, a length or any other numeric type, a math function of that type matches it; one outside a range like [0,∞] is still valid, since the spec clamps it when it's used.
Nesting is limited to 32 functions or parentheses deep, as browsers limit it; deeper is invalid, not a stack overflow.
Color::parse(&value) reads a <color>: hex in all four lengths, the 148 named colors, transparent, currentcolor, the system colors (deprecated ones too), rgb() and rgba(), hsl() and hsla(), hwb(), lab(), lch(), oklab(), oklch(), and color() in srgb, srgb-linear, display-p3, display-p3-linear, a98-rgb, prophoto-rgb, rec2020, xyz, xyz-d50 and xyz-d65. From CSS Color 5, device-cmyk() and light-dark(). Every channel can be none (outside the legacy comma syntax) or a math function.
It's written as CSS Color 4 §15 and WPT have it:
| Written | Serialized |
|---|---|
#234 |
rgb(34, 51, 68) |
RebeccaPurple |
rebeccapurple (a specified value keeps the name) |
hsl(120 30% 50%) |
rgb(89, 166, 89) |
rgba(2, 3, 4, 50%) |
rgba(2, 3, 4, 0.5) |
hsl(120 30 none / 0.5) |
hsl(120 30% none / 0.5) |
rgb(128 none none) |
color(srgb 0.501961 none none) |
lab(400 0 10/50%) |
lab(100 0 10 / 0.5) (lightness clamped when parsed) |
lch(0 150 -10) |
lch(0 150 350) |
color(xyz 10% 10% 10%) |
color(xyz-d65 0.1 0.1 0.1) |
lab(calc(50 * 3) 0 0) |
lab(calc(150) 0 0) (math kept, unclamped) |
From CSS Color 5, too: relative colors (rgb(from <color> r g calc(b / 2)), in every function and alpha(from …)), with the origin's channel names allowed in the channels and in math, color-mix(), contrast-color() and color-layers(). A relative color is kept as written, its origin serialized, since what r is depends on the origin's computed value; a mix is kept the same way, with its defaults left out.
| Written | Serialized |
|---|---|
rgba(from rgb(20%, 40%, 60%, 80%) r g 25 / 25%) |
rgb(from rgba(51, 102, 153, 0.8) r g 25 / 25%) |
rgb(from rebeccapurple r calc(g * .5 + g * .5) 10) |
rgb(from rebeccapurple r calc((0.5 * g) + (0.5 * g)) 10) |
color-mix(in oklab, 25% red, blue) |
color-mix(red 25%, blue 75%) |
color-mix(in hsl shorter hue, red 50%, blue) |
color-mix(in hsl, red, blue) |
computed() gives a named color as rgb(), as a computed value has it. Converting between spaces, and working out relative colors and mixes, is computed-value work for #30.
expand(shorthand, &values) parses a shorthand's value and returns a value for each of its longhands, in the spec's order. A longhand the value leaves out gets its initial value; a CSS-wide keyword, or a value with var() in it, goes to every longhand. For a longhand, it returns that longhand alone.
The split comes from the grammar. Where a shorthand's grammar refers to its longhands (<'margin-top'>{1,4}, <'row-gap'> <'column-gap'>?, [ <'font-style'> || … ] <'font-size'> …), each part goes to the longhand it matched, with the box rules for one to four sides and "the second, left out, is the first" for pairs like gap. Where it doesn't (border: <line-width> || <line-style> || <color>), each part goes to every longhand that takes it, so border: 1px solid red sets all four widths, styles and colors. Where the grammar is positions rather than longhands, those rules apply too: one to four values over the sides (border-color: red blue), and two separated by / (grid-column: 1 / 3, where a second left out is the first if that's a name). Where none of that works, expand says the value is invalid rather than guess; 93 of WPT's 394 shorthand cases end there today, most of them the repeat() lists of CSS Gaps' column-rule.
CustomProperties holds an element's custom properties as declared: declare("--gap", values). resolve(parent) resolves them all at once:
- every
var()in them is substituted, fallbacks included; - a cycle (
--a: var(--b); --b: var(--a), or through a fallback, or of one property on itself) makes every property in it the guaranteed-invalid value; one that only refers to a cycle takes its fallback, or is invalid itself; -
initialis the guaranteed-invalid value, and what isn't declared comes fromparent, since custom properties inherit.
It finds cycles with Tarjan's algorithm, written without recursion, so a chain of 50,000 properties referring each to the next resolves (there's a test). Substitution can grow a value exponentially, ten var(--a)s of ten var(--b)s and so on; past 100,000 component values a value is invalid, as the spec lets a browser decide, so a hostile stylesheet can't make it allocate without bound.
substitute(&values, &resolved) replaces the var()s in any value, and substitute_value(property, &values, &resolved) does that and parses the result for the property: an error there is "invalid at computed-value time", which the cascade will turn into unset. Tokens substituted stay the tokens they were, so var(--n)px with --n: 1 is a number and an ident, never 1px.
use parsec_css::values::{CustomProperties, substitute_value};
let mut props = CustomProperties::new();
props.declare("--gap", parsec_css::parse_component_values("4px"));
props.declare("--a", parsec_css::parse_component_values("var(--b)"));
props.declare("--b", parsec_css::parse_component_values("var(--a)"));
let resolved = props.resolve(None);
let v = parsec_css::parse_component_values("calc(var(--gap) * 2) var(--a, auto)");
assert_eq!(substitute_value("margin", &v, &resolved).unwrap().to_string(), "calc(8px) auto");env() isn't substituted: no environment is given, so a value with one is invalid after substitution. attr() and registered custom properties (@property) aren't done.
Two suites run in cargo test for values, both pinned with their commit and licence, and in each CI run's conformance summary.
| Suite | Data | Passed | Failed |
|---|---|---|---|
css-parsing-tests' color_* files |
tests/css-parsing-tests, at 203ce36
|
4,803 | 3,258, each checked against a change to CSS Color |
| web-platform-tests' CSS parsing tests |
tests/wpt-values, at 1a2a0c5
|
13,899 | 994, listed |
css-parsing-tests: 5096 passed, 3270 failed, 0 skipped
6 color cases fail because custom color spaces need @color-profile, which isn't parsed yet
4 color cases fail because light-dark() is a pair of colors in the suite, and a color here
2760 color cases fail because the draft now clamps lightness and chroma when parsing them
488 color cases fail because the draft now writes a legacy color with `none` in its own function
wpt css parsing: 13899 passed, 994 failed, 129 skipped
invalid: 4920 passed, 150 failed
shorthand: 219 passed, 175 failed
valid: 8760 passed, 669 failed
(The css-parsing-tests line counts the syntax cases on CSS too: 293 passed and 12 failed of them.)
css-parsing-tests' color files were skipped until now. They're compared as computed colors, which is what the suite records, and with one allowance for precision, which CSS Color 4 leaves to the implementation: legacy rgb() channels are compared to within rounding to integers, and their alpha to three decimals, where the suite keeps six. Every failure is checked by color_difference in the runner against one of four ways CSS Color has moved since the suite was written, and counted under it; one that isn't explained that way fails the run. The big one is clamping: the suite keeps lab(110 0 0) as written, and the current draft, and WPT, clamp it to lab(100 0 0) when it's parsed, so for those 2,760 the runner clamps the suite's answer and checks it then matches.
WPT's CSS parsing tests are the ones every browser runs: css/*/parsing/*.html, which call test_valid_value(property, value, serialized), test_invalid_value(property, value) and test_shorthand_value(shorthand, value, longhands). They're JavaScript, so scripts/wpt-values-cases.js runs each file's scripts in a Node sandbox with no DOM, where those helpers record what the test expects instead of setting a style; the same approach as Netweir's selector tests. Anything else a file does throws there and is counted as skipped, with why: 442 files have nothing static to check, most of them computed-value tests, which are #30's. 777 files give 14,893 cases, in tests/wpt-values/cases.json.
A valid case passes when the value parses for the property, writes back exactly as the test expects (or as one of the forms it allows), and what it wrote parses back to itself, which the test checks too. Colors that WPT compares with a tolerance are compared to within 0.01, as it does. An invalid case passes when the value doesn't parse; a shorthand case when each longhand it names comes out as expected.
Every case that fails today is in tests/wpt-values/known-failures.txt, one JSON array a line. The run fails if anything else fails, or if a listed case starts to pass, so the list only shrinks. UPDATE_KNOWN_FAILURES=1 cargo test -p parsec-html-css --test wpt_values rewrites it, and scripts/fetch-wpt-values.sh COMMIT moves the suite to another commit.
To run them with the counts showing:
cargo test -p parsec-html-css -- --nocaptureThe 994 WPT failures, by kind:
| Cases | What | Why |
|---|---|---|
| 508 | Valid values that parse, but are written differently | A property's own canonical form that isn't done: mask and grid-template leaving out defaults, scale: 100% 100% as 1, rotate: 0 0 1 400grad as 400grad, transform: scale(50%) as scale(0.5), skew(0) as skew(0deg); and 48 colors, mostly color-layers() and a relative color whose origin is a mix. Each is a rule of that property's, not of the grammar |
| 161 | Valid values rejected | The data's grammar is behind the spec: animation-range's cover 0%, line-clamp, font-synthesis's oblique-only, text-spacing; or a type the data defines only in prose |
| 150 | Invalid values accepted | Rules the specs write in prose, not in the grammar: will-change refusing its own name and auto in a list, content's counters refusing none, color-scheme's only and normal alone, font-language-override's four letters, grid lines refusing span as a name |
| 93 | Shorthands not split | The grammar doesn't show which part goes to which longhand (CSS Gaps' repeat() lists in column-rule, border-radius's slashes, background layers), and expand won't guess |
| 82 | Shorthands split with a longhand that differs | A property's own rule for a left-out value: CSS Gaps' rule-inset and the like, flex, border-image
|
Nothing in that list is a crash, a hang or a case the runner skips; every one is a case it ran and got a different answer for.
Timed in bench/, which also times the syntax parser (see CSS and Benchmarks): the same ten real stylesheets, parsed with parse_stylesheet_deep and then every declaration's value parsed for its property, against Lexbor's lxb_css_stylesheet_parse, which types the values of the 105 properties it knows as it parses.
| All ten, MB/s | Parsec | Lexbor 3.0.1 | Parsec vs Lexbor |
|---|---|---|---|
| Parse, every value typed | 120 | 116 | 1.04× |
That's the second of two runs on 18 November 2026, each started with the one-minute load under 2.4; the first gave 124 to 113, 1.10 times. It's 33,155 declaration values, every one typed for its property. Sheet by sheet it's a mix, from 0.70 times Lexbor's speed (the New York Times' and Wikipedia's <style> elements, where most declarations are short and Parsec's per-value matching costs more than the parse) to 1.17 times (Bulma) in this run, 1.34 in the first.
It isn't quite the same work. Lexbor types the 105 properties it knows and keeps the rest as text; Parsec types all 822, custom properties kept as tokens, so where a sheet uses properties Lexbor doesn't know, Parsec is doing more. Lexbor's parse also reads every selector, which Parsec's doesn't. Getting here took profiling with sample: a property's grammar, its types and its references are looked up once and cached in the grammar, property names go through a hash table, and a value with no whitespace in it is matched where it lies, without copying.
The parse fuzz target in crates/parsec-css/fuzz now also types every declaration's value for its property, writes it, parses what it wrote, splits every shorthand, and resolves the custom properties of whatever it generated against each other, then substitutes them. It ran clean for five minutes twice locally, 1.1 million inputs and then 600,000 on the final code.
cd crates/parsec-css
cargo +nightly fuzz run parse -- -max_len=4096| Lexbor 3.0.1 | Parsec | |
|---|---|---|
| Typed properties | 105 | All 822 in the specs, from their grammars |
| Where the property list comes from | Hand-written | Generated from w3c/webref's scrape of the specs |
var() and custom properties |
No (lexbor#232) | Yes: resolved, cycles found, substituted anywhere |
| Math functions | No: no calc()
|
calc() and all of Values 4's, simplified |
| CSS Color 4 and 5 | Color 4's functions, rgb() to color()
|
All of Color 4, with none and math in any channel; from Color 5, relative colors, color-mix(), contrast-color(), light-dark(), device-cmyk()
|
| Shorthands into longhands | For the ones it knows | From the grammar, where it shows how |
| Outside suite | No | css-parsing-tests' colors and WPT's parsing tests, counts published |
| Cascade, media queries, computed values | No | Not yet (#30) |
- CSS, for the syntax parser this sits on.
- Conformance, for every suite Parsec runs.
- Benchmarks, for the method behind the speed numbers.
Parsec is Apache-2.0 and not yet released; these pages describe main. Found something wrong here? Open an issue or ask in Discussions.
Repository · Issues · Discussions · Roadmap · Security policy · Licence