Skip to main content

rust_css_parser/parser/utils/
at_rule_media.rs

1//! Port of `src/parser/utils/at-rule-media.ts`.
2
3use crate::ast::arena::{AstArena, TokenField, TokenValue};
4use crate::ast::math::expression::evaluate;
5use crate::ast::math::math::gcd;
6use crate::ast::types::EnumToken;
7use crate::options::ParserOptions;
8use crate::parser::utils::text::equals_ignore_case;
9use crate::syntax::constants::{is_function_def_type, mFGT, mFLT, tokens_func_def_map, MEDIA_TYPES};
10use crate::types::ErrorDescription;
11use crate::validation::match_::{create_validation_context, drop_error, function_syntax, get_mf_info, is_mf_value, match_all_syntaxes, trim_array, Syntax};
12use crate::validation::parser::typedef::MediaFeatureType;
13
14fn trimmed(arena: &AstArena, tokens: &[u32]) -> Vec<u32> {
15    let mut v = tokens.to_vec();
16    trim_array(arena, &mut v);
17    v
18}
19
20fn slice(v: &[u32], start: isize, end: isize) -> Vec<u32> {
21    let len = v.len() as isize;
22    let norm = |i: isize| if i < 0 { (len + i).max(0) } else { i.min(len) } as usize;
23    let (s, e) = (norm(start), norm(end));
24    if s < e {
25        v[s..e].to_vec()
26    } else {
27        Vec::new()
28    }
29}
30
31fn index_of(v: &[u32], value: Option<u32>) -> isize {
32    value.and_then(|value| v.iter().position(|&x| x == value)).map_or(-1, |i| i as isize)
33}
34
35/// `tokens.splice(start, count, item)`
36fn splice_one(v: &mut Vec<u32>, start: isize, count: isize, item: u32) {
37    let len = v.len() as isize;
38    let s = if start < 0 { (len + start).max(0) } else { start.min(len) } as usize;
39    let c = count.clamp(0, len - s as isize) as usize;
40    v.splice(s..s + c, [item]);
41}
42
43fn is_ws(arena: &AstArena, t: u32) -> bool {
44    matches!(arena.data_types.get(t), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType)
45}
46
47fn mf_type(info: Option<&serde_json::Value>) -> Option<&str> {
48    info.and_then(|i| i["type"].as_str())
49}
50
51/// evaluate the calc() functions of a media feature value
52fn evaluate_calc(arena: &AstArena, val: &mut [u32]) {
53    for l in 0..val.len() {
54        if arena.data_types.get(val[l]) == EnumToken::MathFunctionTokenType && arena.string_equals(arena.string_value.get(val[l]), "calc") {
55            let value = evaluate(arena, &[val[l]]);
56            if value.len() == 1 {
57                arena.copy_location(value[0], val[l]);
58                val[l] = value[0];
59            }
60        }
61    }
62}
63
64/// reduce a ratio by the greatest common divisor
65fn reduce_ratio(arena: &AstArena, val: &mut Vec<u32>, options: &ParserOptions) {
66    let filtered: Vec<u32> = val.iter().copied().filter(|&n| !is_ws(arena, n)).collect();
67    if filtered.len() == 3 {
68        if options.compute_calc_expression == Some(true) {
69            let div = gcd(arena.numeric_value.get(filtered[0]), arena.numeric_value.get(filtered[2]));
70            if div > 1.0 {
71                arena.numeric_value.set(filtered[0], arena.numeric_value.get(filtered[0]) / div);
72                arena.numeric_value.set(filtered[2], arena.numeric_value.get(filtered[2]) / div);
73            }
74        }
75        *val = filtered;
76    }
77}
78
79/// parse a media query list. the invalid queries are removed
80pub fn parse_mediaquery_list(arena: &AstArena, stream: &mut Vec<u32>, options: &ParserOptions) -> (bool, Vec<ErrorDescription>) {
81    let t = |x: u32| arena.data_types.get(x);
82    let mut match_count = 0;
83    let mut errors: Vec<ErrorDescription> = Vec::new();
84    let mut has_errors = false;
85    let mut parts: Vec<Vec<u32>> = vec![Vec::new()];
86    for &token in stream.iter() {
87        let typ = t(token);
88        if typ == EnumToken::CommaTokenType && match_count == 0 {
89            parts.push(Vec::new());
90            continue;
91        }
92        parts.last_mut().unwrap().push(token);
93        if typ == EnumToken::StartParensTokenType || is_function_def_type(typ) {
94            match_count += 1;
95        } else if typ == EnumToken::EndParensTokenType && match_count > 0 {
96            match_count -= 1;
97        }
98    }
99    let mut kept: Vec<Vec<u32>> = Vec::new();
100    for part in parts {
101        let stream = part;
102        let mut success = true;
103        // scopes: (has and, has or)
104        let mut scopes: Vec<(bool, bool)> = vec![(false, false)];
105        let mut stack: Vec<u32> = Vec::new();
106        let mut tokens: Vec<u32> = Vec::new();
107        let mut i = 0usize;
108        while i < stream.len() && is_ws(arena, stream[i]) {
109            tokens.push(stream[i]);
110            i += 1;
111        }
112        // [not | only] <media-type> [ and <media-condition-without-or> ]?
113        let mut modifier: Option<String> = None;
114        if i < stream.len() && t(stream[i]) == EnumToken::IdenTokenType {
115            let val = arena.resolve_string(arena.string_value.get(stream[i])).to_lowercase();
116            if val == "not" || val == "only" {
117                modifier = Some(val);
118                tokens.push(stream[i]);
119                i += 1;
120                while i < stream.len() && is_ws(arena, stream[i]) {
121                    tokens.push(stream[i]);
122                    i += 1;
123                }
124            }
125        }
126        if modifier.is_some() && i == stream.len() {
127            success = false;
128            errors.push(drop_error(arena, "expecting '<media-type>'".into(), stream[i - 1], options));
129        } else if modifier.as_deref() == Some("only") && t(stream[i]) != EnumToken::IdenTokenType {
130            // only is followed by a media type
131            success = false;
132            errors.push(drop_error(arena, "expecting '<media-type>'".into(), stream[i], options));
133        } else if i < stream.len() {
134            if t(stream[i]) == EnumToken::IdenTokenType {
135                let val = arena.resolve_string(arena.string_value.get(stream[i])).to_lowercase();
136                if MEDIA_TYPES.contains(&val.as_str()) {
137                    tokens.push(stream[i]);
138                    i += 1;
139                } else {
140                    success = false;
141                    errors.push(drop_error(arena, "expecting '<media-type>'".into(), stream[i], options));
142                }
143            } else if t(stream[i]) != EnumToken::StartParensTokenType {
144                success = false;
145                errors.push(drop_error(arena, "expecting '('".into(), stream[i], options));
146            }
147        }
148        while i < stream.len() {
149            let current = stream[i];
150            tokens.push(current);
151            if is_ws(arena, current) {
152                i += 1;
153                continue;
154            }
155            if t(current) == EnumToken::StartParensTokenType || is_function_def_type(t(current)) {
156                scopes.push((false, false));
157                stack.push(current);
158                i += 1;
159                continue;
160            }
161            'sw: {
162                match t(current) {
163                    EnumToken::ColonTokenType
164                    | EnumToken::LtTokenType
165                    | EnumToken::LteTokenType
166                    | EnumToken::GtTokenType
167                    | EnumToken::GteTokenType
168                    | EnumToken::DelimTokenType => stack.push(current),
169                    EnumToken::IdenTokenType => {
170                        let val = arena.resolve_string(arena.string_value.get(current)).to_lowercase();
171                        if val == "and" || val == "or" {
172                            let op = if val == "and" { EnumToken::AndTokenType } else { EnumToken::OrTokenType };
173                            arena.data_types.set(current, op);
174                            if val == "or" && scopes.len() == 1 && (scopes[0].0 || scopes[0].1) && !scopes[0].1 {
175                                success = false;
176                                errors.push(drop_error(arena, "<or> is not allowed outside of parentheses".into(), current, options));
177                                break 'sw;
178                            }
179                            let scope = scopes.last_mut().unwrap();
180                            if (val == "or" && scope.0) || (val == "and" && scope.1) {
181                                success = false;
182                                errors.push(drop_error(arena, "cannot mix <and> and <or> at the same level".into(), current, options));
183                            }
184                            if op == EnumToken::AndTokenType {
185                                scope.0 = true;
186                            } else {
187                                scope.1 = true;
188                            }
189                            stack.push(current);
190                        }
191                    }
192                    EnumToken::EndParensTokenType => {
193                        if stack.last().is_some_and(|&s| is_function_def_type(t(s))) {
194                            let index = index_of(&tokens, stack.last().copied());
195                            let func = tokens[index as usize];
196                            arena.span_location(func, func, current);
197                            arena.data_types.set(func, tokens_func_def_map(t(func)).unwrap_or(0));
198                            let inner = trimmed(arena, &slice(&tokens, index + 1, tokens.len() as isize - 1));
199                            arena.set_token_list(func, &inner);
200                            tokens.truncate(index as usize + 1);
201                            // looked up once per function name, the children of the syntax are borrowed
202                            let syntax = function_syntax(arena, func);
203                            let chi: Option<&[Syntax]> = syntax.as_ref().and_then(|s| s.first()).map(|f| f.children());
204                            let result = match_all_syntaxes(arena, chi, &create_validation_context(arena, &arena.tokens(func)), options);
205                            stack.pop();
206                            scopes.pop();
207                            if !result.success {
208                                errors.extend(result.errors);
209                                success = false;
210                            }
211                            break 'sw;
212                        }
213                        // range: <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
214                        let top_t = stack.last().map(|&s| t(s));
215                        if top_t.is_some_and(|s| mFLT.contains(&s) || mFGT.contains(&s)) {
216                            let index = index_of(&tokens, stack.last().copied());
217                            let prev_token = if stack.len() >= 2 { Some(stack[stack.len() - 2]) } else { None };
218                            if prev_token.is_some_and(|p| mFLT.contains(&t(p)) || mFGT.contains(&t(p))) {
219                                let prev_token = prev_token.unwrap();
220                                let index2 = index_of(&tokens, Some(prev_token));
221                                let index3 = index_of(&tokens, if stack.len() >= 3 { Some(stack[stack.len() - 3]) } else { None });
222                                let mut left = trimmed(arena, &slice(&tokens, index3 + 1, index2));
223                                let mut right = trimmed(arena, &slice(&tokens, index + 1, tokens.len() as isize - 1));
224                                let names = trimmed(arena, &slice(&tokens, index2 + 1, index));
225                                let filtered_names: Vec<u32> = names.iter().copied().filter(|&n| !is_ws(arena, n)).collect();
226                                let name = filtered_names.first().map_or(String::new(), |&n| arena.resolve_string(arena.string_value.get(n)).to_string());
227                                let info = get_mf_info(&name);
228                                if options.compute_calc_expression == Some(true)
229                                    && (info.is_none() || !matches!(mf_type(info), Some(MediaFeatureType::KeywordType) | Some(MediaFeatureType::StringType)))
230                                {
231                                    evaluate_calc(arena, &mut left);
232                                    evaluate_calc(arena, &mut right);
233                                }
234                                if mf_type(info) == Some(MediaFeatureType::RatioType) {
235                                    reduce_ratio(arena, &mut left, options);
236                                    reduce_ratio(arena, &mut right, options);
237                                }
238                                let range_query = arena.create_token(EnumToken::MediaRangeQueryTokenType, TokenValue::None, None);
239                                arena.set_token_list(arena.field_list(range_query, TokenField::L), &left);
240                                arena.set_token_list(arena.field_list(range_query, TokenField::Val), &filtered_names);
241                                arena.set_token_list(arena.field_list(range_query, TokenField::Op), &[prev_token]);
242                                arena.set_token_list(arena.field_list(range_query, TokenField::Op2), &[*stack.last().unwrap()]);
243                                arena.set_token_list(arena.field_list(range_query, TokenField::R), &right);
244                                if !left.is_empty() && !right.is_empty() {
245                                    arena.span_location(range_query, left[0], *right.last().unwrap());
246                                }
247                                let count = tokens.len() as isize - index3 - 2;
248                                splice_one(&mut tokens, index3 + 1, count, range_query);
249                                stack.pop();
250                                stack.pop();
251                            }
252                        }
253                        let top_t = stack.last().map(|&s| t(s));
254                        if top_t.is_some_and(|s| mFGT.contains(&s) || mFLT.contains(&s) || s == EnumToken::DelimTokenType || s == EnumToken::ColonTokenType) {
255                            let op = *stack.last().unwrap();
256                            let index2 = index_of(&tokens, Some(op));
257                            let index3 = index_of(&tokens, if stack.len() >= 2 { Some(stack[stack.len() - 2]) } else { None });
258                            let names = trimmed(arena, &slice(&tokens, index3 + 1, index2));
259                            let mut values = trimmed(arena, &slice(&tokens, index2 + 1, tokens.len() as isize - 1));
260                            let filtered_names: Vec<u32> = names.iter().copied().filter(|&n| !is_ws(arena, n)).collect();
261                            let name = filtered_names.first().map_or(String::new(), |&n| arena.resolve_string(arena.string_value.get(n)).to_string());
262                            let info = get_mf_info(&name);
263                            if options.compute_calc_expression == Some(true)
264                                && (info.is_none() || !matches!(mf_type(info), Some(MediaFeatureType::KeywordType) | Some(MediaFeatureType::StringType)))
265                            {
266                                evaluate_calc(arena, &mut values);
267                            }
268                            let is_range = mFGT.contains(&t(op)) || mFLT.contains(&t(op)) || t(op) == EnumToken::DelimTokenType;
269                            let mf_value = is_mf_value(arena, &name, &values, is_range);
270                            if !mf_value.success {
271                                success = false;
272                                let message = if mf_value.is_value_allowed == Some(false) { "invalid <mf-name>" } else { "expected <mf-value>" };
273                                let node = values.first().copied().unwrap_or(0);
274                                errors.push(drop_error(arena, message.into(), node, options));
275                                break 'sw;
276                            }
277                            if mf_type(info) == Some(MediaFeatureType::RatioType) {
278                                reduce_ratio(arena, &mut values, options);
279                            }
280                            if t(op) == EnumToken::ColonTokenType {
281                                if let Some(rest) = name.strip_prefix("min-") {
282                                    arena.string_value.set(filtered_names[0], arena.intern_string(rest));
283                                    arena.data_types.set(op, EnumToken::GteTokenType);
284                                } else if let Some(rest) = name.strip_prefix("max-") {
285                                    arena.string_value.set(filtered_names[0], arena.intern_string(rest));
286                                    arena.data_types.set(op, EnumToken::LteTokenType);
287                                }
288                            }
289                            let condition = arena.create_token(EnumToken::MediaQueryConditionTokenType, TokenValue::None, None);
290                            arena.set_token_list(arena.field_list(condition, TokenField::L), &names);
291                            let op = stack.pop().unwrap();
292                            arena.set_token_list(arena.field_list(condition, TokenField::Op), &[op]);
293                            arena.set_token_list(arena.field_list(condition, TokenField::R), &values);
294                            if !names.is_empty() && !values.is_empty() {
295                                arena.span_location(condition, names[0], *values.last().unwrap());
296                            }
297                            let count = tokens.len() as isize - index3 - 2;
298                            splice_one(&mut tokens, index3 + 1, count, condition);
299                        }
300                        if stack.is_empty() {
301                            success = false;
302                            errors.push(drop_error(arena, "unmatched ')'".into(), current, options));
303                            break 'sw;
304                        }
305                        let index = index_of(&tokens, stack.last().copied());
306                        let parens = tokens[index as usize];
307                        arena.data_types.set(parens, EnumToken::ParensTokenType);
308                        let inner = slice(&tokens, index + 1, tokens.len() as isize - 1);
309                        arena.set_token_list(parens, &inner);
310                        arena.span_location(parens, parens, current);
311                        tokens.truncate(index as usize + 1);
312                        scopes.pop();
313                        stack.pop();
314                        if stack.last().is_some_and(|&s| matches!(t(s), EnumToken::AndTokenType | EnumToken::OrTokenType)) {
315                            let index = index_of(&tokens, stack.last().copied());
316                            let mut l = index - 1;
317                            while l > 0 && is_ws(arena, tokens[l as usize]) {
318                                l -= 1;
319                            }
320                            let left = trimmed(arena, &slice(&tokens, l, index));
321                            let right = trimmed(arena, &slice(&tokens, index + 1, tokens.len() as isize));
322                            let op = stack.pop().unwrap();
323                            let condition = arena.create_token(EnumToken::MediaQueryConditionTokenType, TokenValue::None, None);
324                            arena.set_token_list(arena.field_list(condition, TokenField::Op), &[op]);
325                            arena.set_token_list(arena.field_list(condition, TokenField::L), &left);
326                            arena.set_token_list(arena.field_list(condition, TokenField::R), &right);
327                            if !left.is_empty() && !right.is_empty() {
328                                arena.span_location(condition, left[0], *right.last().unwrap());
329                            }
330                            let l = l.max(0) as usize;
331                            if l < tokens.len() {
332                                tokens[l] = condition;
333                            } else {
334                                tokens.push(condition);
335                            }
336                            tokens.truncate(l + 1);
337                            if options.minify == Some(true) && t(op) == EnumToken::AndTokenType {
338                                let single = |side: &Vec<u32>| {
339                                    (side.len() == 1 && t(side[0]) == EnumToken::ParensTokenType && arena.token_count(side[0]) == 1)
340                                        .then(|| arena.first_token.get(side[0]))
341                                };
342                                if let (Some(lc), Some(rc)) = (single(&left), single(&right)) {
343                                    if t(lc) == EnumToken::MediaQueryConditionTokenType && t(rc) == EnumToken::MediaQueryConditionTokenType {
344                                        let left_names = arena.field_tokens(lc, TokenField::L);
345                                        let right_names = arena.field_tokens(rc, TokenField::L);
346                                        let left_op = arena.field(lc, TokenField::Op);
347                                        let right_op = arena.field(rc, TokenField::Op);
348                                        if left_names.len() == 1
349                                            && t(left_names[0]) == EnumToken::IdenTokenType
350                                            && matches!(t(left_op), EnumToken::GtTokenType | EnumToken::GteTokenType)
351                                            && right_names.len() == 1
352                                            && t(right_names[0]) == EnumToken::IdenTokenType
353                                            && matches!(t(right_op), EnumToken::LtTokenType | EnumToken::LteTokenType)
354                                            && equals_ignore_case(
355                                                &arena.resolve_string(arena.string_value.get(left_names[0])),
356                                                &arena.resolve_string(arena.string_value.get(right_names[0])),
357                                            )
358                                        {
359                                            let range_query = arena.create_token(EnumToken::MediaRangeQueryTokenType, TokenValue::None, None);
360                                            arena.data_types.set(
361                                                left_op,
362                                                if t(left_op) == EnumToken::GteTokenType { EnumToken::LteTokenType } else { EnumToken::LtTokenType },
363                                            );
364                                            arena.set_token_list(arena.field_list(range_query, TokenField::L), &arena.field_tokens(lc, TokenField::R));
365                                            arena.set_token_list(arena.field_list(range_query, TokenField::Val), &left_names);
366                                            arena.set_token_list(arena.field_list(range_query, TokenField::Op), &[left_op]);
367                                            arena.set_token_list(arena.field_list(range_query, TokenField::Op2), &[right_op]);
368                                            arena.set_token_list(arena.field_list(range_query, TokenField::R), &arena.field_tokens(rc, TokenField::R));
369                                            arena.span_location(range_query, left[0], *right.last().unwrap());
370                                            let parens = arena.create_token(EnumToken::ParensTokenType, TokenValue::None, None);
371                                            arena.set_token_list(parens, &[range_query]);
372                                            arena.copy_location(parens, range_query);
373                                            tokens[l] = parens;
374                                        }
375                                    }
376                                }
377                            }
378                        }
379                    }
380                    _ => {}
381                }
382            }
383            if !success {
384                break;
385            }
386            i += 1;
387        }
388        if !success {
389            has_errors = true;
390        } else {
391            trim_array(arena, &mut tokens);
392            kept.push(tokens);
393        }
394    }
395    stream.clear();
396    let mut has_part = false;
397    for part in kept {
398        if part.is_empty() {
399            continue;
400        }
401        if has_part {
402            stream.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
403        }
404        stream.extend(part);
405        has_part = true;
406    }
407    let success = !has_errors
408        || stream.iter().any(|&t0| !matches!(t(t0), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::CommaTokenType));
409    (success, errors)
410}