Skip to main content

rust_css_parser/syntax/
constants.rs

1//! Port of `src/syntax/constants.ts`.
2
3use crate::ast::types::EnumToken;
4use crate::plain::Plain;
5use crate::utils::fx::{HashMap, HashSet};
6use std::sync::OnceLock;
7
8/// the units of the validation data, in their canonical spelling (`Hz`, `Q`, `dB`)
9pub fn validation_units() -> &'static [String] {
10    static UNITS: OnceLock<Vec<String>> = OnceLock::new();
11    UNITS.get_or_init(|| {
12        crate::validation::json::config_json()["units"]
13            .as_array()
14            .map(|a| a.iter().filter_map(|u| u.as_str().map(String::from)).collect())
15            .unwrap_or_default()
16    })
17}
18
19/// `/^-((webkit)|o|moz)(-repeating)?-linear-gradient$/i`
20pub fn reg_match_linear_gradient(name: &str) -> bool {
21    match_prefixed_gradient(name, "linear")
22}
23
24/// `/^-((webkit)|o|moz)(-repeating)?-radial-gradient$/i`
25pub fn reg_match_radial_gradient(name: &str) -> bool {
26    match_prefixed_gradient(name, "radial")
27}
28
29fn match_prefixed_gradient(name: &str, kind: &str) -> bool {
30    let lower = name.to_ascii_lowercase();
31    let Some(rest) = ["-webkit", "-o", "-moz"].iter().find_map(|p| lower.strip_prefix(p)) else {
32        return false;
33    };
34    let rest = rest.strip_prefix("-repeating").unwrap_or(rest);
35    rest.strip_prefix('-').and_then(|r| r.strip_prefix(kind)) == Some("-gradient")
36}
37
38pub const mFLT: [u8; 2] = [EnumToken::LtTokenType, EnumToken::LteTokenType];
39pub const mFGT: [u8; 2] = [EnumToken::GtTokenType, EnumToken::GteTokenType];
40
41/// `tokensMap`
42pub fn tokens_map(typ: u8) -> Option<u8> {
43    match typ {
44        EnumToken::Star => Some(EnumToken::Mul),
45        EnumToken::Plus => Some(EnumToken::Add),
46        _ => None,
47    }
48}
49
50/// `/^(["']?)[a-zA-Z0-9_/.-][a-zA-Z0-9_/:.#?-]+(\1)$/`
51pub fn url_token_matcher(value: &str) -> bool {
52    let bytes = value.as_bytes();
53    let quote = match bytes.first() {
54        Some(&q @ (b'"' | b'\'')) => Some(q),
55        _ => None,
56    };
57    let body = match quote {
58        Some(q) => {
59            if bytes.len() < 2 || bytes[bytes.len() - 1] != q {
60                return false;
61            }
62            &bytes[1..bytes.len() - 1]
63        }
64        None => bytes,
65    };
66    if body.len() < 2 {
67        return false;
68    }
69    let first = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'/' | b'.' | b'-');
70    let rest = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'/' | b':' | b'.' | b'#' | b'?' | b'-');
71    first(body[0]) && body[1..].iter().all(|&b| rest(b))
72}
73
74/// `tokensfuncDefMap`: function definition token type -> function token type
75pub const TOKENS_FUNC_DEF_MAP: [(u8, u8); 16] = [
76    (EnumToken::FunctionTokenDefType, EnumToken::FunctionTokenType),
77    (EnumToken::ColorFunctionTokenDefType, EnumToken::ColorTokenType),
78    (EnumToken::UrlFunctionTokenDefType, EnumToken::UrlFunctionTokenType),
79    (EnumToken::MathFunctionTokenDefType, EnumToken::MathFunctionTokenType),
80    (EnumToken::ImageFunctionTokenDefType, EnumToken::ImageFunctionTokenType),
81    (EnumToken::TimingFunctionTokenDefType, EnumToken::TimingFunctionTokenType),
82    (EnumToken::CustomFunctionTokenDefType, EnumToken::CustomFunctionTokenType),
83    (EnumToken::WildCardFunctionTokenDefType, EnumToken::WildCardFunctionTokenType),
84    (EnumToken::TimelineFunctionTokenDefType, EnumToken::TimelineFunctionTokenType),
85    (EnumToken::GridTemplateFuncTokenDefType, EnumToken::GridTemplateFuncTokenType),
86    (EnumToken::SupportsFunctionTokenDefType, EnumToken::SupportsFunctionTokenType),
87    (EnumToken::WhenElseFunctionTokenDefType, EnumToken::WhenElseFunctionTokenType),
88    (EnumToken::ContainerFunctionTokenDefType, EnumToken::ContainerFunctionTokenType),
89    (EnumToken::PseudoClassFunctionTokenDefType, EnumToken::PseudoClassFuncTokenType),
90    (EnumToken::TransformFunctionTokenDefType, EnumToken::TransformFunctionTokenType),
91    (EnumToken::GeneralEnclosedFunctionTokenDefType, EnumToken::GeneralEnclosedFunctionTokenType),
92];
93
94/// `tokensfuncDefMap.get(type)`
95pub fn tokens_func_def_map(typ: u8) -> Option<u8> {
96    TOKENS_FUNC_DEF_MAP.iter().find(|(d, _)| *d == typ).map(|(_, t)| *t)
97}
98
99const fn function_types() -> [u8; 256] {
100    let mut types = [0u8; 256];
101    let mut i = 0;
102    while i < TOKENS_FUNC_DEF_MAP.len() {
103        types[TOKENS_FUNC_DEF_MAP[i].0 as usize] |= 1;
104        types[TOKENS_FUNC_DEF_MAP[i].1 as usize] |= 2;
105        i += 1;
106    }
107    types
108}
109
110static FUNCTION_TYPES: [u8; 256] = function_types();
111
112/// true if the token type is a function definition (`name(`)
113#[inline]
114pub fn is_function_def_type(typ: u8) -> bool {
115    FUNCTION_TYPES[typ as usize] & 1 == 1
116}
117
118/// true if the token type is a function (`tokensfuncSet.has(type)`)
119#[inline]
120pub fn is_function_type(typ: u8) -> bool {
121    FUNCTION_TYPES[typ as usize] & 2 == 2
122}
123
124pub const epsilon: f64 = 1e-5;
125pub const colorDistancePrecision: f64 = epsilon;
126pub const colorPrecision: i32 = 6;
127pub const anglePrecision: i32 = 3;
128
129/// `colorRange`: [min, max] of the components, by color space
130pub fn color_range(space: &str, component: &str) -> Option<[f64; 2]> {
131    Some(match (space, component) {
132        ("rgb", "r" | "g" | "b") => [0.0, 255.0],
133        ("lab", "l") => [0.0, 100.0],
134        ("lab", "a" | "b") => [-125.0, 125.0],
135        ("lch", "l") => [0.0, 100.0],
136        ("lch", "c") => [0.0, 150.0],
137        ("lch", "h") => [0.0, 360.0],
138        ("oklab", "l") => [0.0, 1.0],
139        ("oklab", "a" | "b") => [-0.4, 0.4],
140        ("oklch", "l") => [0.0, 1.0],
141        ("oklch", "a" | "b") => [0.0, 0.4],
142        _ => return None,
143    })
144}
145
146pub const PSEUDO_ELEMENTS: [&str; 8] = [":before", ":after", ":first-line", ":first-letter", "::before", "::after", "::first-line", "::first-letter"];
147pub const WILD_CARD_FUNCS: [&str; 3] = ["var", "env", "if"];
148pub const MATH_FUNCS: [&str; 26] = ["minmax", "repeat", "fit-content", "calc", "clamp", "min", "max", "round", "mod", "rem", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "tan", "pow", "sqrt", "hypot", "log", "exp", "abs", "sign", "anchor"];
149pub const MEDIA_TYPES: [&str; 11] = ["all", "print", "screen", "aural", "braille", "embossed", "handheld", "projection", "tty", "tv", "speech"];
150pub const URL_FUNC: [&str; 1] = ["url"];
151pub const TIMELINE_FUNC: [&str; 2] = ["view", "scroll"];
152pub const GRID_TEMPLATE_FUNC: [&str; 3] = ["minmax", "fit-content", "repeat"];
153pub const SUPPORT_FUNC: [&str; 5] = ["selector", "font-tech", "font-format", "at-rule", "named-feature"];
154pub const WHEN_ELSE_FUNC: [&str; 2] = ["media", "supports"];
155pub const CONTAINER_FUNC: [&str; 2] = ["style", "scroll-state"];
156pub const TIMING_FUNC: [&str; 9] = ["ease", "ease-in", "ease-out", "ease-in-out", "linear", "step-start", "step-end", "steps", "cubic-bezier"];
157pub const COLORS_FUNC: [&str; 16] = ["rgb", "rgba", "hsl", "hsla", "hwb", "device-cmyk", "color-mix", "color", "oklab", "lab", "oklch", "lch", "alpha", "light-dark", "color-layers", "contrast-color"];
158pub const IMAGE_FUNC: [&str; 18] = ["linear-gradient", "radial-gradient", "repeating-linear-gradient", "repeating-radial-gradient", "repeating-conic-gradient", "conic-gradient", "image", "image-set", "element", "cross-fade", "paint", "-o-linear-gradient", "-moz-linear-gradient", "-webkit-linear-gradient", "-webkit-repeating-linear-gradient", "-webkit-gradient", "-webkit-radial-gradient", "-webkit-repeating-radial-gradient"];
159pub const TRANSFORM_FUNCTIONS: [&str; 21] = ["translate", "scale", "rotate", "skew", "perspective", "translateX", "translateY", "translateZ", "scaleX", "scaleY", "scaleZ", "rotateX", "rotateY", "rotateZ", "skewX", "skewY", "rotate3d", "translate3d", "scale3d", "matrix", "matrix3d"];
160pub const COLOR_FUNC_COLOR_SPACE: [&str; 12] = ["srgb", "srgb-linear", "display-p3", "display-p3-linear", "prophoto-rgb", "a98-rgb", "rec2020", "lab", "oklab", "xyz", "xyz-d65", "xyz-d50"];
161pub const COMBINATORS: [&str; 5] = ["+", ">", "~", "||", "|"];
162pub const PAGE_MARGIN_BOX_TYPE: [&str; 16] = ["top-left-corner", "top-left", "top-center", "top-right", "top-right-corner", "bottom-left-corner", "bottom-left", "bottom-center", "bottom-right", "bottom-right-corner", "left-top", "left-middle", "left-bottom", "right-top", "right-middle", "right-bottom"];
163
164pub const FUNC_LIKE: [u8; 9] = [
165    EnumToken::ParensTokenType,
166    EnumToken::FunctionTokenType,
167    EnumToken::UrlFunctionTokenType,
168    EnumToken::StartParensTokenType,
169    EnumToken::ImageFunctionTokenType,
170    EnumToken::TimingFunctionTokenType,
171    EnumToken::TimingFunctionTokenType,
172    EnumToken::PseudoClassFuncTokenType,
173    EnumToken::GridTemplateFuncTokenType,
174];
175
176pub const D50: [f64; 3] = [0.3457 / 0.3585, 1.0, (1.0 - 0.3457 - 0.3585) / 0.3585];
177/// `Math.pow(29, 3) / Math.pow(3, 3)`
178pub const k: f64 = 24389.0 / 27.0;
179/// `Math.pow(6, 3) / Math.pow(29, 3)`
180pub const e: f64 = 216.0 / 24389.0;
181
182/// `nonStandardColors`
183pub fn non_standard_colors() -> &'static HashSet<String> {
184    static SET: OnceLock<HashSet<String>> = OnceLock::new();
185    SET.get_or_init(|| {
186        let syntax = crate::validation::json::config_json()["syntaxes"]["-non-standard-color"]["syntax"].as_str().unwrap_or("");
187        syntax
188            .split(|c: char| c.is_whitespace() || c == '|')
189            .filter(|s| !s.is_empty())
190            .map(|m| m.to_lowercase())
191            .collect()
192    })
193}
194
195/// `systemColors` (lowercase)
196pub const SYSTEM_COLORS: [&str; 16] = ["activetext", "buttonborder", "buttonface", "buttontext", "canvas", "canvastext", "field", "fieldtext", "graytext", "highlight", "highlighttext", "linktext", "mark", "marktext", "visitedtext", "-webkit-focus-ring-color"];
197/// `deprecatedSystemColors` (lowercase)
198pub const DEPRECATED_SYSTEM_COLORS: [&str; 28] = ["activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext"];
199
200/// `COLORS_NAMES`: name to color
201pub const COLORS_NAMES: [(&str, &str); 149] = [
202    ("aliceblue", "#f0f8ff"),
203    ("antiquewhite", "#faebd7"),
204    ("aqua", "#00ffff"),
205    ("aquamarine", "#7fffd4"),
206    ("azure", "#f0ffff"),
207    ("beige", "#f5f5dc"),
208    ("bisque", "#ffe4c4"),
209    ("black", "#000000"),
210    ("blanchedalmond", "#ffebcd"),
211    ("blue", "#0000ff"),
212    ("blueviolet", "#8a2be2"),
213    ("brown", "#a52a2a"),
214    ("burlywood", "#deb887"),
215    ("cadetblue", "#5f9ea0"),
216    ("chartreuse", "#7fff00"),
217    ("chocolate", "#d2691e"),
218    ("coral", "#ff7f50"),
219    ("cornflowerblue", "#6495ed"),
220    ("cornsilk", "#fff8dc"),
221    ("crimson", "#dc143c"),
222    ("cyan", "#00ffff"),
223    ("darkblue", "#00008b"),
224    ("darkcyan", "#008b8b"),
225    ("darkgoldenrod", "#b8860b"),
226    ("darkgray", "#a9a9a9"),
227    ("darkgrey", "#a9a9a9"),
228    ("darkgreen", "#006400"),
229    ("darkkhaki", "#bdb76b"),
230    ("darkmagenta", "#8b008b"),
231    ("darkolivegreen", "#556b2f"),
232    ("darkorange", "#ff8c00"),
233    ("darkorchid", "#9932cc"),
234    ("darkred", "#8b0000"),
235    ("darksalmon", "#e9967a"),
236    ("darkseagreen", "#8fbc8f"),
237    ("darkslateblue", "#483d8b"),
238    ("darkslategray", "#2f4f4f"),
239    ("darkslategrey", "#2f4f4f"),
240    ("darkturquoise", "#00ced1"),
241    ("darkviolet", "#9400d3"),
242    ("deeppink", "#ff1493"),
243    ("deepskyblue", "#00bfff"),
244    ("dimgray", "#696969"),
245    ("dimgrey", "#696969"),
246    ("dodgerblue", "#1e90ff"),
247    ("firebrick", "#b22222"),
248    ("floralwhite", "#fffaf0"),
249    ("forestgreen", "#228b22"),
250    ("fuchsia", "#ff00ff"),
251    ("gainsboro", "#dcdcdc"),
252    ("ghostwhite", "#f8f8ff"),
253    ("gold", "#ffd700"),
254    ("goldenrod", "#daa520"),
255    ("gray", "#808080"),
256    ("grey", "#808080"),
257    ("green", "#008000"),
258    ("greenyellow", "#adff2f"),
259    ("honeydew", "#f0fff0"),
260    ("hotpink", "#ff69b4"),
261    ("indianred", "#cd5c5c"),
262    ("indigo", "#4b0082"),
263    ("ivory", "#fffff0"),
264    ("khaki", "#f0e68c"),
265    ("lavender", "#e6e6fa"),
266    ("lavenderblush", "#fff0f5"),
267    ("lawngreen", "#7cfc00"),
268    ("lemonchiffon", "#fffacd"),
269    ("lightblue", "#add8e6"),
270    ("lightcoral", "#f08080"),
271    ("lightcyan", "#e0ffff"),
272    ("lightgoldenrodyellow", "#fafad2"),
273    ("lightgray", "#d3d3d3"),
274    ("lightgrey", "#d3d3d3"),
275    ("lightgreen", "#90ee90"),
276    ("lightpink", "#ffb6c1"),
277    ("lightsalmon", "#ffa07a"),
278    ("lightseagreen", "#20b2aa"),
279    ("lightskyblue", "#87cefa"),
280    ("lightslategray", "#778899"),
281    ("lightslategrey", "#778899"),
282    ("lightsteelblue", "#b0c4de"),
283    ("lightyellow", "#ffffe0"),
284    ("lime", "#00ff00"),
285    ("limegreen", "#32cd32"),
286    ("linen", "#faf0e6"),
287    ("magenta", "#ff00ff"),
288    ("maroon", "#800000"),
289    ("mediumaquamarine", "#66cdaa"),
290    ("mediumblue", "#0000cd"),
291    ("mediumorchid", "#ba55d3"),
292    ("mediumpurple", "#9370d8"),
293    ("mediumseagreen", "#3cb371"),
294    ("mediumslateblue", "#7b68ee"),
295    ("mediumspringgreen", "#00fa9a"),
296    ("mediumturquoise", "#48d1cc"),
297    ("mediumvioletred", "#c71585"),
298    ("midnightblue", "#191970"),
299    ("mintcream", "#f5fffa"),
300    ("mistyrose", "#ffe4e1"),
301    ("moccasin", "#ffe4b5"),
302    ("navajowhite", "#ffdead"),
303    ("navy", "#000080"),
304    ("oldlace", "#fdf5e6"),
305    ("olive", "#808000"),
306    ("olivedrab", "#6b8e23"),
307    ("orange", "#ffa500"),
308    ("orangered", "#ff4500"),
309    ("orchid", "#da70d6"),
310    ("palegoldenrod", "#eee8aa"),
311    ("palegreen", "#98fb98"),
312    ("paleturquoise", "#afeeee"),
313    ("palevioletred", "#d87093"),
314    ("papayawhip", "#ffefd5"),
315    ("peachpuff", "#ffdab9"),
316    ("peru", "#cd853f"),
317    ("pink", "#ffc0cb"),
318    ("plum", "#dda0dd"),
319    ("powderblue", "#b0e0e6"),
320    ("purple", "#800080"),
321    ("red", "#ff0000"),
322    ("rosybrown", "#bc8f8f"),
323    ("royalblue", "#4169e1"),
324    ("saddlebrown", "#8b4513"),
325    ("salmon", "#fa8072"),
326    ("sandybrown", "#f4a460"),
327    ("seagreen", "#2e8b57"),
328    ("seashell", "#fff5ee"),
329    ("sienna", "#a0522d"),
330    ("silver", "#c0c0c0"),
331    ("skyblue", "#87ceeb"),
332    ("slateblue", "#6a5acd"),
333    ("slategray", "#708090"),
334    ("slategrey", "#708090"),
335    ("snow", "#fffafa"),
336    ("springgreen", "#00ff7f"),
337    ("steelblue", "#4682b4"),
338    ("tan", "#d2b48c"),
339    ("teal", "#008080"),
340    ("thistle", "#d8bfd8"),
341    ("tomato", "#ff6347"),
342    ("turquoise", "#40e0d0"),
343    ("violet", "#ee82ee"),
344    ("wheat", "#f5deb3"),
345    ("white", "#ffffff"),
346    ("whitesmoke", "#f5f5f5"),
347    ("yellow", "#ffff00"),
348    ("yellowgreen", "#9acd32"),
349    ("rebeccapurple", "#663399"),
350    ("transparent", "#00000000"),
351];
352
353/// `COLORS_NAMES[name]`
354pub fn color_name_to_hex(name: &str) -> Option<&'static str> {
355    static MAP: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
356    MAP.get_or_init(|| COLORS_NAMES.iter().copied().collect()).get(name).copied()
357}
358
359/// `NAMES_COLORS[hex]`: color to name (the last name of a color wins, like the typescript reduce)
360pub fn hex_to_color_name(hex: &str) -> Option<&'static str> {
361    static MAP: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
362    MAP.get_or_init(|| COLORS_NAMES.iter().map(|&(name, hex)| (hex, name)).collect()).get(hex).copied()
363}
364
365/// `trimTokenSpace`
366pub fn trim_token_space(typ: u8) -> bool {
367    matches!(
368        typ,
369        EnumToken::Add
370            | EnumToken::Mul
371            | EnumToken::Div
372            | EnumToken::Sub
373            | EnumToken::ColonTokenType
374            | EnumToken::CommaTokenType
375            | EnumToken::SemiColonTokenType
376            | EnumToken::DashedIdenTokenType
377            | EnumToken::DeclarationNodeType
378            | EnumToken::SupportsQueryConditionTokenType
379            | EnumToken::SupportsQueryUnaryConditionTokenType
380    )
381}
382
383#[allow(dead_code)]
384fn _plain(_: Plain) {}