Skip to main content

rust_css_parser/syntax/
syntax.rs

1//! Port of `src/syntax/syntax.ts`.
2
3use crate::ast::arena::{AstArena, TokenField, TokenValue};
4use crate::ast::strings::StringFlag;
5use crate::ast::types::{ColorType, EnumToken, WalkerOptionEnum};
6use crate::ast::walk::{ValueWalker, WalkerValueOptions, WalkerValueResult};
7use crate::parser::utils::angle::to_degrees;
8use crate::parser::utils::text::{equals_ignore_case, lowercase};
9use crate::syntax::color::utils::colorspace::get_color_space;
10use crate::syntax::color::utils::components::get_color_components;
11use crate::syntax::color::utils::distance::is_ok_lab_close;
12use crate::syntax::constants::{
13    anglePrecision, colorPrecision, color_name_to_hex, epsilon, non_standard_colors, validation_units, COLORS_FUNC,
14    COLOR_FUNC_COLOR_SPACE, DEPRECATED_SYSTEM_COLORS, SYSTEM_COLORS,
15};
16use crate::types::ErrorDescription;
17use crate::utils::number::{js_number_to_string, js_round};
18use crate::validation::match_::trim_array;
19use crate::validation::utils::list::split_token_list_comma;
20use std::cell::RefCell;
21use crate::utils::fx::HashMap;
22
23const REVERSE_SOLIDUS: u32 = 0x5c;
24
25pub const FLEX_UNITS: [&str; 1] = ["fr"];
26pub const FREQUENCY_UNITS: [&str; 2] = ["Hz", "kHz"];
27pub const TIME_UNITS: [&str; 2] = ["ms", "s"];
28pub const ANGLE_UNITS: [&str; 4] = ["rad", "turn", "deg", "grad"];
29pub const RESOLUTION_UNITS: [&str; 4] = ["dpi", "dpcm", "dppx", "x"];
30pub const DIMENSION_UNITS: [&str; 49] = ["cap", "ch", "cm", "cqb", "cqh", "cqi", "cqmax", "cqmin", "cqw", "dvb", "dvh", "dvi", "dvmax", "dvmin", "dvw", "em", "ex", "ic", "in", "lh", "lvb", "lvh", "lvi", "lvmax", "lvmin", "lvw", "mm", "pc", "pt", "px", "Q", "rcap", "rch", "rem", "rex", "ric", "rlh", "svb", "svh", "svi", "svmax", "svmin", "svw", "vb", "vh", "vi", "vmax", "vmin", "vw"];
31
32/// `pseudoAliasMap`
33pub fn pseudo_alias_map(name: &str) -> Option<&'static str> {
34    match name {
35        "-moz-center" => Some("center"),
36        "-webkit-center" => Some("center"),
37        "-ms-grid-columns" => Some("grid-template-columns"),
38        "-ms-grid-rows" => Some("grid-template-rows"),
39        "-ms-grid-row" => Some("grid-row-start"),
40        "-ms-grid-column" => Some("grid-column-start"),
41        "-ms-grid-row-align" => Some("align-self"),
42        "-ms-grid-row-span" => Some("grid-row-end"),
43        "-ms-grid-column-span" => Some("grid-column-end"),
44        "-ms-grid-column-align" => Some("justify-self"),
45        ":-ms-input-placeholder" => Some("::placeholder"),
46        "::-ms-input-placeholder" => Some("::placeholder"),
47        ":-moz-any()" => Some(":is"),
48        "-moz-user-modify" => Some("user-modify"),
49        "-webkit-match-parent" => Some("match-parent"),
50        "-moz-background-clip" => Some("background-clip"),
51        "-moz-background-origin" => Some("background-origin"),
52        "-ms-input-placeholder" => Some("placeholder"),
53        ":-webkit-autofill" => Some(":autofill"),
54        ":-webkit-any()" => Some(":is"),
55        "::-webkit-input-placeholder" => Some("::placeholder"),
56        "::-webkit-file-upload-button" => Some("::file-selector-button"),
57        "::-moz-placeholder" => Some("::placeholder"),
58        ":-webkit-any-link" => Some(":any-link"),
59        "-webkit-border-after" => Some("border-block-end"),
60        "-webkit-border-after-color" => Some("border-block-end-color"),
61        "-webkit-border-after-style" => Some("border-block-end-style"),
62        "-webkit-border-after-width" => Some("border-block-end-width"),
63        "-webkit-border-before" => Some("border-block-start"),
64        "-webkit-border-before-color" => Some("border-block-start-color"),
65        "-webkit-border-before-style" => Some("border-block-start-style"),
66        "-webkit-border-before-width" => Some("border-block-start-width"),
67        "-webkit-border-end" => Some("border-inline-end"),
68        "-webkit-border-end-color" => Some("border-inline-end-color"),
69        "-webkit-border-end-style" => Some("border-inline-end-style"),
70        "-webkit-border-end-width" => Some("border-inline-end-width"),
71        "-webkit-border-start" => Some("border-inline-start"),
72        "-webkit-border-start-color" => Some("border-inline-start-color"),
73        "-webkit-border-start-style" => Some("border-inline-start-style"),
74        "-webkit-border-start-width" => Some("border-inline-start-width"),
75        "-webkit-box-align" => Some("align-items"),
76        "-webkit-box-direction" => Some("flex-direction"),
77        "-webkit-box-flex" => Some("flex-grow"),
78        "-webkit-box-lines" => Some("flex-flow"),
79        "-webkit-box-ordinal-group" => Some("order"),
80        "-webkit-box-orient" => Some("flex-direction"),
81        "-webkit-box-pack" => Some("justify-content"),
82        "-webkit-column-break-after" => Some("break-after"),
83        "-webkit-column-break-before" => Some("break-before"),
84        "-webkit-column-break-inside" => Some("break-inside"),
85        "-webkit-font-feature-settings" => Some("font-feature-settings"),
86        "-webkit-hyphenate-character" => Some("hyphenate-character"),
87        "-webkit-initial-letter" => Some("initial-letter"),
88        "-webkit-margin-end" => Some("margin-block-end"),
89        "-webkit-margin-start" => Some("margin-block-start"),
90        "-webkit-padding-after" => Some("padding-block-end"),
91        "-webkit-padding-before" => Some("padding-block-start"),
92        "-webkit-padding-end" => Some("padding-inline-end"),
93        "-webkit-padding-start" => Some("padding-inline-start"),
94        "-webkit-min-device-pixel-ratio" => Some("min-resolution"),
95        "-webkit-max-device-pixel-ratio" => Some("max-resolution"),
96        "-webkit-font-smoothing" => Some("font-smooth"),
97        "-webkit-line-clamp" => Some("line-clamp"),
98        ":-webkit-autofill-strong-password" => Some(":autofill"),
99        ":-webkit-full-page-media" => Some(":fullscreen"),
100        ":-webkit-full-screen" => Some(":fullscreen"),
101        ":-webkit-full-screen-ancestor" => Some(":fullscreen"),
102        ":-webkit-full-screen-document" => Some(":fullscreen"),
103        ":-webkit-full-screen-controls-hidden" => Some(":fullscreen"),
104        "-moz-background-inline-policy" => Some("box-decoration-break"),
105        "-moz-background-size" => Some("background-size"),
106        "-moz-border-end" => Some("border-inline-end"),
107        "-moz-border-end-color" => Some("border-inline-end-color"),
108        "-moz-border-end-style" => Some("border-inline-end-style"),
109        "-moz-border-end-width" => Some("border-inline-end-width"),
110        "-moz-border-image" => Some("border-inline-end-width"),
111        "-moz-border-start" => Some("border-inline-start"),
112        "-moz-border-start-color" => Some("border-inline-start-color"),
113        "-moz-border-start-style" => Some("border-inline-start-style"),
114        "-moz-border-start-width" => Some("border-inline-start-width"),
115        "-moz-column-count" => Some("column-count"),
116        "-moz-column-fill" => Some("column-fill"),
117        "-moz-column-gap" => Some("column-gap"),
118        "-moz-column-width" => Some("column-width"),
119        "-moz-column-rule" => Some("column-rule"),
120        "-moz-column-rule-width" => Some("column-rule-width"),
121        "-moz-column-rule-style" => Some("column-rule-style"),
122        "-moz-column-rule-color" => Some("column-rule-color"),
123        "-moz-margin-end" => Some("margin-inline-end"),
124        "-moz-margin-start" => Some("margin-inline-start"),
125        "-moz-opacity" => Some("opacity"),
126        "-moz-outline" => Some("outline"),
127        "-moz-outline-color" => Some("outline-color"),
128        "-moz-outline-offset" => Some("outline-offset"),
129        "-moz-outline-style" => Some("outline-style"),
130        "-moz-outline-width" => Some("outline-width"),
131        "-moz-padding-end" => Some("padding-inline-end"),
132        "-moz-padding-start" => Some("padding-inline-start"),
133        "-moz-tab-size" => Some("tab-size"),
134        "-moz-text-align-last" => Some("text-align-last"),
135        "-moz-text-decoration-color" => Some("text-decoration-color"),
136        "-moz-text-decoration-line" => Some("text-decoration-line"),
137        "-moz-text-decoration-style" => Some("text-decoration-style"),
138        "-moz-transition" => Some("transition"),
139        "-moz-transition-delay" => Some("transition-delay"),
140        "-moz-transition-duration" => Some("transition-duration"),
141        "-moz-transition-property" => Some("transition-property"),
142        "-moz-transition-timing-function" => Some("transition-timing-function"),
143        "-moz-user-select" => Some("user-select"),
144        "-moz-initial" => Some("initial"),
145        "-moz-linear-gradient()" => Some("linear-gradient"),
146        "-moz-radial-gradient()" => Some("radial-gradient"),
147        "-moz-element()" => Some("element"),
148        "-moz-crisp-edges" => Some("crisp-edges"),
149        "-moz-calc()" => Some("calc"),
150        "-moz-min-content" => Some("min-content"),
151        "-moz-fit-content" => Some("fit-content"),
152        "-moz-max-content" => Some("max-content"),
153        "-moz-available" => Some("stretch"),
154        ":-moz-any-link" => Some(":any-link"),
155        ":-moz-full-screen" => Some(":fullscreen"),
156        ":-moz-full-screen-ancestor" => Some(":fullscreen"),
157        ":-moz-placeholder" => Some(":placeholder-shown"),
158        ":-moz-read-only" => Some(":read-only"),
159        ":-moz-read-write" => Some(":read-write"),
160        ":-moz-submit-invalid" => Some(":invalid"),
161        ":-moz-ui-invalid" => Some(":user-invalid"),
162        ":-moz-ui-valid" => Some(":user-valid"),
163        "::-moz-selection" => Some("::selection"),
164        _ => None,
165    }
166}
167
168/// `renamedStandardProperties`
169pub fn renamed_standard_properties(name: &str) -> Option<&'static str> {
170    match name {
171        "color-adjust" => Some("print-color-adjust"),
172        "font-stretch" => Some("font-width"),
173        "grid-column-gap" => Some("column-gap"),
174        "grid-gap" => Some("gap"),
175        "grid-row-gap" => Some("row-gap"),
176        "word-wrap" => Some("overflow-wrap"),
177        _ => None,
178    }
179}
180
181fn unit_in(units: &[&str], unit: &str) -> bool {
182    units.iter().any(|u| u.eq_ignore_ascii_case(unit))
183}
184
185pub fn is_length_unit(unit: &str) -> bool {
186    unit_in(&DIMENSION_UNITS, unit)
187}
188
189pub fn is_resolution_unit(unit: &str) -> bool {
190    unit_in(&RESOLUTION_UNITS, unit)
191}
192
193pub fn is_angle_unit(unit: &str) -> bool {
194    unit_in(&ANGLE_UNITS, unit)
195}
196
197pub fn is_time_unit(unit: &str) -> bool {
198    unit_in(&TIME_UNITS, unit)
199}
200
201pub fn is_frequency_unit(unit: &str) -> bool {
202    unit_in(&FREQUENCY_UNITS, unit)
203}
204
205pub fn is_flex_unit(unit: &str) -> bool {
206    unit_in(&FLEX_UNITS, unit)
207}
208
209fn unit_test(arena: &AstArena, dimension: u32, test: fn(&str) -> bool) -> bool {
210    arena.unit.get(dimension) != 0 && arena.with_string(arena.unit.get(dimension), test)
211}
212
213pub fn is_length(arena: &AstArena, dimension: u32) -> bool {
214    unit_test(arena, dimension, is_length_unit)
215}
216
217pub fn is_resolution(arena: &AstArena, dimension: u32) -> bool {
218    unit_test(arena, dimension, is_resolution_unit)
219}
220
221pub fn is_angle(arena: &AstArena, dimension: u32) -> bool {
222    unit_test(arena, dimension, is_angle_unit)
223}
224
225pub fn is_time(arena: &AstArena, dimension: u32) -> bool {
226    unit_test(arena, dimension, is_time_unit)
227}
228
229pub fn is_frequency(arena: &AstArena, dimension: u32) -> bool {
230    unit_test(arena, dimension, is_frequency_unit)
231}
232
233pub fn is_flex(arena: &AstArena, dimension: u32) -> bool {
234    unit_test(arena, dimension, is_flex_unit)
235}
236
237fn rebuild_stops(arena: &AstArena, stops: &mut Vec<u32>, parts: &[Vec<u32>]) {
238    stops.clear();
239    for part in parts {
240        if !stops.is_empty() {
241            stops.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
242        }
243        stops.extend_from_slice(part);
244    }
245}
246
247/// reduce color stops
248pub fn reduce_color_stops(arena: &AstArena, stops: &mut Vec<u32>) {
249    let mut parts = split_token_list_comma(arena, stops);
250    let n = if parts.len() == 1 { 1.0 } else { (parts.len() - 1) as f64 };
251    let mut k: f64 = -1.0;
252    let mut updated = false;
253    let mut i: isize = 0;
254    while (i as usize) < parts.len() {
255        let iu = i as usize;
256        k += 1.0;
257        if parts[iu].len() != 3 {
258            i += 1;
259            continue;
260        }
261        if iu > 0 && is_ok_lab_close(arena, parts[iu - 1][0], parts[iu][0]) {
262            if parts[iu - 1].len() == 1 {
263                let ws = arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None);
264                let pc = arena.create_token(EnumToken::PercentageTokenType, TokenValue::Num(((k - 1.0) * 100.0) / n), None);
265                parts[iu - 1].push(ws);
266                parts[iu - 1].push(pc);
267            }
268            let tail: Vec<u32> = parts[iu][1..].to_vec();
269            parts[iu - 1].extend(tail);
270            parts.remove(iu);
271            updated = true;
272            continue;
273        }
274        for j in 0..parts[iu].len() {
275            let t = parts[iu][j];
276            let typ = arena.data_types.get(t);
277            if (typ == EnumToken::LengthTokenType && arena.numeric_value.get(t) == 0.0)
278                || typ == EnumToken::NumberTokenType
279                || typ == EnumToken::PercentageTokenType
280            {
281                if arena.numeric_value.get(t) == (k * 100.0) / n {
282                    parts[iu].truncate(j);
283                    trim_array(arena, &mut parts[iu]);
284                    updated = true;
285                    break;
286                }
287            }
288        }
289        i += 1;
290    }
291    if updated {
292        rebuild_stops(arena, stops, &parts);
293    }
294}
295
296/// reduce background-position values
297pub fn reducegradient_background_position(arena: &AstArena, positions: &mut Vec<u32>, position: &str) {
298    let pc = |v: f64| arena.create_token(EnumToken::PercentageTokenType, TokenValue::Num(v), None);
299    let ws = || arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None);
300    let iden = |v: &str| arena.create_token(EnumToken::IdenTokenType, TokenValue::Str(v), None);
301    let replace: Option<Vec<u32>> = match position {
302        "50%" | "50% 50%" | "center" | "center center" => Some(vec![]),
303        "0% 50%" | "0 50%" | "left" | "left center" | "center left" => Some(vec![pc(0.0)]),
304        "50% 0%" | "50% 0" | "top center" | "center top" => Some(vec![iden("top")]),
305        "bottom center" | "center bottom" | "bottom" | "50% 100%" => Some(vec![iden("bottom")]),
306        "right center" | "center right" | "100% 50%" | "right" => Some(vec![pc(100.0)]),
307        "bottom left" | "left bottom" => Some(vec![pc(0.0), ws(), pc(100.0)]),
308        "bottom right" | "right bottom" => Some(vec![pc(100.0), ws(), pc(100.0)]),
309        "top left" | "left top" => Some(vec![pc(0.0), ws(), pc(0.0)]),
310        "top right" | "right top" => Some(vec![pc(100.0), ws(), pc(0.0)]),
311        _ => None,
312    };
313    if let Some(replace) = replace {
314        *positions = replace;
315    }
316}
317
318/// reduce conic-gradient color stops
319pub fn reduce_conic_color_stops(arena: &AstArena, stops: &mut Vec<u32>) {
320    let mut parts = split_token_list_comma(arena, stops);
321    let n = if parts.len() == 1 { 1.0 } else { (parts.len() - 1) as f64 };
322    let mut k: f64 = -1.0;
323    let mut updated = false;
324    let mut i: usize = 0;
325    while i < parts.len() {
326        k += 1.0;
327        if parts[i].len() != 3 {
328            i += 1;
329            continue;
330        }
331        if i > 0 && is_ok_lab_close(arena, parts[i - 1][0], parts[i][0]) {
332            if parts[i - 1].len() == 1 {
333                let ws = arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None);
334                let an = arena.create_token(EnumToken::AngleTokenType, TokenValue::Num(((k - 1.0) * 100.0) / n), Some("deg"));
335                parts[i - 1].push(ws);
336                parts[i - 1].push(an);
337            }
338            let tail: Vec<u32> = parts[i][1..].to_vec();
339            parts[i - 1].extend(tail);
340            parts.remove(i);
341            updated = true;
342            continue;
343        }
344        for j in 0..parts[i].len() {
345            let t = parts[i][j];
346            let typ = arena.data_types.get(t);
347            if (typ == EnumToken::NumberTokenType && arena.numeric_value.get(t) == 0.0) || typ == EnumToken::AngleTokenType {
348                if arena.numeric_value.get(to_degrees(arena, t)) == (k * 360.0) / n {
349                    parts[i].truncate(j);
350                    trim_array(arena, &mut parts[i]);
351                    updated = true;
352                    break;
353                }
354            }
355        }
356        i += 1;
357    }
358    if updated {
359        rebuild_stops(arena, stops, &parts);
360    }
361}
362
363/// is rectangular orthogonal colorspace
364pub fn is_rectangular_orthogonal_colorspace(arena: &AstArena, token: u32) -> bool {
365    arena.data_types.get(token) == EnumToken::IdenTokenType
366        && arena.with_string(arena.string_value.get(token), |v| COLOR_FUNC_COLOR_SPACE.iter().any(|t| equals_ignore_case(t, v)))
367}
368
369/// is polar colorspace
370pub fn is_polar_colorspace(arena: &AstArena, token: u32) -> bool {
371    arena.data_types.get(token) == EnumToken::IdenTokenType
372        && arena.with_string(arena.string_value.get(token), |v| ["hsl", "hwb", "lch", "oklch"].iter().any(|t| equals_ignore_case(t, v)))
373}
374
375/// is ident color
376pub fn is_ident_color(arena: &AstArena, token: u32) -> bool {
377    let kin = arena.color_type.get(token);
378    arena.data_types.get(token) == EnumToken::ColorTokenType
379        && kin != ColorType::NONE
380        && [ColorType::SYS, ColorType::DPSYS, ColorType::LIT].contains(&kin)
381        && arena.with_string(arena.string_value.get(token), is_ident)
382}
383
384/// true if the identifier is a color: a system color, a named color, `currentcolor` or `transparent`
385pub fn is_color_name(str: &str) -> bool {
386    let val = lowercase(str);
387    let val: &str = &val;
388    if SYSTEM_COLORS.contains(&val) || DEPRECATED_SYSTEM_COLORS.contains(&val) || non_standard_colors().contains(val) {
389        return true;
390    }
391    color_name_to_hex(val).is_some() || val == "currentcolor" || val == "transparent"
392}
393
394/// color function arguments of the given types
395fn filter_children(arena: &AstArena, token: u32, types: &[u8]) -> Vec<u32> {
396    arena.token_iter(token).filter(|&t| types.contains(&arena.data_types.get(t))).collect()
397}
398
399const COLOR_KEYWORDS: [&str; 9] = ["in", "hue", "from", "alpha", "none", "shorter", "longer", "increasing", "decreasing"];
400
401/// `typeof Math[val.toUpperCase()] === "number"`: the `Math` constants
402fn is_math_constant(val: &str) -> bool {
403    matches!(val.to_uppercase().as_str(), "E" | "LN10" | "LN2" | "LOG10E" | "LOG2E" | "PI" | "SQRT1_2" | "SQRT2")
404}
405
406/// `color_space` is a string of channel names (one character each)
407/// `ColorType[name.replace('-', '_').toUpperCase()]`: the name is converted in a buffer on the stack
408fn color_type_of(name: &str) -> u8 {
409    let mut buffer = [0u8; 32];
410    if name.len() > buffer.len() || !name.is_ascii() {
411        return ColorType::value(&name.replace('-', "_").to_uppercase()).unwrap_or(0);
412    }
413    for (i, b) in name.bytes().enumerate() {
414        buffer[i] = if b == b'-' { b'_' } else { b.to_ascii_uppercase() };
415    }
416    // SAFETY: ascii
417    ColorType::value(unsafe { std::str::from_utf8_unchecked(&buffer[..name.len()]) }).unwrap_or(0)
418}
419
420fn unexpected_constant(val: &str, color_space: &str) -> bool {
421    !is_math_constant(val)
422        && !COLOR_KEYWORDS.contains(&val)
423        && !COLORS_FUNC.contains(&val)
424        && !(val.chars().count() == 1 && color_space.contains(val))
425        && !COLOR_FUNC_COLOR_SPACE.contains(&val)
426}
427
428fn push_error(errors: &mut Option<&mut Vec<ErrorDescription>>, message: String, node: u32) {
429    if let Some(errors) = errors.as_deref_mut() {
430        errors.push(ErrorDescription::drop(message).with_node(node));
431    }
432}
433
434/// is a color
435pub fn is_color(arena: &AstArena, token: u32, mut errors: Option<&mut Vec<ErrorDescription>>) -> bool {
436    let typ = arena.data_types.get(token);
437    if typ == EnumToken::WildCardFunctionTokenType {
438        return true;
439    }
440    if typ == EnumToken::ColorTokenType && arena.color_type.get(token) != ColorType::NONE && arena.first_token.get(token) == 0 {
441        return true;
442    }
443    if typ == EnumToken::IdenTokenType {
444        return arena.string_flag(arena.string_value.get(token), StringFlag::Color, is_color_name);
445    }
446    if (typ == EnumToken::FunctionTokenType || typ == EnumToken::ColorTokenType) && arena.first_token.get(token) != 0 {
447        let name = arena.resolve_string(arena.string_value.get(token));
448        if &*name == "light-dark" {
449            let children = filter_children(
450                arena,
451                token,
452                &[
453                    EnumToken::IdenTokenType,
454                    EnumToken::NumberTokenType,
455                    EnumToken::LiteralTokenType,
456                    EnumToken::ColorTokenType,
457                    EnumToken::FunctionTokenType,
458                    EnumToken::PercentageTokenType,
459                    EnumToken::WildCardFunctionTokenType,
460                ],
461            );
462            if children.len() != 2 {
463                push_error(&mut errors, "light-dark function must have 2 arguments".into(), token);
464                return false;
465            }
466            if is_color(arena, children[0], None) && is_color(arena, children[1], None) {
467                return true;
468            }
469        }
470        if let Some(components) = get_color_components(arena, token) {
471            if let Some(color_space) = get_color_space(arena, token) {
472                for &value in &components {
473                    if arena.data_types.get(value) == EnumToken::IdenTokenType {
474                        let val = arena.resolve_string(arena.string_value.get(value)).to_lowercase();
475                        if unexpected_constant(&val, &color_space) {
476                            push_error(&mut errors, format!("Unexpected constant '{}'", val), value);
477                            return false;
478                        }
479                    } else if arena.data_types.get(value) == EnumToken::MathFunctionTokenType
480                        && arena.with_string(arena.string_value.get(value), |n| equals_ignore_case("calc", n))
481                    {
482                        let tokens = arena.tokens(value);
483                        let mut walker = ValueWalker::of_tokens(&tokens, WalkerValueOptions::default(), false);
484                        while let Some(v) = walker.next(arena) {
485                            if arena.data_types.get(v) == EnumToken::IdenTokenType {
486                                let val = arena.resolve_string(arena.string_value.get(v)).to_lowercase();
487                                if unexpected_constant(&val, &color_space) {
488                                    push_error(&mut errors, format!("Unexpected constant '{}'", val), v);
489                                    return false;
490                                }
491                            }
492                        }
493                    }
494                }
495            }
496        }
497        let tokens = arena.tokens(token);
498        let mut walker = ValueWalker::of_tokens(
499            &tokens,
500            WalkerValueOptions {
501                fn_: Some(Box::new(|arena, value, _| {
502                    if arena.data_types.get(value) == EnumToken::WildCardFunctionTokenType {
503                        WalkerValueResult::Option(WalkerOptionEnum::Ignore | WalkerOptionEnum::IgnoreChildren)
504                    } else {
505                        WalkerValueResult::None
506                    }
507                })),
508                ..Default::default()
509            },
510            false,
511        );
512        while let Some(value) = walker.next(arena) {
513            let parent = match arena.get_value_parent(value) {
514                0 => token,
515                p => p,
516            };
517            let mut tk = 0;
518            let mut tl = 0;
519            if arena.data_types.get(value) == EnumToken::BinaryExpressionTokenType {
520                tk = arena.field(value, TokenField::L);
521                tl = arena.field(value, TokenField::R);
522            } else if parent != token
523                && arena.data_types.get(parent) == EnumToken::MathFunctionTokenType
524                && arena.string_equals(arena.string_value.get(parent), "calc")
525            {
526                let children = arena.tokens(parent);
527                let k = 0;
528                let mut l = k + 1;
529                while l + 1 < children.len() {
530                    let t = arena.data_types.get(children[l]);
531                    if matches!(
532                        t,
533                        EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::Add | EnumToken::Sub | EnumToken::Div | EnumToken::Mul
534                    ) {
535                        l += 1;
536                        continue;
537                    }
538                    break;
539                }
540                tk = children.get(k).copied().unwrap_or(0);
541                tl = children.get(l).copied().unwrap_or(0);
542            }
543            if tk != 0 && tl != 0 {
544                let (a, b) = (arena.data_types.get(tk), arena.data_types.get(tl));
545                if (a == EnumToken::PercentageTokenType || b == EnumToken::PercentageTokenType) && a != b {
546                    push_error(&mut errors, "adding percentage and number is not allowed".into(), token);
547                    return false;
548                }
549            }
550        }
551        if &*name == "color" {
552            let children = filter_children(
553                arena,
554                token,
555                &[
556                    EnumToken::DashedIdenTokenType,
557                    EnumToken::IdenTokenType,
558                    EnumToken::NumberTokenType,
559                    EnumToken::LiteralTokenType,
560                    EnumToken::ColorTokenType,
561                    EnumToken::FunctionTokenType,
562                    EnumToken::MathFunctionTokenType,
563                    EnumToken::PercentageTokenType,
564                ],
565            );
566            let is_relative = children.first().is_some_and(|&c| {
567                arena.data_types.get(c) == EnumToken::IdenTokenType && arena.string_equals(arena.string_value.get(c), "from")
568            });
569            let offset = if is_relative { 2 } else { 0 };
570            if offset < children.len() && arena.data_types.get(children[offset]) == EnumToken::DashedIdenTokenType {
571                if children.len() <= offset + 1 {
572                    push_error(&mut errors, "Invalid color".into(), token);
573                    return false;
574                }
575                for &child in &children[offset + 1..] {
576                    let child_type = arena.data_types.get(child);
577                    if matches!(
578                        child_type,
579                        EnumToken::NumberTokenType
580                            | EnumToken::LiteralTokenType
581                            | EnumToken::ColorTokenType
582                            | EnumToken::FunctionTokenType
583                            | EnumToken::MathFunctionTokenType
584                            | EnumToken::PercentageTokenType
585                    ) || is_color(arena, child, None)
586                        || (child_type == EnumToken::IdenTokenType && arena.string_equals_ignore_case(arena.string_value.get(child), "none"))
587                    {
588                        continue;
589                    }
590                    return false;
591                }
592                return true;
593            }
594            return true;
595        } else if &*name == "color-mix" {
596            let mut children: Vec<Vec<u32>> = vec![Vec::new()];
597            for t in arena.token_iter(token) {
598                let tt = arena.data_types.get(t);
599                if tt == EnumToken::CommaTokenType {
600                    children.push(Vec::new());
601                } else if tt != EnumToken::WhitespaceTokenType && tt != EnumToken::CommentTokenType {
602                    children.last_mut().unwrap().push(t);
603                }
604            }
605            let j = 0;
606            let mut k = 0;
607            let first = &children[j];
608            let s = |t: u32| arena.resolve_string(arena.string_value.get(t));
609            if !first.is_empty()
610                && arena.data_types.get(first[0]) == EnumToken::IdenTokenType
611                && equals_ignore_case("in", &s(first[k]))
612            {
613                k += 1;
614                if k < first.len() && arena.data_types.get(first[k]) == EnumToken::IdenTokenType {
615                    if !is_rectangular_orthogonal_colorspace(arena, first[k]) {
616                        let polar = is_polar_colorspace(arena, first[k]);
617                        k += 1;
618                        if polar {
619                            if k == first.len() {
620                            } else if arena.data_types.get(first[k]) != EnumToken::IdenTokenType {
621                                return false;
622                            } else if equals_ignore_case("hue", &s(first[k])) {
623                            } else {
624                                match &*s(first[k]) {
625                                    "increasing" | "decreasing" | "longer" | "shorter" => k += 1,
626                                    _ => return false,
627                                }
628                                if k >= first.len()
629                                    || arena.data_types.get(first[k]) != EnumToken::IdenTokenType
630                                    || !equals_ignore_case("hue", &s(first[k]))
631                                {
632                                    return false;
633                                }
634                            }
635                        }
636                    }
637                }
638            }
639            return true;
640        }
641        return true;
642    }
643    false
644}
645
646/// parse a color token: set the color type of identifiers and color functions
647pub fn parse_color(arena: &AstArena, token: u32) -> u32 {
648    let typ = arena.data_types.get(token);
649    if typ == EnumToken::IdenTokenType {
650        let val = arena.resolve_string(arena.string_value.get(token)).to_lowercase();
651        if non_standard_colors().contains(&val) {
652            arena.data_types.set(token, EnumToken::ColorTokenType);
653            arena.color_type.set(token, ColorType::NON_STD);
654            return token;
655        }
656        if SYSTEM_COLORS.contains(&val.as_str()) {
657            arena.data_types.set(token, EnumToken::ColorTokenType);
658            arena.color_type.set(token, ColorType::SYS);
659            return token;
660        }
661        if DEPRECATED_SYSTEM_COLORS.contains(&val.as_str()) {
662            arena.data_types.set(token, EnumToken::ColorTokenType);
663            arena.color_type.set(token, ColorType::DPSYS);
664            return token;
665        }
666        if color_name_to_hex(&val).is_some() || val == "currentcolor" {
667            arena.data_types.set(token, EnumToken::ColorTokenType);
668            arena.string_value.set(token, arena.intern_string(&val));
669            arena.color_type.set(token, ColorType::LIT);
670            return token;
671        }
672    }
673    if typ == EnumToken::ColorTokenType {
674        let val = arena.resolve_string(arena.string_value.get(token));
675        if arena.color_type.get(token) == ColorType::NONE && arena.string_value.get(token) != 0 {
676            arena.color_type.set(token, color_type_of(&val));
677        }
678        if arena.first_token.get(token) != 0 {
679            let tk = arena.find_token(token, |arena, t| {
680                let tt = arena.data_types.get(t);
681                tt != EnumToken::WhitespaceTokenType && tt != EnumToken::CommentTokenType
682            });
683            if let Some(tk) = tk {
684                if arena.data_types.get(tk) == EnumToken::IdenTokenType && arena.string_equals(arena.string_value.get(tk), "from") {
685                    arena.unit.set(token, arena.intern_string("rel"));
686                } else if &*val == "color-mix" && arena.string_equals(arena.string_value.get(tk), "in") {
687                    arena.unit.set(token, arena.intern_string("mix"));
688                }
689                if &*val == "color" && arena.data_types.get(tk) == EnumToken::DashedIdenTokenType {
690                    arena.color_type.set(token, ColorType::CUSTOM_COLOR);
691                }
692            }
693        }
694    }
695    token
696}
697
698#[inline]
699pub fn is_letter(codepoint: u32) -> bool {
700    (0x61..=0x7a).contains(&codepoint) || (0x41..=0x5a).contains(&codepoint)
701}
702
703#[inline]
704fn is_non_ascii(codepoint: u32) -> bool {
705    codepoint >= 0x80
706}
707
708#[inline]
709pub fn is_ident_start(codepoint: u32) -> bool {
710    // u32::MAX stands for `undefined` / NaN
711    codepoint != u32::MAX && (codepoint == 0x5f || is_letter(codepoint) || is_non_ascii(codepoint) || codepoint == REVERSE_SOLIDUS)
712}
713
714#[inline]
715pub fn is_digit(codepoint: u32) -> bool {
716    (0x30..=0x39).contains(&codepoint)
717}
718
719#[inline]
720pub fn is_ident_codepoint(codepoint: u32) -> bool {
721    codepoint == 0x2d || is_digit(codepoint) || is_ident_start(codepoint)
722}
723
724/// true if the name is an identifier (over the utf-16 code units, like the typescript implementation)
725pub fn is_ident(name: &str) -> bool {
726    let units: Vec<u16> = if name.is_ascii() { name.bytes().map(|b| b as u16).collect() } else { name.encode_utf16().collect() };
727    is_ident_units(&units)
728}
729
730/// [`is_ident`] over utf-16 code units
731pub fn is_ident_units(name: &[u16]) -> bool {
732    let at = |i: usize| name.get(i).map_or(u32::MAX, |&c| c as u32);
733    let j: isize = name.len() as isize - 1;
734    let mut i: isize = 0;
735    let mut codepoint = at(0);
736    if codepoint == 0x2d {
737        let next = at(1);
738        if next == u32::MAX || is_digit(next) {
739            return false;
740        }
741        codepoint = next;
742        i = 1;
743    }
744    if codepoint != 0x2d && !is_ident_start(codepoint) {
745        return false;
746    }
747    if codepoint == REVERSE_SOLIDUS {
748        if i + 1 > j {
749            return false;
750        }
751        i += 1;
752    }
753    while i < j {
754        i += 1;
755        codepoint = at(i as usize);
756        if codepoint == REVERSE_SOLIDUS {
757            i += 1;
758            i += 1;
759            continue;
760        }
761        if codepoint != 0x2d && !is_ident_codepoint(codepoint) {
762            return false;
763        }
764    }
765    true
766}
767
768#[inline]
769pub fn is_non_printable(codepoint: u32) -> bool {
770    codepoint <= 0x8 || codepoint == 0xb || codepoint == 0x7f || (0xe..=0x1f).contains(&codepoint)
771}
772
773/// `:name`, `::name`, `:name(`
774pub fn is_pseudo(name: &str) -> bool {
775    if !name.starts_with(':') {
776        return false;
777    }
778    let skip = if name[1..].starts_with(':') { 2 } else { 1 };
779    (name.ends_with('(') && name.len() > skip && is_ident(&name[skip..name.len() - 1])) || is_ident(&name[skip..])
780}
781
782pub fn is_hash(name: &str) -> bool {
783    name.starts_with('#') && is_ident_start(name.encode_utf16().nth(1).map_or(u32::MAX, |c| c as u32))
784}
785
786/// result of [`parse_dimension`]
787#[derive(Clone, Debug, PartialEq)]
788pub struct Dimension {
789    pub typ: u8,
790    pub val: f64,
791    pub unit: String,
792}
793
794/// parse a dimension (`10px`)
795pub fn parse_dimension(name: &str) -> Option<Dimension> {
796    let bytes = name.as_bytes();
797    let mut index = bytes.len();
798    while index > 0 && is_letter(bytes[index - 1] as u32) {
799        index -= 1;
800    }
801    // every character is a letter (the typescript index reaches -1)
802    if index == 0 {
803        return None;
804    }
805    let unit = &name[index..];
806    let val = crate::utils::number::js_parse_number(&name[..index]);
807    if val.is_nan() {
808        return None;
809    }
810    let unit = validation_units().iter().find(|u| equals_ignore_case(u, unit)).cloned().unwrap_or_else(|| unit.to_lowercase());
811    let typ = if is_angle_unit(&unit) {
812        EnumToken::AngleTokenType
813    } else if is_length_unit(&unit) {
814        EnumToken::LengthTokenType
815    } else if is_time_unit(&unit) {
816        EnumToken::TimeTokenType
817    } else if is_resolution_unit(&unit) {
818        EnumToken::ResolutionTokenType
819    } else if is_frequency_unit(&unit) {
820        EnumToken::FrequencyTokenType
821    } else if is_flex_unit(&unit) {
822        EnumToken::FlexTokenType
823    } else {
824        EnumToken::DimensionTokenType
825    };
826    Some(Dimension { typ, val, unit })
827}
828
829pub fn is_function(name: &str) -> bool {
830    name.ends_with('(') && is_ident(&name[..name.len() - 1])
831}
832
833#[inline]
834pub fn is_new_line(codepoint: u32) -> bool {
835    matches!(codepoint, 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029)
836}
837
838#[inline]
839pub fn is_white_space(codepoint: u32) -> bool {
840    matches!(codepoint, 0x9 | 0x20 | 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029)
841}
842
843/// convert a length to px
844pub fn length2_px(arena: &AstArena, value: u32) -> Option<f64> {
845    let val = arena.numeric_value.get(value);
846    let result = if arena.data_types.get(value) == EnumToken::NumberTokenType {
847        Some(val)
848    } else {
849        arena.with_string(arena.unit.get(value), |unit| match unit.to_lowercase().as_str() {
850            "cm" => Some((val * 96.0) / 2.54),
851            "mm" => Some((val * 96.0) / 25.4),
852            "q" => Some((val * 96.0) / 101.6),
853            "in" => Some(val * 96.0),
854            "pc" => Some(val * 16.0),
855            "pt" => Some((val * 4.0) / 3.0),
856            "px" => Some(val),
857            _ => None,
858        })
859    };
860    result.filter(|r| !r.is_nan())
861}
862
863thread_local! {
864    /// minified numbers, see [`minify_number`]
865    static MINIFIED_NUMBERS: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::default());
866}
867
868const MINIFIED_NUMBERS_SIZE: usize = 4096;
869
870/// run a function with the minified number: the cached string is borrowed (see [`minify_number`])
871pub fn with_minified_number<R>(val: f64, f: impl FnOnce(&str) -> R) -> R {
872    MINIFIED_NUMBERS.with(|cache| {
873        if let Some(result) = cache.borrow().get(&val.to_bits()) {
874            return f(result);
875        }
876        let result = minify_number_value(val);
877        let output = f(&result);
878        let mut cache = cache.borrow_mut();
879        if cache.len() >= MINIFIED_NUMBERS_SIZE {
880            cache.clear();
881        }
882        cache.insert(val.to_bits(), result);
883        output
884    })
885}
886
887/// minify a number
888pub fn minify_number(val: f64) -> String {
889    MINIFIED_NUMBERS.with(|cache| {
890        if let Some(result) = cache.borrow().get(&val.to_bits()) {
891            return result.clone();
892        }
893        let result = minify_number_value(val);
894        let mut cache = cache.borrow_mut();
895        if cache.len() >= MINIFIED_NUMBERS_SIZE {
896            cache.clear();
897        }
898        cache.insert(val.to_bits(), result.clone());
899        result
900    })
901}
902
903/// minify a number given as a string
904pub fn minify_number_str(val: &str) -> String {
905    minify_number_value(crate::utils::number::js_parse_number(val))
906}
907
908/// minify a number
909fn minify_number_value(val: f64) -> String {
910    let val = js_number_to_string(to_precision_value(val, colorPrecision));
911    if val == "0" {
912        return "0".into();
913    }
914    if let Some(rest) = val.strip_prefix("-0") {
915        return if rest.is_empty() { "0".into() } else { format!("-{}", rest) };
916    }
917    if let Some(rest) = val.strip_prefix('0') {
918        return rest.into();
919    }
920    val
921}
922
923/// round a value to a precision (default `colorPrecision`)
924pub fn to_precision_value(value: f64, precision: i32) -> f64 {
925    let div = 10f64.powi(precision);
926    let value = js_round(value * div) / div;
927    if value.abs() < epsilon {
928        0.0
929    } else {
930        value
931    }
932}
933
934/// round an angle (default precision `anglePrecision`, corrected)
935pub fn to_precision_angle(angle: f64, precision: i32, correct_value: bool) -> f64 {
936    let mut angle = to_precision_value(angle, precision);
937    if correct_value && angle.abs() >= 360.0 {
938        angle %= 360.0;
939    }
940    if correct_value && angle < 0.0 {
941        angle += 360.0;
942    }
943    angle
944}
945
946/// `toPrecisionAngle(angle)` with the default arguments
947pub fn to_precision_angle_default(angle: f64) -> f64 {
948    to_precision_angle(angle, anglePrecision, true)
949}